Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ adfa3b26

History | View | Annotate | Download (442.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

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

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

    
64

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

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

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

    
77

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

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

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

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

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

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

    
99

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

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

113
  Note that all commands require root permissions.
114

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

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

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

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

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

    
155
    # Tasklets
156
    self.tasklets = None
157

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

    
161
    self.CheckArguments()
162

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

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

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

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

178
    """
179
    pass
180

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

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

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

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

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

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

206
    Examples::
207

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

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

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

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

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

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

245
    """
246

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

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

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

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

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

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

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

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

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

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

297
    """
298
    raise NotImplementedError
299

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

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

311
    """
312
    raise NotImplementedError
313

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
400
    del self.recalculate_locks[locking.LEVEL_NODE]
401

    
402

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

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

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

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

416
    This just raises an error.
417

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

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

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

    
427

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

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

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

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

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

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

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

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

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

460
    """
461
    pass
462

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

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

470
    """
471
    raise NotImplementedError
472

    
473

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

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

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

484
    """
485
    self.use_locking = use_locking
486

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

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

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

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

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

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

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

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

    
521
    # Return expanded names
522
    return self.wanted
523

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

527
    See L{LogicalUnit.ExpandNames}.
528

529
    """
530
    raise NotImplementedError()
531

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

535
    See L{LogicalUnit.DeclareLocks}.
536

537
    """
538
    raise NotImplementedError()
539

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

543
    @return: Query data object
544

545
    """
546
    raise NotImplementedError()
547

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

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

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

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

    
562

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

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

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

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

    
580

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

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

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

    
600

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

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

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

    
633

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

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

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

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

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

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

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

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

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

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

    
678

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

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

    
690

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

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

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

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

    
709

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

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

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

    
724

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

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

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

    
739

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

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

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

    
752

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

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

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

    
765

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

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

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

    
783

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

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

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

    
810

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

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

    
818

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

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

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

    
834

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

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

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

    
851

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

    
856

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

    
861

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

867
  This builds the hook environment from individual variables.
868

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

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

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

    
931
  env["INSTANCE_NIC_COUNT"] = nic_count
932

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

    
941
  env["INSTANCE_DISK_COUNT"] = disk_count
942

    
943
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
944
    for key, value in source.items():
945
      env["INSTANCE_%s_%s" % (kind, key)] = value
946

    
947
  return env
948

    
949

    
950
def _NICListToTuple(lu, nics):
951
  """Build a list of nic information tuples.
952

953
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
954
  value in LUInstanceQueryData.
955

956
  @type lu:  L{LogicalUnit}
957
  @param lu: the logical unit on whose behalf we execute
958
  @type nics: list of L{objects.NIC}
959
  @param nics: list of nics to convert to hooks tuples
960

961
  """
962
  hooks_nics = []
963
  cluster = lu.cfg.GetClusterInfo()
964
  for nic in nics:
965
    ip = nic.ip
966
    mac = nic.mac
967
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
968
    mode = filled_params[constants.NIC_MODE]
969
    link = filled_params[constants.NIC_LINK]
970
    hooks_nics.append((ip, mac, mode, link))
971
  return hooks_nics
972

    
973

    
974
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
975
  """Builds instance related env variables for hooks from an object.
976

977
  @type lu: L{LogicalUnit}
978
  @param lu: the logical unit on whose behalf we execute
979
  @type instance: L{objects.Instance}
980
  @param instance: the instance for which we should build the
981
      environment
982
  @type override: dict
983
  @param override: dictionary with key/values that will override
984
      our values
985
  @rtype: dict
986
  @return: the hook environment dictionary
987

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

    
1011

    
1012
def _AdjustCandidatePool(lu, exceptions):
1013
  """Adjust the candidate pool after node operations.
1014

1015
  """
1016
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1017
  if mod_list:
1018
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1019
               utils.CommaJoin(node.name for node in mod_list))
1020
    for name in mod_list:
1021
      lu.context.ReaddNode(name)
1022
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1023
  if mc_now > mc_max:
1024
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1025
               (mc_now, mc_max))
1026

    
1027

    
1028
def _DecideSelfPromotion(lu, exceptions=None):
1029
  """Decide whether I should promote myself as a master candidate.
1030

1031
  """
1032
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1033
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1034
  # the new node will increase mc_max with one, so:
1035
  mc_should = min(mc_should + 1, cp_size)
1036
  return mc_now < mc_should
1037

    
1038

    
1039
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1040
  """Check that the brigdes needed by a list of nics exist.
1041

1042
  """
1043
  cluster = lu.cfg.GetClusterInfo()
1044
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1045
  brlist = [params[constants.NIC_LINK] for params in paramslist
1046
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1047
  if brlist:
1048
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1049
    result.Raise("Error checking bridges on destination node '%s'" %
1050
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1051

    
1052

    
1053
def _CheckInstanceBridgesExist(lu, instance, node=None):
1054
  """Check that the brigdes needed by an instance exist.
1055

1056
  """
1057
  if node is None:
1058
    node = instance.primary_node
1059
  _CheckNicsBridgesExist(lu, instance.nics, node)
1060

    
1061

    
1062
def _CheckOSVariant(os_obj, name):
1063
  """Check whether an OS name conforms to the os variants specification.
1064

1065
  @type os_obj: L{objects.OS}
1066
  @param os_obj: OS object to check
1067
  @type name: string
1068
  @param name: OS name passed by the user, to check for validity
1069

1070
  """
1071
  if not os_obj.supported_variants:
1072
    return
1073
  variant = objects.OS.GetVariant(name)
1074
  if not variant:
1075
    raise errors.OpPrereqError("OS name must include a variant",
1076
                               errors.ECODE_INVAL)
1077

    
1078
  if variant not in os_obj.supported_variants:
1079
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1080

    
1081

    
1082
def _GetNodeInstancesInner(cfg, fn):
1083
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1084

    
1085

    
1086
def _GetNodeInstances(cfg, node_name):
1087
  """Returns a list of all primary and secondary instances on a node.
1088

1089
  """
1090

    
1091
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1092

    
1093

    
1094
def _GetNodePrimaryInstances(cfg, node_name):
1095
  """Returns primary instances on a node.
1096

1097
  """
1098
  return _GetNodeInstancesInner(cfg,
1099
                                lambda inst: node_name == inst.primary_node)
1100

    
1101

    
1102
def _GetNodeSecondaryInstances(cfg, node_name):
1103
  """Returns secondary instances on a node.
1104

1105
  """
1106
  return _GetNodeInstancesInner(cfg,
1107
                                lambda inst: node_name in inst.secondary_nodes)
1108

    
1109

    
1110
def _GetStorageTypeArgs(cfg, storage_type):
1111
  """Returns the arguments for a storage type.
1112

1113
  """
1114
  # Special case for file storage
1115
  if storage_type == constants.ST_FILE:
1116
    # storage.FileStorage wants a list of storage directories
1117
    return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1118

    
1119
  return []
1120

    
1121

    
1122
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1123
  faulty = []
1124

    
1125
  for dev in instance.disks:
1126
    cfg.SetDiskID(dev, node_name)
1127

    
1128
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1129
  result.Raise("Failed to get disk status from node %s" % node_name,
1130
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1131

    
1132
  for idx, bdev_status in enumerate(result.payload):
1133
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1134
      faulty.append(idx)
1135

    
1136
  return faulty
1137

    
1138

    
1139
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1140
  """Check the sanity of iallocator and node arguments and use the
1141
  cluster-wide iallocator if appropriate.
1142

1143
  Check that at most one of (iallocator, node) is specified. If none is
1144
  specified, then the LU's opcode's iallocator slot is filled with the
1145
  cluster-wide default iallocator.
1146

1147
  @type iallocator_slot: string
1148
  @param iallocator_slot: the name of the opcode iallocator slot
1149
  @type node_slot: string
1150
  @param node_slot: the name of the opcode target node slot
1151

1152
  """
1153
  node = getattr(lu.op, node_slot, None)
1154
  iallocator = getattr(lu.op, iallocator_slot, None)
1155

    
1156
  if node is not None and iallocator is not None:
1157
    raise errors.OpPrereqError("Do not specify both, iallocator and node",
1158
                               errors.ECODE_INVAL)
1159
  elif node is None and iallocator is None:
1160
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1161
    if default_iallocator:
1162
      setattr(lu.op, iallocator_slot, default_iallocator)
1163
    else:
1164
      raise errors.OpPrereqError("No iallocator or node given and no"
1165
                                 " cluster-wide default iallocator found;"
1166
                                 " please specify either an iallocator or a"
1167
                                 " node, or set a cluster-wide default"
1168
                                 " iallocator")
1169

    
1170

    
1171
class LUClusterPostInit(LogicalUnit):
1172
  """Logical unit for running hooks after cluster initialization.
1173

1174
  """
1175
  HPATH = "cluster-init"
1176
  HTYPE = constants.HTYPE_CLUSTER
1177

    
1178
  def BuildHooksEnv(self):
1179
    """Build hooks env.
1180

1181
    """
1182
    return {
1183
      "OP_TARGET": self.cfg.GetClusterName(),
1184
      }
1185

    
1186
  def BuildHooksNodes(self):
1187
    """Build hooks nodes.
1188

1189
    """
1190
    return ([], [self.cfg.GetMasterNode()])
1191

    
1192
  def Exec(self, feedback_fn):
1193
    """Nothing to do.
1194

1195
    """
1196
    return True
1197

    
1198

    
1199
class LUClusterDestroy(LogicalUnit):
1200
  """Logical unit for destroying the cluster.
1201

1202
  """
1203
  HPATH = "cluster-destroy"
1204
  HTYPE = constants.HTYPE_CLUSTER
1205

    
1206
  def BuildHooksEnv(self):
1207
    """Build hooks env.
1208

1209
    """
1210
    return {
1211
      "OP_TARGET": self.cfg.GetClusterName(),
1212
      }
1213

    
1214
  def BuildHooksNodes(self):
1215
    """Build hooks nodes.
1216

1217
    """
1218
    return ([], [])
1219

    
1220
  def CheckPrereq(self):
1221
    """Check prerequisites.
1222

1223
    This checks whether the cluster is empty.
1224

1225
    Any errors are signaled by raising errors.OpPrereqError.
1226

1227
    """
1228
    master = self.cfg.GetMasterNode()
1229

    
1230
    nodelist = self.cfg.GetNodeList()
1231
    if len(nodelist) != 1 or nodelist[0] != master:
1232
      raise errors.OpPrereqError("There are still %d node(s) in"
1233
                                 " this cluster." % (len(nodelist) - 1),
1234
                                 errors.ECODE_INVAL)
1235
    instancelist = self.cfg.GetInstanceList()
1236
    if instancelist:
1237
      raise errors.OpPrereqError("There are still %d instance(s) in"
1238
                                 " this cluster." % len(instancelist),
1239
                                 errors.ECODE_INVAL)
1240

    
1241
  def Exec(self, feedback_fn):
1242
    """Destroys the cluster.
1243

1244
    """
1245
    master = self.cfg.GetMasterNode()
1246

    
1247
    # Run post hooks on master node before it's removed
1248
    _RunPostHook(self, master)
1249

    
1250
    result = self.rpc.call_node_stop_master(master, False)
1251
    result.Raise("Could not disable the master role")
1252

    
1253
    return master
1254

    
1255

    
1256
def _VerifyCertificate(filename):
1257
  """Verifies a certificate for LUClusterVerifyConfig.
1258

1259
  @type filename: string
1260
  @param filename: Path to PEM file
1261

1262
  """
1263
  try:
1264
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1265
                                           utils.ReadFile(filename))
1266
  except Exception, err: # pylint: disable-msg=W0703
1267
    return (LUClusterVerifyConfig.ETYPE_ERROR,
1268
            "Failed to load X509 certificate %s: %s" % (filename, err))
1269

    
1270
  (errcode, msg) = \
1271
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1272
                                constants.SSL_CERT_EXPIRATION_ERROR)
1273

    
1274
  if msg:
1275
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1276
  else:
1277
    fnamemsg = None
1278

    
1279
  if errcode is None:
1280
    return (None, fnamemsg)
1281
  elif errcode == utils.CERT_WARNING:
1282
    return (LUClusterVerifyConfig.ETYPE_WARNING, fnamemsg)
1283
  elif errcode == utils.CERT_ERROR:
1284
    return (LUClusterVerifyConfig.ETYPE_ERROR, fnamemsg)
1285

    
1286
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1287

    
1288

    
1289
def _GetAllHypervisorParameters(cluster, instances):
1290
  """Compute the set of all hypervisor parameters.
1291

1292
  @type cluster: L{objects.Cluster}
1293
  @param cluster: the cluster object
1294
  @param instances: list of L{objects.Instance}
1295
  @param instances: additional instances from which to obtain parameters
1296
  @rtype: list of (origin, hypervisor, parameters)
1297
  @return: a list with all parameters found, indicating the hypervisor they
1298
       apply to, and the origin (can be "cluster", "os X", or "instance Y")
1299

1300
  """
1301
  hvp_data = []
1302

    
1303
  for hv_name in cluster.enabled_hypervisors:
1304
    hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
1305

    
1306
  for os_name, os_hvp in cluster.os_hvp.items():
1307
    for hv_name, hv_params in os_hvp.items():
1308
      if hv_params:
1309
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
1310
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
1311

    
1312
  # TODO: collapse identical parameter values in a single one
1313
  for instance in instances:
1314
    if instance.hvparams:
1315
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
1316
                       cluster.FillHV(instance)))
1317

    
1318
  return hvp_data
1319

    
1320

    
1321
class _VerifyErrors(object):
1322
  """Mix-in for cluster/group verify LUs.
1323

1324
  It provides _Error and _ErrorIf, and updates the self.bad boolean. (Expects
1325
  self.op and self._feedback_fn to be available.)
1326

1327
  """
1328
  TCLUSTER = "cluster"
1329
  TNODE = "node"
1330
  TINSTANCE = "instance"
1331

    
1332
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1333
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1334
  ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1335
  ECLUSTERDANGLINGNODES = (TNODE, "ECLUSTERDANGLINGNODES")
1336
  ECLUSTERDANGLINGINST = (TNODE, "ECLUSTERDANGLINGINST")
1337
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1338
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1339
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1340
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1341
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1342
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1343
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1344
  ENODEDRBD = (TNODE, "ENODEDRBD")
1345
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1346
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1347
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1348
  ENODEHV = (TNODE, "ENODEHV")
1349
  ENODELVM = (TNODE, "ENODELVM")
1350
  ENODEN1 = (TNODE, "ENODEN1")
1351
  ENODENET = (TNODE, "ENODENET")
1352
  ENODEOS = (TNODE, "ENODEOS")
1353
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1354
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1355
  ENODERPC = (TNODE, "ENODERPC")
1356
  ENODESSH = (TNODE, "ENODESSH")
1357
  ENODEVERSION = (TNODE, "ENODEVERSION")
1358
  ENODESETUP = (TNODE, "ENODESETUP")
1359
  ENODETIME = (TNODE, "ENODETIME")
1360
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1361

    
1362
  ETYPE_FIELD = "code"
1363
  ETYPE_ERROR = "ERROR"
1364
  ETYPE_WARNING = "WARNING"
1365

    
1366
  def _Error(self, ecode, item, msg, *args, **kwargs):
1367
    """Format an error message.
1368

1369
    Based on the opcode's error_codes parameter, either format a
1370
    parseable error code, or a simpler error string.
1371

1372
    This must be called only from Exec and functions called from Exec.
1373

1374
    """
1375
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1376
    itype, etxt = ecode
1377
    # first complete the msg
1378
    if args:
1379
      msg = msg % args
1380
    # then format the whole message
1381
    if self.op.error_codes: # This is a mix-in. pylint: disable-msg=E1101
1382
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1383
    else:
1384
      if item:
1385
        item = " " + item
1386
      else:
1387
        item = ""
1388
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1389
    # and finally report it via the feedback_fn
1390
    self._feedback_fn("  - %s" % msg) # Mix-in. pylint: disable-msg=E1101
1391

    
1392
  def _ErrorIf(self, cond, *args, **kwargs):
1393
    """Log an error message if the passed condition is True.
1394

1395
    """
1396
    cond = (bool(cond)
1397
            or self.op.debug_simulate_errors) # pylint: disable-msg=E1101
1398
    if cond:
1399
      self._Error(*args, **kwargs)
1400
    # do not mark the operation as failed for WARN cases only
1401
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1402
      self.bad = self.bad or cond
1403

    
1404

    
1405
class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1406
  """Verifies the cluster config.
1407

1408
  """
1409

    
1410
  REQ_BGL = False
1411

    
1412
  def _VerifyHVP(self, hvp_data):
1413
    """Verifies locally the syntax of the hypervisor parameters.
1414

1415
    """
1416
    for item, hv_name, hv_params in hvp_data:
1417
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
1418
             (item, hv_name))
1419
      try:
1420
        hv_class = hypervisor.GetHypervisor(hv_name)
1421
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1422
        hv_class.CheckParameterSyntax(hv_params)
1423
      except errors.GenericError, err:
1424
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
1425

    
1426
  def ExpandNames(self):
1427
    self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1428
    self.all_node_info = self.cfg.GetAllNodesInfo()
1429
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1430
    self.needed_locks = {}
1431

    
1432
  def Exec(self, feedback_fn):
1433
    """Verify integrity of cluster, performing various test on nodes.
1434

1435
    """
1436
    self.bad = False
1437
    self._feedback_fn = feedback_fn
1438

    
1439
    feedback_fn("* Verifying cluster config")
1440

    
1441
    for msg in self.cfg.VerifyConfig():
1442
      self._ErrorIf(True, self.ECLUSTERCFG, None, msg)
1443

    
1444
    feedback_fn("* Verifying cluster certificate files")
1445

    
1446
    for cert_filename in constants.ALL_CERT_FILES:
1447
      (errcode, msg) = _VerifyCertificate(cert_filename)
1448
      self._ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1449

    
1450
    feedback_fn("* Verifying hypervisor parameters")
1451

    
1452
    self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1453
                                                self.all_inst_info.values()))
1454

    
1455
    feedback_fn("* Verifying all nodes belong to an existing group")
1456

    
1457
    # We do this verification here because, should this bogus circumstance
1458
    # occur, it would never be catched by VerifyGroup, which only acts on
1459
    # nodes/instances reachable from existing node groups.
1460

    
1461
    dangling_nodes = set(node.name for node in self.all_node_info.values()
1462
                         if node.group not in self.all_group_info)
1463

    
1464
    dangling_instances = {}
1465
    no_node_instances = []
1466

    
1467
    for inst in self.all_inst_info.values():
1468
      if inst.primary_node in dangling_nodes:
1469
        dangling_instances.setdefault(inst.primary_node, []).append(inst.name)
1470
      elif inst.primary_node not in self.all_node_info:
1471
        no_node_instances.append(inst.name)
1472

    
1473
    pretty_dangling = [
1474
        "%s (%s)" %
1475
        (node.name,
1476
         utils.CommaJoin(dangling_instances.get(node.name,
1477
                                                ["no instances"])))
1478
        for node in dangling_nodes]
1479

    
1480
    self._ErrorIf(bool(dangling_nodes), self.ECLUSTERDANGLINGNODES, None,
1481
                  "the following nodes (and their instances) belong to a non"
1482
                  " existing group: %s", utils.CommaJoin(pretty_dangling))
1483

    
1484
    self._ErrorIf(bool(no_node_instances), self.ECLUSTERDANGLINGINST, None,
1485
                  "the following instances have a non-existing primary-node:"
1486
                  " %s", utils.CommaJoin(no_node_instances))
1487

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

    
1490

    
1491
class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1492
  """Verifies the status of a node group.
1493

1494
  """
1495

    
1496
  HPATH = "cluster-verify"
1497
  HTYPE = constants.HTYPE_CLUSTER
1498
  REQ_BGL = False
1499

    
1500
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1501

    
1502
  class NodeImage(object):
1503
    """A class representing the logical and physical status of a node.
1504

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

1533
    """
1534
    def __init__(self, offline=False, name=None, vm_capable=True):
1535
      self.name = name
1536
      self.volumes = {}
1537
      self.instances = []
1538
      self.pinst = []
1539
      self.sinst = []
1540
      self.sbp = {}
1541
      self.mfree = 0
1542
      self.dfree = 0
1543
      self.offline = offline
1544
      self.vm_capable = vm_capable
1545
      self.rpc_fail = False
1546
      self.lvm_fail = False
1547
      self.hyp_fail = False
1548
      self.ghost = False
1549
      self.os_fail = False
1550
      self.oslist = {}
1551

    
1552
  def ExpandNames(self):
1553
    # This raises errors.OpPrereqError on its own:
1554
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1555

    
1556
    all_node_info = self.cfg.GetAllNodesInfo()
1557
    all_inst_info = self.cfg.GetAllInstancesInfo()
1558

    
1559
    node_names = set(node.name
1560
                     for node in all_node_info.values()
1561
                     if node.group == self.group_uuid)
1562

    
1563
    inst_names = [inst.name
1564
                  for inst in all_inst_info.values()
1565
                  if inst.primary_node in node_names]
1566

    
1567
    # In Exec(), we warn about mirrored instances that have primary and
1568
    # secondary living in separate node groups. To fully verify that
1569
    # volumes for these instances are healthy, we will need to do an
1570
    # extra call to their secondaries. We ensure here those nodes will
1571
    # be locked.
1572
    for inst in inst_names:
1573
      if all_inst_info[inst].disk_template in constants.DTS_INT_MIRROR:
1574
        node_names.update(all_inst_info[inst].secondary_nodes)
1575

    
1576
    self.needed_locks = {
1577
      locking.LEVEL_NODEGROUP: [self.group_uuid],
1578
      locking.LEVEL_NODE: list(node_names),
1579
      locking.LEVEL_INSTANCE: inst_names,
1580
    }
1581

    
1582
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1583

    
1584
  def CheckPrereq(self):
1585
    self.all_node_info = self.cfg.GetAllNodesInfo()
1586
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1587

    
1588
    group_nodes = set(node.name
1589
                      for node in self.all_node_info.values()
1590
                      if node.group == self.group_uuid)
1591

    
1592
    group_instances = set(inst.name
1593
                          for inst in self.all_inst_info.values()
1594
                          if inst.primary_node in group_nodes)
1595

    
1596
    unlocked_nodes = \
1597
        group_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1598

    
1599
    unlocked_instances = \
1600
        group_instances.difference(self.glm.list_owned(locking.LEVEL_INSTANCE))
1601

    
1602
    if unlocked_nodes:
1603
      raise errors.OpPrereqError("missing lock for nodes: %s" %
1604
                                 utils.CommaJoin(unlocked_nodes))
1605

    
1606
    if unlocked_instances:
1607
      raise errors.OpPrereqError("missing lock for instances: %s" %
1608
                                 utils.CommaJoin(unlocked_instances))
1609

    
1610
    self.my_node_names = utils.NiceSort(group_nodes)
1611
    self.my_inst_names = utils.NiceSort(group_instances)
1612

    
1613
    self.my_node_info = dict((name, self.all_node_info[name])
1614
                             for name in self.my_node_names)
1615

    
1616
    self.my_inst_info = dict((name, self.all_inst_info[name])
1617
                             for name in self.my_inst_names)
1618

    
1619
    # We detect here the nodes that will need the extra RPC calls for verifying
1620
    # split LV volumes; they should be locked.
1621
    extra_lv_nodes = set()
1622

    
1623
    for inst in self.my_inst_info.values():
1624
      if inst.disk_template in constants.DTS_INT_MIRROR:
1625
        group = self.my_node_info[inst.primary_node].group
1626
        for nname in inst.secondary_nodes:
1627
          if self.all_node_info[nname].group != group:
1628
            extra_lv_nodes.add(nname)
1629

    
1630
    unlocked_lv_nodes = \
1631
        extra_lv_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1632

    
1633
    if unlocked_lv_nodes:
1634
      raise errors.OpPrereqError("these nodes could be locked: %s" %
1635
                                 utils.CommaJoin(unlocked_lv_nodes))
1636
    self.extra_lv_nodes = list(extra_lv_nodes)
1637

    
1638
  def _VerifyNode(self, ninfo, nresult):
1639
    """Perform some basic validation on data returned from a node.
1640

1641
      - check the result data structure is well formed and has all the
1642
        mandatory fields
1643
      - check ganeti version
1644

1645
    @type ninfo: L{objects.Node}
1646
    @param ninfo: the node to check
1647
    @param nresult: the results from the node
1648
    @rtype: boolean
1649
    @return: whether overall this call was successful (and we can expect
1650
         reasonable values in the respose)
1651

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

    
1656
    # main result, nresult should be a non-empty dict
1657
    test = not nresult or not isinstance(nresult, dict)
1658
    _ErrorIf(test, self.ENODERPC, node,
1659
                  "unable to verify node: no data returned")
1660
    if test:
1661
      return False
1662

    
1663
    # compares ganeti version
1664
    local_version = constants.PROTOCOL_VERSION
1665
    remote_version = nresult.get("version", None)
1666
    test = not (remote_version and
1667
                isinstance(remote_version, (list, tuple)) and
1668
                len(remote_version) == 2)
1669
    _ErrorIf(test, self.ENODERPC, node,
1670
             "connection to node returned invalid data")
1671
    if test:
1672
      return False
1673

    
1674
    test = local_version != remote_version[0]
1675
    _ErrorIf(test, self.ENODEVERSION, node,
1676
             "incompatible protocol versions: master %s,"
1677
             " node %s", local_version, remote_version[0])
1678
    if test:
1679
      return False
1680

    
1681
    # node seems compatible, we can actually try to look into its results
1682

    
1683
    # full package version
1684
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1685
                  self.ENODEVERSION, node,
1686
                  "software version mismatch: master %s, node %s",
1687
                  constants.RELEASE_VERSION, remote_version[1],
1688
                  code=self.ETYPE_WARNING)
1689

    
1690
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1691
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1692
      for hv_name, hv_result in hyp_result.iteritems():
1693
        test = hv_result is not None
1694
        _ErrorIf(test, self.ENODEHV, node,
1695
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1696

    
1697
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1698
    if ninfo.vm_capable and isinstance(hvp_result, list):
1699
      for item, hv_name, hv_result in hvp_result:
1700
        _ErrorIf(True, self.ENODEHV, node,
1701
                 "hypervisor %s parameter verify failure (source %s): %s",
1702
                 hv_name, item, hv_result)
1703

    
1704
    test = nresult.get(constants.NV_NODESETUP,
1705
                       ["Missing NODESETUP results"])
1706
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1707
             "; ".join(test))
1708

    
1709
    return True
1710

    
1711
  def _VerifyNodeTime(self, ninfo, nresult,
1712
                      nvinfo_starttime, nvinfo_endtime):
1713
    """Check the node time.
1714

1715
    @type ninfo: L{objects.Node}
1716
    @param ninfo: the node to check
1717
    @param nresult: the remote results for the node
1718
    @param nvinfo_starttime: the start time of the RPC call
1719
    @param nvinfo_endtime: the end time of the RPC call
1720

1721
    """
1722
    node = ninfo.name
1723
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1724

    
1725
    ntime = nresult.get(constants.NV_TIME, None)
1726
    try:
1727
      ntime_merged = utils.MergeTime(ntime)
1728
    except (ValueError, TypeError):
1729
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1730
      return
1731

    
1732
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1733
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1734
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1735
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1736
    else:
1737
      ntime_diff = None
1738

    
1739
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1740
             "Node time diverges by at least %s from master node time",
1741
             ntime_diff)
1742

    
1743
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1744
    """Check the node LVM results.
1745

1746
    @type ninfo: L{objects.Node}
1747
    @param ninfo: the node to check
1748
    @param nresult: the remote results for the node
1749
    @param vg_name: the configured VG name
1750

1751
    """
1752
    if vg_name is None:
1753
      return
1754

    
1755
    node = ninfo.name
1756
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1757

    
1758
    # checks vg existence and size > 20G
1759
    vglist = nresult.get(constants.NV_VGLIST, None)
1760
    test = not vglist
1761
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1762
    if not test:
1763
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1764
                                            constants.MIN_VG_SIZE)
1765
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1766

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

    
1780
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1781
    """Check the node bridges.
1782

1783
    @type ninfo: L{objects.Node}
1784
    @param ninfo: the node to check
1785
    @param nresult: the remote results for the node
1786
    @param bridges: the expected list of bridges
1787

1788
    """
1789
    if not bridges:
1790
      return
1791

    
1792
    node = ninfo.name
1793
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1794

    
1795
    missing = nresult.get(constants.NV_BRIDGES, None)
1796
    test = not isinstance(missing, list)
1797
    _ErrorIf(test, self.ENODENET, node,
1798
             "did not return valid bridge information")
1799
    if not test:
1800
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1801
               utils.CommaJoin(sorted(missing)))
1802

    
1803
  def _VerifyNodeNetwork(self, ninfo, nresult):
1804
    """Check the node network connectivity results.
1805

1806
    @type ninfo: L{objects.Node}
1807
    @param ninfo: the node to check
1808
    @param nresult: the remote results for the node
1809

1810
    """
1811
    node = ninfo.name
1812
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1813

    
1814
    test = constants.NV_NODELIST not in nresult
1815
    _ErrorIf(test, self.ENODESSH, node,
1816
             "node hasn't returned node ssh connectivity data")
1817
    if not test:
1818
      if nresult[constants.NV_NODELIST]:
1819
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1820
          _ErrorIf(True, self.ENODESSH, node,
1821
                   "ssh communication with node '%s': %s", a_node, a_msg)
1822

    
1823
    test = constants.NV_NODENETTEST not in nresult
1824
    _ErrorIf(test, self.ENODENET, node,
1825
             "node hasn't returned node tcp connectivity data")
1826
    if not test:
1827
      if nresult[constants.NV_NODENETTEST]:
1828
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1829
        for anode in nlist:
1830
          _ErrorIf(True, self.ENODENET, node,
1831
                   "tcp communication with node '%s': %s",
1832
                   anode, nresult[constants.NV_NODENETTEST][anode])
1833

    
1834
    test = constants.NV_MASTERIP not in nresult
1835
    _ErrorIf(test, self.ENODENET, node,
1836
             "node hasn't returned node master IP reachability data")
1837
    if not test:
1838
      if not nresult[constants.NV_MASTERIP]:
1839
        if node == self.master_node:
1840
          msg = "the master node cannot reach the master IP (not configured?)"
1841
        else:
1842
          msg = "cannot reach the master IP"
1843
        _ErrorIf(True, self.ENODENET, node, msg)
1844

    
1845
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1846
                      diskstatus):
1847
    """Verify an instance.
1848

1849
    This function checks to see if the required block devices are
1850
    available on the instance's node.
1851

1852
    """
1853
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1854
    node_current = instanceconfig.primary_node
1855

    
1856
    node_vol_should = {}
1857
    instanceconfig.MapLVsByNode(node_vol_should)
1858

    
1859
    for node in node_vol_should:
1860
      n_img = node_image[node]
1861
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1862
        # ignore missing volumes on offline or broken nodes
1863
        continue
1864
      for volume in node_vol_should[node]:
1865
        test = volume not in n_img.volumes
1866
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1867
                 "volume %s missing on node %s", volume, node)
1868

    
1869
    if instanceconfig.admin_up:
1870
      pri_img = node_image[node_current]
1871
      test = instance not in pri_img.instances and not pri_img.offline
1872
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1873
               "instance not running on its primary node %s",
1874
               node_current)
1875

    
1876
    diskdata = [(nname, success, status, idx)
1877
                for (nname, disks) in diskstatus.items()
1878
                for idx, (success, status) in enumerate(disks)]
1879

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

    
1894
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1895
    """Verify if there are any unknown volumes in the cluster.
1896

1897
    The .os, .swap and backup volumes are ignored. All other volumes are
1898
    reported as unknown.
1899

1900
    @type reserved: L{ganeti.utils.FieldSet}
1901
    @param reserved: a FieldSet of reserved volume names
1902

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

    
1915
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1916
    """Verify N+1 Memory Resilience.
1917

1918
    Check that if one single node dies we can still start all the
1919
    instances it was primary for.
1920

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

    
1950
  @classmethod
1951
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1952
                   (files_all, files_all_opt, files_mc, files_vm)):
1953
    """Verifies file checksums collected from all nodes.
1954

1955
    @param errorif: Callback for reporting errors
1956
    @param nodeinfo: List of L{objects.Node} objects
1957
    @param master_node: Name of master node
1958
    @param all_nvinfo: RPC results
1959

1960
    """
1961
    node_names = frozenset(node.name for node in nodeinfo)
1962

    
1963
    assert master_node in node_names
1964
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1965
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1966
           "Found file listed in more than one file list"
1967

    
1968
    # Define functions determining which nodes to consider for a file
1969
    file2nodefn = dict([(filename, fn)
1970
      for (files, fn) in [(files_all, None),
1971
                          (files_all_opt, None),
1972
                          (files_mc, lambda node: (node.master_candidate or
1973
                                                   node.name == master_node)),
1974
                          (files_vm, lambda node: node.vm_capable)]
1975
      for filename in files])
1976

    
1977
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1978

    
1979
    for node in nodeinfo:
1980
      nresult = all_nvinfo[node.name]
1981

    
1982
      if nresult.fail_msg or not nresult.payload:
1983
        node_files = None
1984
      else:
1985
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1986

    
1987
      test = not (node_files and isinstance(node_files, dict))
1988
      errorif(test, cls.ENODEFILECHECK, node.name,
1989
              "Node did not return file checksum data")
1990
      if test:
1991
        continue
1992

    
1993
      for (filename, checksum) in node_files.items():
1994
        # Check if the file should be considered for a node
1995
        fn = file2nodefn[filename]
1996
        if fn is None or fn(node):
1997
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
1998

    
1999
    for (filename, checksums) in fileinfo.items():
2000
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
2001

    
2002
      # Nodes having the file
2003
      with_file = frozenset(node_name
2004
                            for nodes in fileinfo[filename].values()
2005
                            for node_name in nodes)
2006

    
2007
      # Nodes missing file
2008
      missing_file = node_names - with_file
2009

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

    
2022
      # See if there are multiple versions of the file
2023
      test = len(checksums) > 1
2024
      if test:
2025
        variants = ["variant %s on %s" %
2026
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
2027
                    for (idx, (checksum, nodes)) in
2028
                      enumerate(sorted(checksums.items()))]
2029
      else:
2030
        variants = []
2031

    
2032
      errorif(test, cls.ECLUSTERFILECHECK, None,
2033
              "File %s found with %s different checksums (%s)",
2034
              filename, len(checksums), "; ".join(variants))
2035

    
2036
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
2037
                      drbd_map):
2038
    """Verifies and the node DRBD status.
2039

2040
    @type ninfo: L{objects.Node}
2041
    @param ninfo: the node to check
2042
    @param nresult: the remote results for the node
2043
    @param instanceinfo: the dict of instances
2044
    @param drbd_helper: the configured DRBD usermode helper
2045
    @param drbd_map: the DRBD map as returned by
2046
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
2047

2048
    """
2049
    node = ninfo.name
2050
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2051

    
2052
    if drbd_helper:
2053
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
2054
      test = (helper_result == None)
2055
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
2056
               "no drbd usermode helper returned")
2057
      if helper_result:
2058
        status, payload = helper_result
2059
        test = not status
2060
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2061
                 "drbd usermode helper check unsuccessful: %s", payload)
2062
        test = status and (payload != drbd_helper)
2063
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2064
                 "wrong drbd usermode helper: %s", payload)
2065

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

    
2081
    # and now check them
2082
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
2083
    test = not isinstance(used_minors, (tuple, list))
2084
    _ErrorIf(test, self.ENODEDRBD, node,
2085
             "cannot parse drbd status file: %s", str(used_minors))
2086
    if test:
2087
      # we cannot check drbd status
2088
      return
2089

    
2090
    for minor, (iname, must_exist) in node_drbd.items():
2091
      test = minor not in used_minors and must_exist
2092
      _ErrorIf(test, self.ENODEDRBD, node,
2093
               "drbd minor %d of instance %s is not active", minor, iname)
2094
    for minor in used_minors:
2095
      test = minor not in node_drbd
2096
      _ErrorIf(test, self.ENODEDRBD, node,
2097
               "unallocated drbd minor %d is in use", minor)
2098

    
2099
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
2100
    """Builds the node OS structures.
2101

2102
    @type ninfo: L{objects.Node}
2103
    @param ninfo: the node to check
2104
    @param nresult: the remote results for the node
2105
    @param nimg: the node image object
2106

2107
    """
2108
    node = ninfo.name
2109
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2110

    
2111
    remote_os = nresult.get(constants.NV_OSLIST, None)
2112
    test = (not isinstance(remote_os, list) or
2113
            not compat.all(isinstance(v, list) and len(v) == 7
2114
                           for v in remote_os))
2115

    
2116
    _ErrorIf(test, self.ENODEOS, node,
2117
             "node hasn't returned valid OS data")
2118

    
2119
    nimg.os_fail = test
2120

    
2121
    if test:
2122
      return
2123

    
2124
    os_dict = {}
2125

    
2126
    for (name, os_path, status, diagnose,
2127
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2128

    
2129
      if name not in os_dict:
2130
        os_dict[name] = []
2131

    
2132
      # parameters is a list of lists instead of list of tuples due to
2133
      # JSON lacking a real tuple type, fix it:
2134
      parameters = [tuple(v) for v in parameters]
2135
      os_dict[name].append((os_path, status, diagnose,
2136
                            set(variants), set(parameters), set(api_ver)))
2137

    
2138
    nimg.oslist = os_dict
2139

    
2140
  def _VerifyNodeOS(self, ninfo, nimg, base):
2141
    """Verifies the node OS list.
2142

2143
    @type ninfo: L{objects.Node}
2144
    @param ninfo: the node to check
2145
    @param nimg: the node image object
2146
    @param base: the 'template' node we match against (e.g. from the master)
2147

2148
    """
2149
    node = ninfo.name
2150
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2151

    
2152
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2153

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

    
2189
    # check any missing OSes
2190
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2191
    _ErrorIf(missing, self.ENODEOS, node,
2192
             "OSes present on reference node %s but missing on this node: %s",
2193
             base.name, utils.CommaJoin(missing))
2194

    
2195
  def _VerifyOob(self, ninfo, nresult):
2196
    """Verifies out of band functionality of a node.
2197

2198
    @type ninfo: L{objects.Node}
2199
    @param ninfo: the node to check
2200
    @param nresult: the remote results for the node
2201

2202
    """
2203
    node = ninfo.name
2204
    # We just have to verify the paths on master and/or master candidates
2205
    # as the oob helper is invoked on the master
2206
    if ((ninfo.master_candidate or ninfo.master_capable) and
2207
        constants.NV_OOB_PATHS in nresult):
2208
      for path_result in nresult[constants.NV_OOB_PATHS]:
2209
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2210

    
2211
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2212
    """Verifies and updates the node volume data.
2213

2214
    This function will update a L{NodeImage}'s internal structures
2215
    with data from the remote call.
2216

2217
    @type ninfo: L{objects.Node}
2218
    @param ninfo: the node to check
2219
    @param nresult: the remote results for the node
2220
    @param nimg: the node image object
2221
    @param vg_name: the configured VG name
2222

2223
    """
2224
    node = ninfo.name
2225
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2226

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

    
2240
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2241
    """Verifies and updates the node instance list.
2242

2243
    If the listing was successful, then updates this node's instance
2244
    list. Otherwise, it marks the RPC call as failed for the instance
2245
    list key.
2246

2247
    @type ninfo: L{objects.Node}
2248
    @param ninfo: the node to check
2249
    @param nresult: the remote results for the node
2250
    @param nimg: the node image object
2251

2252
    """
2253
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2254
    test = not isinstance(idata, list)
2255
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2256
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2257
    if test:
2258
      nimg.hyp_fail = True
2259
    else:
2260
      nimg.instances = idata
2261

    
2262
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2263
    """Verifies and computes a node information map
2264

2265
    @type ninfo: L{objects.Node}
2266
    @param ninfo: the node to check
2267
    @param nresult: the remote results for the node
2268
    @param nimg: the node image object
2269
    @param vg_name: the configured VG name
2270

2271
    """
2272
    node = ninfo.name
2273
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2274

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

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

    
2300
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2301
    """Gets per-disk status information for all instances.
2302

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

2314
    """
2315
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2316

    
2317
    node_disks = {}
2318
    node_disks_devonly = {}
2319
    diskless_instances = set()
2320
    diskless = constants.DT_DISKLESS
2321

    
2322
    for nname in nodelist:
2323
      node_instances = list(itertools.chain(node_image[nname].pinst,
2324
                                            node_image[nname].sinst))
2325
      diskless_instances.update(inst for inst in node_instances
2326
                                if instanceinfo[inst].disk_template == diskless)
2327
      disks = [(inst, disk)
2328
               for inst in node_instances
2329
               for disk in instanceinfo[inst].disks]
2330

    
2331
      if not disks:
2332
        # No need to collect data
2333
        continue
2334

    
2335
      node_disks[nname] = disks
2336

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

    
2341
      for dev in devonly:
2342
        self.cfg.SetDiskID(dev, nname)
2343

    
2344
      node_disks_devonly[nname] = devonly
2345

    
2346
    assert len(node_disks) == len(node_disks_devonly)
2347

    
2348
    # Collect data from all nodes with disks
2349
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2350
                                                          node_disks_devonly)
2351

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

    
2354
    instdisk = {}
2355

    
2356
    for (nname, nres) in result.items():
2357
      disks = node_disks[nname]
2358

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

    
2379
      for ((inst, _), status) in zip(disks, data):
2380
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2381

    
2382
    # Add empty entries for diskless instances.
2383
    for inst in diskless_instances:
2384
      assert inst not in instdisk
2385
      instdisk[inst] = {}
2386

    
2387
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2388
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2389
                      compat.all(isinstance(s, (tuple, list)) and
2390
                                 len(s) == 2 for s in statuses)
2391
                      for inst, nnames in instdisk.items()
2392
                      for nname, statuses in nnames.items())
2393
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2394

    
2395
    return instdisk
2396

    
2397
  def BuildHooksEnv(self):
2398
    """Build hooks env.
2399

2400
    Cluster-Verify hooks just ran in the post phase and their failure makes
2401
    the output be logged in the verify output and the verification to fail.
2402

2403
    """
2404
    env = {
2405
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2406
      }
2407

    
2408
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2409
               for node in self.my_node_info.values())
2410

    
2411
    return env
2412

    
2413
  def BuildHooksNodes(self):
2414
    """Build hooks nodes.
2415

2416
    """
2417
    assert self.my_node_names, ("Node list not gathered,"
2418
      " has CheckPrereq been executed?")
2419
    return ([], self.my_node_names)
2420

    
2421
  def Exec(self, feedback_fn):
2422
    """Verify integrity of the node group, performing various test on nodes.
2423

2424
    """
2425
    # This method has too many local variables. pylint: disable-msg=R0914
2426
    self.bad = False
2427
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2428
    verbose = self.op.verbose
2429
    self._feedback_fn = feedback_fn
2430

    
2431
    vg_name = self.cfg.GetVGName()
2432
    drbd_helper = self.cfg.GetDRBDHelper()
2433
    cluster = self.cfg.GetClusterInfo()
2434
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2435
    hypervisors = cluster.enabled_hypervisors
2436
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2437

    
2438
    i_non_redundant = [] # Non redundant instances
2439
    i_non_a_balanced = [] # Non auto-balanced instances
2440
    n_offline = 0 # Count of offline nodes
2441
    n_drained = 0 # Count of nodes being drained
2442
    node_vol_should = {}
2443

    
2444
    # FIXME: verify OS list
2445

    
2446
    # File verification
2447
    filemap = _ComputeAncillaryFiles(cluster, False)
2448

    
2449
    # do local checksums
2450
    master_node = self.master_node = self.cfg.GetMasterNode()
2451
    master_ip = self.cfg.GetMasterIP()
2452

    
2453
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2454

    
2455
    # We will make nodes contact all nodes in their group, and one node from
2456
    # every other group.
2457
    # TODO: should it be a *random* node, different every time?
2458
    online_nodes = [node.name for node in node_data_list if not node.offline]
2459
    other_group_nodes = {}
2460

    
2461
    for name in sorted(self.all_node_info):
2462
      node = self.all_node_info[name]
2463
      if (node.group not in other_group_nodes
2464
          and node.group != self.group_uuid
2465
          and not node.offline):
2466
        other_group_nodes[node.group] = node.name
2467

    
2468
    node_verify_param = {
2469
      constants.NV_FILELIST:
2470
        utils.UniqueSequence(filename
2471
                             for files in filemap
2472
                             for filename in files),
2473
      constants.NV_NODELIST: online_nodes + other_group_nodes.values(),
2474
      constants.NV_HYPERVISOR: hypervisors,
2475
      constants.NV_HVPARAMS:
2476
        _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2477
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2478
                                 for node in node_data_list
2479
                                 if not node.offline],
2480
      constants.NV_INSTANCELIST: hypervisors,
2481
      constants.NV_VERSION: None,
2482
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2483
      constants.NV_NODESETUP: None,
2484
      constants.NV_TIME: None,
2485
      constants.NV_MASTERIP: (master_node, master_ip),
2486
      constants.NV_OSLIST: None,
2487
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2488
      }
2489

    
2490
    if vg_name is not None:
2491
      node_verify_param[constants.NV_VGLIST] = None
2492
      node_verify_param[constants.NV_LVLIST] = vg_name
2493
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2494
      node_verify_param[constants.NV_DRBDLIST] = None
2495

    
2496
    if drbd_helper:
2497
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2498

    
2499
    # bridge checks
2500
    # FIXME: this needs to be changed per node-group, not cluster-wide
2501
    bridges = set()
2502
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2503
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2504
      bridges.add(default_nicpp[constants.NIC_LINK])
2505
    for instance in self.my_inst_info.values():
2506
      for nic in instance.nics:
2507
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2508
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2509
          bridges.add(full_nic[constants.NIC_LINK])
2510

    
2511
    if bridges:
2512
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2513

    
2514
    # Build our expected cluster state
2515
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2516
                                                 name=node.name,
2517
                                                 vm_capable=node.vm_capable))
2518
                      for node in node_data_list)
2519

    
2520
    # Gather OOB paths
2521
    oob_paths = []
2522
    for node in self.all_node_info.values():
2523
      path = _SupportsOob(self.cfg, node)
2524
      if path and path not in oob_paths:
2525
        oob_paths.append(path)
2526

    
2527
    if oob_paths:
2528
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2529

    
2530
    for instance in self.my_inst_names:
2531
      inst_config = self.my_inst_info[instance]
2532

    
2533
      for nname in inst_config.all_nodes:
2534
        if nname not in node_image:
2535
          gnode = self.NodeImage(name=nname)
2536
          gnode.ghost = (nname not in self.all_node_info)
2537
          node_image[nname] = gnode
2538

    
2539
      inst_config.MapLVsByNode(node_vol_should)
2540

    
2541
      pnode = inst_config.primary_node
2542
      node_image[pnode].pinst.append(instance)
2543

    
2544
      for snode in inst_config.secondary_nodes:
2545
        nimg = node_image[snode]
2546
        nimg.sinst.append(instance)
2547
        if pnode not in nimg.sbp:
2548
          nimg.sbp[pnode] = []
2549
        nimg.sbp[pnode].append(instance)
2550

    
2551
    # At this point, we have the in-memory data structures complete,
2552
    # except for the runtime information, which we'll gather next
2553

    
2554
    # Due to the way our RPC system works, exact response times cannot be
2555
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2556
    # time before and after executing the request, we can at least have a time
2557
    # window.
2558
    nvinfo_starttime = time.time()
2559
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2560
                                           node_verify_param,
2561
                                           self.cfg.GetClusterName())
2562
    if self.extra_lv_nodes and vg_name is not None:
2563
      extra_lv_nvinfo = \
2564
          self.rpc.call_node_verify(self.extra_lv_nodes,
2565
                                    {constants.NV_LVLIST: vg_name},
2566
                                    self.cfg.GetClusterName())
2567
    else:
2568
      extra_lv_nvinfo = {}
2569
    nvinfo_endtime = time.time()
2570

    
2571
    all_drbd_map = self.cfg.ComputeDRBDMap()
2572

    
2573
    feedback_fn("* Gathering disk information (%s nodes)" %
2574
                len(self.my_node_names))
2575
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2576
                                     self.my_inst_info)
2577

    
2578
    feedback_fn("* Verifying configuration file consistency")
2579

    
2580
    # If not all nodes are being checked, we need to make sure the master node
2581
    # and a non-checked vm_capable node are in the list.
2582
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2583
    if absent_nodes:
2584
      vf_nvinfo = all_nvinfo.copy()
2585
      vf_node_info = list(self.my_node_info.values())
2586
      additional_nodes = []
2587
      if master_node not in self.my_node_info:
2588
        additional_nodes.append(master_node)
2589
        vf_node_info.append(self.all_node_info[master_node])
2590
      # Add the first vm_capable node we find which is not included
2591
      for node in absent_nodes:
2592
        nodeinfo = self.all_node_info[node]
2593
        if nodeinfo.vm_capable and not nodeinfo.offline:
2594
          additional_nodes.append(node)
2595
          vf_node_info.append(self.all_node_info[node])
2596
          break
2597
      key = constants.NV_FILELIST
2598
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2599
                                                 {key: node_verify_param[key]},
2600
                                                 self.cfg.GetClusterName()))
2601
    else:
2602
      vf_nvinfo = all_nvinfo
2603
      vf_node_info = self.my_node_info.values()
2604

    
2605
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2606

    
2607
    feedback_fn("* Verifying node status")
2608

    
2609
    refos_img = None
2610

    
2611
    for node_i in node_data_list:
2612
      node = node_i.name
2613
      nimg = node_image[node]
2614

    
2615
      if node_i.offline:
2616
        if verbose:
2617
          feedback_fn("* Skipping offline node %s" % (node,))
2618
        n_offline += 1
2619
        continue
2620

    
2621
      if node == master_node:
2622
        ntype = "master"
2623
      elif node_i.master_candidate:
2624
        ntype = "master candidate"
2625
      elif node_i.drained:
2626
        ntype = "drained"
2627
        n_drained += 1
2628
      else:
2629
        ntype = "regular"
2630
      if verbose:
2631
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2632

    
2633
      msg = all_nvinfo[node].fail_msg
2634
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2635
      if msg:
2636
        nimg.rpc_fail = True
2637
        continue
2638

    
2639
      nresult = all_nvinfo[node].payload
2640

    
2641
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2642
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2643
      self._VerifyNodeNetwork(node_i, nresult)
2644
      self._VerifyOob(node_i, nresult)
2645

    
2646
      if nimg.vm_capable:
2647
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2648
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2649
                             all_drbd_map)
2650

    
2651
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2652
        self._UpdateNodeInstances(node_i, nresult, nimg)
2653
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2654
        self._UpdateNodeOS(node_i, nresult, nimg)
2655

    
2656
        if not nimg.os_fail:
2657
          if refos_img is None:
2658
            refos_img = nimg
2659
          self._VerifyNodeOS(node_i, nimg, refos_img)
2660
        self._VerifyNodeBridges(node_i, nresult, bridges)
2661

    
2662
        # Check whether all running instancies are primary for the node. (This
2663
        # can no longer be done from _VerifyInstance below, since some of the
2664
        # wrong instances could be from other node groups.)
2665
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2666

    
2667
        for inst in non_primary_inst:
2668
          test = inst in self.all_inst_info
2669
          _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2670
                   "instance should not run on node %s", node_i.name)
2671
          _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2672
                   "node is running unknown instance %s", inst)
2673

    
2674
    for node, result in extra_lv_nvinfo.items():
2675
      self._UpdateNodeVolumes(self.all_node_info[node], result.payload,
2676
                              node_image[node], vg_name)
2677

    
2678
    feedback_fn("* Verifying instance status")
2679
    for instance in self.my_inst_names:
2680
      if verbose:
2681
        feedback_fn("* Verifying instance %s" % instance)
2682
      inst_config = self.my_inst_info[instance]
2683
      self._VerifyInstance(instance, inst_config, node_image,
2684
                           instdisk[instance])
2685
      inst_nodes_offline = []
2686

    
2687
      pnode = inst_config.primary_node
2688
      pnode_img = node_image[pnode]
2689
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2690
               self.ENODERPC, pnode, "instance %s, connection to"
2691
               " primary node failed", instance)
2692

    
2693
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2694
               self.EINSTANCEBADNODE, instance,
2695
               "instance is marked as running and lives on offline node %s",
2696
               inst_config.primary_node)
2697

    
2698
      # If the instance is non-redundant we cannot survive losing its primary
2699
      # node, so we are not N+1 compliant. On the other hand we have no disk
2700
      # templates with more than one secondary so that situation is not well
2701
      # supported either.
2702
      # FIXME: does not support file-backed instances
2703
      if not inst_config.secondary_nodes:
2704
        i_non_redundant.append(instance)
2705

    
2706
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2707
               instance, "instance has multiple secondary nodes: %s",
2708
               utils.CommaJoin(inst_config.secondary_nodes),
2709
               code=self.ETYPE_WARNING)
2710

    
2711
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2712
        pnode = inst_config.primary_node
2713
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2714
        instance_groups = {}
2715

    
2716
        for node in instance_nodes:
2717
          instance_groups.setdefault(self.all_node_info[node].group,
2718
                                     []).append(node)
2719

    
2720
        pretty_list = [
2721
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2722
          # Sort so that we always list the primary node first.
2723
          for group, nodes in sorted(instance_groups.items(),
2724
                                     key=lambda (_, nodes): pnode in nodes,
2725
                                     reverse=True)]
2726

    
2727
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2728
                      instance, "instance has primary and secondary nodes in"
2729
                      " different groups: %s", utils.CommaJoin(pretty_list),
2730
                      code=self.ETYPE_WARNING)
2731

    
2732
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2733
        i_non_a_balanced.append(instance)
2734

    
2735
      for snode in inst_config.secondary_nodes:
2736
        s_img = node_image[snode]
2737
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2738
                 "instance %s, connection to secondary node failed", instance)
2739

    
2740
        if s_img.offline:
2741
          inst_nodes_offline.append(snode)
2742

    
2743
      # warn that the instance lives on offline nodes
2744
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2745
               "instance has offline secondary node(s) %s",
2746
               utils.CommaJoin(inst_nodes_offline))
2747
      # ... or ghost/non-vm_capable nodes
2748
      for node in inst_config.all_nodes:
2749
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2750
                 "instance lives on ghost node %s", node)
2751
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2752
                 instance, "instance lives on non-vm_capable node %s", node)
2753

    
2754
    feedback_fn("* Verifying orphan volumes")
2755
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2756

    
2757
    # We will get spurious "unknown volume" warnings if any node of this group
2758
    # is secondary for an instance whose primary is in another group. To avoid
2759
    # them, we find these instances and add their volumes to node_vol_should.
2760
    for inst in self.all_inst_info.values():
2761
      for secondary in inst.secondary_nodes:
2762
        if (secondary in self.my_node_info
2763
            and inst.name not in self.my_inst_info):
2764
          inst.MapLVsByNode(node_vol_should)
2765
          break
2766

    
2767
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2768

    
2769
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2770
      feedback_fn("* Verifying N+1 Memory redundancy")
2771
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2772

    
2773
    feedback_fn("* Other Notes")
2774
    if i_non_redundant:
2775
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2776
                  % len(i_non_redundant))
2777

    
2778
    if i_non_a_balanced:
2779
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2780
                  % len(i_non_a_balanced))
2781

    
2782
    if n_offline:
2783
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2784

    
2785
    if n_drained:
2786
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2787

    
2788
    return not self.bad
2789

    
2790
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2791
    """Analyze the post-hooks' result
2792

2793
    This method analyses the hook result, handles it, and sends some
2794
    nicely-formatted feedback back to the user.
2795

2796
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2797
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2798
    @param hooks_results: the results of the multi-node hooks rpc call
2799
    @param feedback_fn: function used send feedback back to the caller
2800
    @param lu_result: previous Exec result
2801
    @return: the new Exec result, based on the previous result
2802
        and hook results
2803

2804
    """
2805
    # We only really run POST phase hooks, and are only interested in
2806
    # their results
2807
    if phase == constants.HOOKS_PHASE_POST:
2808
      # Used to change hooks' output to proper indentation
2809
      feedback_fn("* Hooks Results")
2810
      assert hooks_results, "invalid result from hooks"
2811

    
2812
      for node_name in hooks_results:
2813
        res = hooks_results[node_name]
2814
        msg = res.fail_msg
2815
        test = msg and not res.offline
2816
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2817
                      "Communication failure in hooks execution: %s", msg)
2818
        if res.offline or msg:
2819
          # No need to investigate payload if node is offline or gave an error.
2820
          # override manually lu_result here as _ErrorIf only
2821
          # overrides self.bad
2822
          lu_result = 1
2823
          continue
2824
        for script, hkr, output in res.payload:
2825
          test = hkr == constants.HKR_FAIL
2826
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2827
                        "Script %s failed, output:", script)
2828
          if test:
2829
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2830
            feedback_fn("%s" % output)
2831
            lu_result = 0
2832

    
2833
      return lu_result
2834

    
2835

    
2836
class LUClusterVerifyDisks(NoHooksLU):
2837
  """Verifies the cluster disks status.
2838

2839
  """
2840
  REQ_BGL = False
2841

    
2842
  def ExpandNames(self):
2843
    self.needed_locks = {
2844
      locking.LEVEL_NODE: locking.ALL_SET,
2845
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2846
    }
2847
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2848

    
2849
  def Exec(self, feedback_fn):
2850
    """Verify integrity of cluster disks.
2851

2852
    @rtype: tuple of three items
2853
    @return: a tuple of (dict of node-to-node_error, list of instances
2854
        which need activate-disks, dict of instance: (node, volume) for
2855
        missing volumes
2856

2857
    """
2858
    result = res_nodes, res_instances, res_missing = {}, [], {}
2859

    
2860
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2861
    instances = self.cfg.GetAllInstancesInfo().values()
2862

    
2863
    nv_dict = {}
2864
    for inst in instances:
2865
      inst_lvs = {}
2866
      if not inst.admin_up:
2867
        continue
2868
      inst.MapLVsByNode(inst_lvs)
2869
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2870
      for node, vol_list in inst_lvs.iteritems():
2871
        for vol in vol_list:
2872
          nv_dict[(node, vol)] = inst
2873

    
2874
    if not nv_dict:
2875
      return result
2876

    
2877
    node_lvs = self.rpc.call_lv_list(nodes, [])
2878
    for node, node_res in node_lvs.items():
2879
      if node_res.offline:
2880
        continue
2881
      msg = node_res.fail_msg
2882
      if msg:
2883
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2884
        res_nodes[node] = msg
2885
        continue
2886

    
2887
      lvs = node_res.payload
2888
      for lv_name, (_, _, lv_online) in lvs.items():
2889
        inst = nv_dict.pop((node, lv_name), None)
2890
        if (not lv_online and inst is not None
2891
            and inst.name not in res_instances):
2892
          res_instances.append(inst.name)
2893

    
2894
    # any leftover items in nv_dict are missing LVs, let's arrange the
2895
    # data better
2896
    for key, inst in nv_dict.iteritems():
2897
      if inst.name not in res_missing:
2898
        res_missing[inst.name] = []
2899
      res_missing[inst.name].append(key)
2900

    
2901
    return result
2902

    
2903

    
2904
class LUClusterRepairDiskSizes(NoHooksLU):
2905
  """Verifies the cluster disks sizes.
2906

2907
  """
2908
  REQ_BGL = False
2909

    
2910
  def ExpandNames(self):
2911
    if self.op.instances:
2912
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2913
      self.needed_locks = {
2914
        locking.LEVEL_NODE: [],
2915
        locking.LEVEL_INSTANCE: self.wanted_names,
2916
        }
2917
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2918
    else:
2919
      self.wanted_names = None
2920
      self.needed_locks = {
2921
        locking.LEVEL_NODE: locking.ALL_SET,
2922
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2923
        }
2924
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2925

    
2926
  def DeclareLocks(self, level):
2927
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2928
      self._LockInstancesNodes(primary_only=True)
2929

    
2930
  def CheckPrereq(self):
2931
    """Check prerequisites.
2932

2933
    This only checks the optional instance list against the existing names.
2934

2935
    """
2936
    if self.wanted_names is None:
2937
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2938

    
2939
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2940
                             in self.wanted_names]
2941

    
2942
  def _EnsureChildSizes(self, disk):
2943
    """Ensure children of the disk have the needed disk size.
2944

2945
    This is valid mainly for DRBD8 and fixes an issue where the
2946
    children have smaller disk size.
2947

2948
    @param disk: an L{ganeti.objects.Disk} object
2949

2950
    """
2951
    if disk.dev_type == constants.LD_DRBD8:
2952
      assert disk.children, "Empty children for DRBD8?"
2953
      fchild = disk.children[0]
2954
      mismatch = fchild.size < disk.size
2955
      if mismatch:
2956
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2957
                     fchild.size, disk.size)
2958
        fchild.size = disk.size
2959

    
2960
      # and we recurse on this child only, not on the metadev
2961
      return self._EnsureChildSizes(fchild) or mismatch
2962
    else:
2963
      return False
2964

    
2965
  def Exec(self, feedback_fn):
2966
    """Verify the size of cluster disks.
2967

2968
    """
2969
    # TODO: check child disks too
2970
    # TODO: check differences in size between primary/secondary nodes
2971
    per_node_disks = {}
2972
    for instance in self.wanted_instances:
2973
      pnode = instance.primary_node
2974
      if pnode not in per_node_disks:
2975
        per_node_disks[pnode] = []
2976
      for idx, disk in enumerate(instance.disks):
2977
        per_node_disks[pnode].append((instance, idx, disk))
2978

    
2979
    changed = []
2980
    for node, dskl in per_node_disks.items():
2981
      newl = [v[2].Copy() for v in dskl]
2982
      for dsk in newl:
2983
        self.cfg.SetDiskID(dsk, node)
2984
      result = self.rpc.call_blockdev_getsize(node, newl)
2985
      if result.fail_msg:
2986
        self.LogWarning("Failure in blockdev_getsize call to node"
2987
                        " %s, ignoring", node)
2988
        continue
2989
      if len(result.payload) != len(dskl):
2990
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2991
                        " result.payload=%s", node, len(dskl), result.payload)
2992
        self.LogWarning("Invalid result from node %s, ignoring node results",
2993
                        node)
2994
        continue
2995
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2996
        if size is None:
2997
          self.LogWarning("Disk %d of instance %s did not return size"
2998
                          " information, ignoring", idx, instance.name)
2999
          continue
3000
        if not isinstance(size, (int, long)):
3001
          self.LogWarning("Disk %d of instance %s did not return valid"
3002
                          " size information, ignoring", idx, instance.name)
3003
          continue
3004
        size = size >> 20
3005
        if size != disk.size:
3006
          self.LogInfo("Disk %d of instance %s has mismatched size,"
3007
                       " correcting: recorded %d, actual %d", idx,
3008
                       instance.name, disk.size, size)
3009
          disk.size = size
3010
          self.cfg.Update(instance, feedback_fn)
3011
          changed.append((instance.name, idx, size))
3012
        if self._EnsureChildSizes(disk):
3013
          self.cfg.Update(instance, feedback_fn)
3014
          changed.append((instance.name, idx, disk.size))
3015
    return changed
3016

    
3017

    
3018
class LUClusterRename(LogicalUnit):
3019
  """Rename the cluster.
3020

3021
  """
3022
  HPATH = "cluster-rename"
3023
  HTYPE = constants.HTYPE_CLUSTER
3024

    
3025
  def BuildHooksEnv(self):
3026
    """Build hooks env.
3027

3028
    """
3029
    return {
3030
      "OP_TARGET": self.cfg.GetClusterName(),
3031
      "NEW_NAME": self.op.name,
3032
      }
3033

    
3034
  def BuildHooksNodes(self):
3035
    """Build hooks nodes.
3036

3037
    """
3038
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
3039

    
3040
  def CheckPrereq(self):
3041
    """Verify that the passed name is a valid one.
3042

3043
    """
3044
    hostname = netutils.GetHostname(name=self.op.name,
3045
                                    family=self.cfg.GetPrimaryIPFamily())
3046

    
3047
    new_name = hostname.name
3048
    self.ip = new_ip = hostname.ip
3049
    old_name = self.cfg.GetClusterName()
3050
    old_ip = self.cfg.GetMasterIP()
3051
    if new_name == old_name and new_ip == old_ip:
3052
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
3053
                                 " cluster has changed",
3054
                                 errors.ECODE_INVAL)
3055
    if new_ip != old_ip:
3056
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
3057
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
3058
                                   " reachable on the network" %
3059
                                   new_ip, errors.ECODE_NOTUNIQUE)
3060

    
3061
    self.op.name = new_name
3062

    
3063
  def Exec(self, feedback_fn):
3064
    """Rename the cluster.
3065

3066
    """
3067
    clustername = self.op.name
3068
    ip = self.ip
3069

    
3070
    # shutdown the master IP
3071
    master = self.cfg.GetMasterNode()
3072
    result = self.rpc.call_node_stop_master(master, False)
3073
    result.Raise("Could not disable the master role")
3074

    
3075
    try:
3076
      cluster = self.cfg.GetClusterInfo()
3077
      cluster.cluster_name = clustername
3078
      cluster.master_ip = ip
3079
      self.cfg.Update(cluster, feedback_fn)
3080

    
3081
      # update the known hosts file
3082
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
3083
      node_list = self.cfg.GetOnlineNodeList()
3084
      try:
3085
        node_list.remove(master)
3086
      except ValueError:
3087
        pass
3088
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3089
    finally:
3090
      result = self.rpc.call_node_start_master(master, False, False)
3091
      msg = result.fail_msg
3092
      if msg:
3093
        self.LogWarning("Could not re-enable the master role on"
3094
                        " the master, please restart manually: %s", msg)
3095

    
3096
    return clustername
3097

    
3098

    
3099
class LUClusterSetParams(LogicalUnit):
3100
  """Change the parameters of the cluster.
3101

3102
  """
3103
  HPATH = "cluster-modify"
3104
  HTYPE = constants.HTYPE_CLUSTER
3105
  REQ_BGL = False
3106

    
3107
  def CheckArguments(self):
3108
    """Check parameters
3109

3110
    """
3111
    if self.op.uid_pool:
3112
      uidpool.CheckUidPool(self.op.uid_pool)
3113

    
3114
    if self.op.add_uids:
3115
      uidpool.CheckUidPool(self.op.add_uids)
3116

    
3117
    if self.op.remove_uids:
3118
      uidpool.CheckUidPool(self.op.remove_uids)
3119

    
3120
  def ExpandNames(self):
3121
    # FIXME: in the future maybe other cluster params won't require checking on
3122
    # all nodes to be modified.
3123
    self.needed_locks = {
3124
      locking.LEVEL_NODE: locking.ALL_SET,
3125
    }
3126
    self.share_locks[locking.LEVEL_NODE] = 1
3127

    
3128
  def BuildHooksEnv(self):
3129
    """Build hooks env.
3130

3131
    """
3132
    return {
3133
      "OP_TARGET": self.cfg.GetClusterName(),
3134
      "NEW_VG_NAME": self.op.vg_name,
3135
      }
3136

    
3137
  def BuildHooksNodes(self):
3138
    """Build hooks nodes.
3139

3140
    """
3141
    mn = self.cfg.GetMasterNode()
3142
    return ([mn], [mn])
3143

    
3144
  def CheckPrereq(self):
3145
    """Check prerequisites.
3146

3147
    This checks whether the given params don't conflict and
3148
    if the given volume group is valid.
3149

3150
    """
3151
    if self.op.vg_name is not None and not self.op.vg_name:
3152
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3153
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3154
                                   " instances exist", errors.ECODE_INVAL)
3155

    
3156
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
3157
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3158
        raise errors.OpPrereqError("Cannot disable drbd helper while"
3159
                                   " drbd-based instances exist",
3160
                                   errors.ECODE_INVAL)
3161

    
3162
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
3163

    
3164
    # if vg_name not None, checks given volume group on all nodes
3165
    if self.op.vg_name:
3166
      vglist = self.rpc.call_vg_list(node_list)
3167
      for node in node_list:
3168
        msg = vglist[node].fail_msg
3169
        if msg:
3170
          # ignoring down node
3171
          self.LogWarning("Error while gathering data on node %s"
3172
                          " (ignoring node): %s", node, msg)
3173
          continue
3174
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3175
                                              self.op.vg_name,
3176
                                              constants.MIN_VG_SIZE)
3177
        if vgstatus:
3178
          raise errors.OpPrereqError("Error on node '%s': %s" %
3179
                                     (node, vgstatus), errors.ECODE_ENVIRON)
3180

    
3181
    if self.op.drbd_helper:
3182
      # checks given drbd helper on all nodes
3183
      helpers = self.rpc.call_drbd_helper(node_list)
3184
      for node in node_list:
3185
        ninfo = self.cfg.GetNodeInfo(node)
3186
        if ninfo.offline:
3187
          self.LogInfo("Not checking drbd helper on offline node %s", node)
3188
          continue
3189
        msg = helpers[node].fail_msg
3190
        if msg:
3191
          raise errors.OpPrereqError("Error checking drbd helper on node"
3192
                                     " '%s': %s" % (node, msg),
3193
                                     errors.ECODE_ENVIRON)
3194
        node_helper = helpers[node].payload
3195
        if node_helper != self.op.drbd_helper:
3196
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3197
                                     (node, node_helper), errors.ECODE_ENVIRON)
3198

    
3199
    self.cluster = cluster = self.cfg.GetClusterInfo()
3200
    # validate params changes
3201
    if self.op.beparams:
3202
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3203
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3204

    
3205
    if self.op.ndparams:
3206
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3207
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3208

    
3209
      # TODO: we need a more general way to handle resetting
3210
      # cluster-level parameters to default values
3211
      if self.new_ndparams["oob_program"] == "":
3212
        self.new_ndparams["oob_program"] = \
3213
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3214

    
3215
    if self.op.nicparams:
3216
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3217
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3218
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3219
      nic_errors = []
3220

    
3221
      # check all instances for consistency
3222
      for instance in self.cfg.GetAllInstancesInfo().values():
3223
        for nic_idx, nic in enumerate(instance.nics):
3224
          params_copy = copy.deepcopy(nic.nicparams)
3225
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3226

    
3227
          # check parameter syntax
3228
          try:
3229
            objects.NIC.CheckParameterSyntax(params_filled)
3230
          except errors.ConfigurationError, err:
3231
            nic_errors.append("Instance %s, nic/%d: %s" %
3232
                              (instance.name, nic_idx, err))
3233

    
3234
          # if we're moving instances to routed, check that they have an ip
3235
          target_mode = params_filled[constants.NIC_MODE]
3236
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3237
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3238
                              " address" % (instance.name, nic_idx))
3239
      if nic_errors:
3240
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3241
                                   "\n".join(nic_errors))
3242

    
3243
    # hypervisor list/parameters
3244
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3245
    if self.op.hvparams:
3246
      for hv_name, hv_dict in self.op.hvparams.items():
3247
        if hv_name not in self.new_hvparams:
3248
          self.new_hvparams[hv_name] = hv_dict
3249
        else:
3250
          self.new_hvparams[hv_name].update(hv_dict)
3251

    
3252
    # os hypervisor parameters
3253
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3254
    if self.op.os_hvp:
3255
      for os_name, hvs in self.op.os_hvp.items():
3256
        if os_name not in self.new_os_hvp:
3257
          self.new_os_hvp[os_name] = hvs
3258
        else:
3259
          for hv_name, hv_dict in hvs.items():
3260
            if hv_name not in self.new_os_hvp[os_name]:
3261
              self.new_os_hvp[os_name][hv_name] = hv_dict
3262
            else:
3263
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3264

    
3265
    # os parameters
3266
    self.new_osp = objects.FillDict(cluster.osparams, {})
3267
    if self.op.osparams:
3268
      for os_name, osp in self.op.osparams.items():
3269
        if os_name not in self.new_osp:
3270
          self.new_osp[os_name] = {}
3271

    
3272
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3273
                                                  use_none=True)
3274

    
3275
        if not self.new_osp[os_name]:
3276
          # we removed all parameters
3277
          del self.new_osp[os_name]
3278
        else:
3279
          # check the parameter validity (remote check)
3280
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3281
                         os_name, self.new_osp[os_name])
3282

    
3283
    # changes to the hypervisor list
3284
    if self.op.enabled_hypervisors is not None:
3285
      self.hv_list = self.op.enabled_hypervisors
3286
      for hv in self.hv_list:
3287
        # if the hypervisor doesn't already exist in the cluster
3288
        # hvparams, we initialize it to empty, and then (in both
3289
        # cases) we make sure to fill the defaults, as we might not
3290
        # have a complete defaults list if the hypervisor wasn't
3291
        # enabled before
3292
        if hv not in new_hvp:
3293
          new_hvp[hv] = {}
3294
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3295
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3296
    else:
3297
      self.hv_list = cluster.enabled_hypervisors
3298

    
3299
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3300
      # either the enabled list has changed, or the parameters have, validate
3301
      for hv_name, hv_params in self.new_hvparams.items():
3302
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3303
            (self.op.enabled_hypervisors and
3304
             hv_name in self.op.enabled_hypervisors)):
3305
          # either this is a new hypervisor, or its parameters have changed
3306
          hv_class = hypervisor.GetHypervisor(hv_name)
3307
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3308
          hv_class.CheckParameterSyntax(hv_params)
3309
          _CheckHVParams(self, node_list, hv_name, hv_params)
3310

    
3311
    if self.op.os_hvp:
3312
      # no need to check any newly-enabled hypervisors, since the
3313
      # defaults have already been checked in the above code-block
3314
      for os_name, os_hvp in self.new_os_hvp.items():
3315
        for hv_name, hv_params in os_hvp.items():
3316
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3317
          # we need to fill in the new os_hvp on top of the actual hv_p
3318
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3319
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3320
          hv_class = hypervisor.GetHypervisor(hv_name)
3321
          hv_class.CheckParameterSyntax(new_osp)
3322
          _CheckHVParams(self, node_list, hv_name, new_osp)
3323

    
3324
    if self.op.default_iallocator:
3325
      alloc_script = utils.FindFile(self.op.default_iallocator,
3326
                                    constants.IALLOCATOR_SEARCH_PATH,
3327
                                    os.path.isfile)
3328
      if alloc_script is None:
3329
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3330
                                   " specified" % self.op.default_iallocator,
3331
                                   errors.ECODE_INVAL)
3332

    
3333
  def Exec(self, feedback_fn):
3334
    """Change the parameters of the cluster.
3335

3336
    """
3337
    if self.op.vg_name is not None:
3338
      new_volume = self.op.vg_name
3339
      if not new_volume:
3340
        new_volume = None
3341
      if new_volume != self.cfg.GetVGName():
3342
        self.cfg.SetVGName(new_volume)
3343
      else:
3344
        feedback_fn("Cluster LVM configuration already in desired"
3345
                    " state, not changing")
3346
    if self.op.drbd_helper is not None:
3347
      new_helper = self.op.drbd_helper
3348
      if not new_helper:
3349
        new_helper = None
3350
      if new_helper != self.cfg.GetDRBDHelper():
3351
        self.cfg.SetDRBDHelper(new_helper)
3352
      else:
3353
        feedback_fn("Cluster DRBD helper already in desired state,"
3354
                    " not changing")
3355
    if self.op.hvparams:
3356
      self.cluster.hvparams = self.new_hvparams
3357
    if self.op.os_hvp:
3358
      self.cluster.os_hvp = self.new_os_hvp
3359
    if self.op.enabled_hypervisors is not None:
3360
      self.cluster.hvparams = self.new_hvparams
3361
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3362
    if self.op.beparams:
3363
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3364
    if self.op.nicparams:
3365
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3366
    if self.op.osparams:
3367
      self.cluster.osparams = self.new_osp
3368
    if self.op.ndparams:
3369
      self.cluster.ndparams = self.new_ndparams
3370

    
3371
    if self.op.candidate_pool_size is not None:
3372
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3373
      # we need to update the pool size here, otherwise the save will fail
3374
      _AdjustCandidatePool(self, [])
3375

    
3376
    if self.op.maintain_node_health is not None:
3377
      self.cluster.maintain_node_health = self.op.maintain_node_health
3378

    
3379
    if self.op.prealloc_wipe_disks is not None:
3380
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3381

    
3382
    if self.op.add_uids is not None:
3383
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3384

    
3385
    if self.op.remove_uids is not None:
3386
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3387

    
3388
    if self.op.uid_pool is not None:
3389
      self.cluster.uid_pool = self.op.uid_pool
3390

    
3391
    if self.op.default_iallocator is not None:
3392
      self.cluster.default_iallocator = self.op.default_iallocator
3393

    
3394
    if self.op.reserved_lvs is not None:
3395
      self.cluster.reserved_lvs = self.op.reserved_lvs
3396

    
3397
    def helper_os(aname, mods, desc):
3398
      desc += " OS list"
3399
      lst = getattr(self.cluster, aname)
3400
      for key, val in mods:
3401
        if key == constants.DDM_ADD:
3402
          if val in lst:
3403
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3404
          else:
3405
            lst.append(val)
3406
        elif key == constants.DDM_REMOVE:
3407
          if val in lst:
3408
            lst.remove(val)
3409
          else:
3410
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3411
        else:
3412
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3413

    
3414
    if self.op.hidden_os:
3415
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3416

    
3417
    if self.op.blacklisted_os:
3418
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3419

    
3420
    if self.op.master_netdev:
3421
      master = self.cfg.GetMasterNode()
3422
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3423
                  self.cluster.master_netdev)
3424
      result = self.rpc.call_node_stop_master(master, False)
3425
      result.Raise("Could not disable the master ip")
3426
      feedback_fn("Changing master_netdev from %s to %s" %
3427
                  (self.cluster.master_netdev, self.op.master_netdev))
3428
      self.cluster.master_netdev = self.op.master_netdev
3429

    
3430
    self.cfg.Update(self.cluster, feedback_fn)
3431

    
3432
    if self.op.master_netdev:
3433
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3434
                  self.op.master_netdev)
3435
      result = self.rpc.call_node_start_master(master, False, False)
3436
      if result.fail_msg:
3437
        self.LogWarning("Could not re-enable the master ip on"
3438
                        " the master, please restart manually: %s",
3439
                        result.fail_msg)
3440

    
3441

    
3442
def _UploadHelper(lu, nodes, fname):
3443
  """Helper for uploading a file and showing warnings.
3444

3445
  """
3446
  if os.path.exists(fname):
3447
    result = lu.rpc.call_upload_file(nodes, fname)
3448
    for to_node, to_result in result.items():
3449
      msg = to_result.fail_msg
3450
      if msg:
3451
        msg = ("Copy of file %s to node %s failed: %s" %
3452
               (fname, to_node, msg))
3453
        lu.proc.LogWarning(msg)
3454

    
3455

    
3456
def _ComputeAncillaryFiles(cluster, redist):
3457
  """Compute files external to Ganeti which need to be consistent.
3458

3459
  @type redist: boolean
3460
  @param redist: Whether to include files which need to be redistributed
3461

3462
  """
3463
  # Compute files for all nodes
3464
  files_all = set([
3465
    constants.SSH_KNOWN_HOSTS_FILE,
3466
    constants.CONFD_HMAC_KEY,
3467
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3468
    ])
3469

    
3470
  if not redist:
3471
    files_all.update(constants.ALL_CERT_FILES)
3472
    files_all.update(ssconf.SimpleStore().GetFileList())
3473

    
3474
  if cluster.modify_etc_hosts:
3475
    files_all.add(constants.ETC_HOSTS)
3476

    
3477
  # Files which must either exist on all nodes or on none
3478
  files_all_opt = set([
3479
    constants.RAPI_USERS_FILE,
3480
    ])
3481

    
3482
  # Files which should only be on master candidates
3483
  files_mc = set()
3484
  if not redist:
3485
    files_mc.add(constants.CLUSTER_CONF_FILE)
3486

    
3487
  # Files which should only be on VM-capable nodes
3488
  files_vm = set(filename
3489
    for hv_name in cluster.enabled_hypervisors
3490
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3491

    
3492
  # Filenames must be unique
3493
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3494
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3495
         "Found file listed in more than one file list"
3496

    
3497
  return (files_all, files_all_opt, files_mc, files_vm)
3498

    
3499

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

3503
  ConfigWriter takes care of distributing the config and ssconf files, but
3504
  there are more files which should be distributed to all nodes. This function
3505
  makes sure those are copied.
3506

3507
  @param lu: calling logical unit
3508
  @param additional_nodes: list of nodes not in the config to distribute to
3509
  @type additional_vm: boolean
3510
  @param additional_vm: whether the additional nodes are vm-capable or not
3511

3512
  """
3513
  # Gather target nodes
3514
  cluster = lu.cfg.GetClusterInfo()
3515
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3516

    
3517
  online_nodes = lu.cfg.GetOnlineNodeList()
3518
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3519

    
3520
  if additional_nodes is not None:
3521
    online_nodes.extend(additional_nodes)
3522
    if additional_vm:
3523
      vm_nodes.extend(additional_nodes)
3524

    
3525
  # Never distribute to master node
3526
  for nodelist in [online_nodes, vm_nodes]:
3527
    if master_info.name in nodelist:
3528
      nodelist.remove(master_info.name)
3529

    
3530
  # Gather file lists
3531
  (files_all, files_all_opt, files_mc, files_vm) = \
3532
    _ComputeAncillaryFiles(cluster, True)
3533

    
3534
  # Never re-distribute configuration file from here
3535
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3536
              constants.CLUSTER_CONF_FILE in files_vm)
3537
  assert not files_mc, "Master candidates not handled in this function"
3538

    
3539
  filemap = [
3540
    (online_nodes, files_all),
3541
    (online_nodes, files_all_opt),
3542
    (vm_nodes, files_vm),
3543
    ]
3544

    
3545
  # Upload the files
3546
  for (node_list, files) in filemap:
3547
    for fname in files:
3548
      _UploadHelper(lu, node_list, fname)
3549

    
3550

    
3551
class LUClusterRedistConf(NoHooksLU):
3552
  """Force the redistribution of cluster configuration.
3553

3554
  This is a very simple LU.
3555

3556
  """
3557
  REQ_BGL = False
3558

    
3559
  def ExpandNames(self):
3560
    self.needed_locks = {
3561
      locking.LEVEL_NODE: locking.ALL_SET,
3562
    }
3563
    self.share_locks[locking.LEVEL_NODE] = 1
3564

    
3565
  def Exec(self, feedback_fn):
3566
    """Redistribute the configuration.
3567

3568
    """
3569
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3570
    _RedistributeAncillaryFiles(self)
3571

    
3572

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

3576
  """
3577
  if not instance.disks or disks is not None and not disks:
3578
    return True
3579

    
3580
  disks = _ExpandCheckDisks(instance, disks)
3581

    
3582
  if not oneshot:
3583
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3584

    
3585
  node = instance.primary_node
3586

    
3587
  for dev in disks:
3588
    lu.cfg.SetDiskID(dev, node)
3589

    
3590
  # TODO: Convert to utils.Retry
3591

    
3592
  retries = 0
3593
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3594
  while True:
3595
    max_time = 0
3596
    done = True
3597
    cumul_degraded = False
3598
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3599
    msg = rstats.fail_msg
3600
    if msg:
3601
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3602
      retries += 1
3603
      if retries >= 10:
3604
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3605
                                 " aborting." % node)
3606
      time.sleep(6)
3607
      continue
3608
    rstats = rstats.payload
3609
    retries = 0
3610
    for i, mstat in enumerate(rstats):
3611
      if mstat is None:
3612
        lu.LogWarning("Can't compute data for node %s/%s",
3613
                           node, disks[i].iv_name)
3614
        continue
3615

    
3616
      cumul_degraded = (cumul_degraded or
3617
                        (mstat.is_degraded and mstat.sync_percent is None))
3618
      if mstat.sync_percent is not None:
3619
        done = False
3620
        if mstat.estimated_time is not None:
3621
          rem_time = ("%s remaining (estimated)" %
3622
                      utils.FormatSeconds(mstat.estimated_time))
3623
          max_time = mstat.estimated_time
3624
        else:
3625
          rem_time = "no time estimate"
3626
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3627
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3628

    
3629
    # if we're done but degraded, let's do a few small retries, to
3630
    # make sure we see a stable and not transient situation; therefore
3631
    # we force restart of the loop
3632
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3633
      logging.info("Degraded disks found, %d retries left", degr_retries)
3634
      degr_retries -= 1
3635
      time.sleep(1)
3636
      continue
3637

    
3638
    if done or oneshot:
3639
      break
3640

    
3641
    time.sleep(min(60, max_time))
3642

    
3643
  if done:
3644
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3645
  return not cumul_degraded
3646

    
3647

    
3648
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3649
  """Check that mirrors are not degraded.
3650

3651
  The ldisk parameter, if True, will change the test from the
3652
  is_degraded attribute (which represents overall non-ok status for
3653
  the device(s)) to the ldisk (representing the local storage status).
3654

3655
  """
3656
  lu.cfg.SetDiskID(dev, node)
3657

    
3658
  result = True
3659

    
3660
  if on_primary or dev.AssembleOnSecondary():
3661
    rstats = lu.rpc.call_blockdev_find(node, dev)
3662
    msg = rstats.fail_msg
3663
    if msg:
3664
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3665
      result = False
3666
    elif not rstats.payload:
3667
      lu.LogWarning("Can't find disk on node %s", node)
3668
      result = False
3669
    else:
3670
      if ldisk:
3671
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3672
      else:
3673
        result = result and not rstats.payload.is_degraded
3674

    
3675
  if dev.children:
3676
    for child in dev.children:
3677
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3678

    
3679
  return result
3680

    
3681

    
3682
class LUOobCommand(NoHooksLU):
3683
  """Logical unit for OOB handling.
3684

3685
  """
3686
  REG_BGL = False
3687
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3688

    
3689
  def ExpandNames(self):
3690
    """Gather locks we need.
3691

3692
    """
3693
    if self.op.node_names:
3694
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3695
      lock_names = self.op.node_names
3696
    else:
3697
      lock_names = locking.ALL_SET
3698

    
3699
    self.needed_locks = {
3700
      locking.LEVEL_NODE: lock_names,
3701
      }
3702

    
3703
  def CheckPrereq(self):
3704
    """Check prerequisites.
3705

3706
    This checks:
3707
     - the node exists in the configuration
3708
     - OOB is supported
3709

3710
    Any errors are signaled by raising errors.OpPrereqError.
3711

3712
    """
3713
    self.nodes = []
3714
    self.master_node = self.cfg.GetMasterNode()
3715

    
3716
    assert self.op.power_delay >= 0.0
3717

    
3718
    if self.op.node_names:
3719
      if (self.op.command in self._SKIP_MASTER and
3720
          self.master_node in self.op.node_names):
3721
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3722
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3723

    
3724
        if master_oob_handler:
3725
          additional_text = ("run '%s %s %s' if you want to operate on the"
3726
                             " master regardless") % (master_oob_handler,
3727
                                                      self.op.command,
3728
                                                      self.master_node)
3729
        else:
3730
          additional_text = "it does not support out-of-band operations"
3731

    
3732
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3733
                                    " allowed for %s; %s") %
3734
                                   (self.master_node, self.op.command,
3735
                                    additional_text), errors.ECODE_INVAL)
3736
    else:
3737
      self.op.node_names = self.cfg.GetNodeList()
3738
      if self.op.command in self._SKIP_MASTER:
3739
        self.op.node_names.remove(self.master_node)
3740

    
3741
    if self.op.command in self._SKIP_MASTER:
3742
      assert self.master_node not in self.op.node_names
3743

    
3744
    for node_name in self.op.node_names:
3745
      node = self.cfg.GetNodeInfo(node_name)
3746

    
3747
      if node is None:
3748
        raise errors.OpPrereqError("Node %s not found" % node_name,
3749
                                   errors.ECODE_NOENT)
3750
      else:
3751
        self.nodes.append(node)
3752

    
3753
      if (not self.op.ignore_status and
3754
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3755
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3756
                                    " not marked offline") % node_name,
3757
                                   errors.ECODE_STATE)
3758

    
3759
  def Exec(self, feedback_fn):
3760
    """Execute OOB and return result if we expect any.
3761

3762
    """
3763
    master_node = self.master_node
3764
    ret = []
3765

    
3766
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3767
                                              key=lambda node: node.name)):
3768
      node_entry = [(constants.RS_NORMAL, node.name)]
3769
      ret.append(node_entry)
3770

    
3771
      oob_program = _SupportsOob(self.cfg, node)
3772

    
3773
      if not oob_program:
3774
        node_entry.append((constants.RS_UNAVAIL, None))
3775
        continue
3776

    
3777
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3778
                   self.op.command, oob_program, node.name)
3779
      result = self.rpc.call_run_oob(master_node, oob_program,
3780
                                     self.op.command, node.name,
3781
                                     self.op.timeout)
3782

    
3783
      if result.fail_msg:
3784
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3785
                        node.name, result.fail_msg)
3786
        node_entry.append((constants.RS_NODATA, None))
3787
      else:
3788
        try:
3789
          self._CheckPayload(result)
3790
        except errors.OpExecError, err:
3791
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3792
                          node.name, err)
3793
          node_entry.append((constants.RS_NODATA, None))
3794
        else:
3795
          if self.op.command == constants.OOB_HEALTH:
3796
            # For health we should log important events
3797
            for item, status in result.payload:
3798
              if status in [constants.OOB_STATUS_WARNING,
3799
                            constants.OOB_STATUS_CRITICAL]:
3800
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3801
                                item, node.name, status)
3802

    
3803
          if self.op.command == constants.OOB_POWER_ON:
3804
            node.powered = True
3805
          elif self.op.command == constants.OOB_POWER_OFF:
3806
            node.powered = False
3807
          elif self.op.command == constants.OOB_POWER_STATUS:
3808
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3809
            if powered != node.powered:
3810
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3811
                               " match actual power state (%s)"), node.powered,
3812
                              node.name, powered)
3813

    
3814
          # For configuration changing commands we should update the node
3815
          if self.op.command in (constants.OOB_POWER_ON,
3816
                                 constants.OOB_POWER_OFF):
3817
            self.cfg.Update(node, feedback_fn)
3818

    
3819
          node_entry.append((constants.RS_NORMAL, result.payload))
3820

    
3821
          if (self.op.command == constants.OOB_POWER_ON and
3822
              idx < len(self.nodes) - 1):
3823
            time.sleep(self.op.power_delay)
3824

    
3825
    return ret
3826

    
3827
  def _CheckPayload(self, result):
3828
    """Checks if the payload is valid.
3829

3830
    @param result: RPC result
3831
    @raises errors.OpExecError: If payload is not valid
3832

3833
    """
3834
    errs = []
3835
    if self.op.command == constants.OOB_HEALTH:
3836
      if not isinstance(result.payload, list):
3837
        errs.append("command 'health' is expected to return a list but got %s" %
3838
                    type(result.payload))
3839
      else:
3840
        for item, status in result.payload:
3841
          if status not in constants.OOB_STATUSES:
3842
            errs.append("health item '%s' has invalid status '%s'" %
3843
                        (item, status))
3844

    
3845
    if self.op.command == constants.OOB_POWER_STATUS:
3846
      if not isinstance(result.payload, dict):
3847
        errs.append("power-status is expected to return a dict but got %s" %
3848
                    type(result.payload))
3849

    
3850
    if self.op.command in [
3851
        constants.OOB_POWER_ON,
3852
        constants.OOB_POWER_OFF,
3853
        constants.OOB_POWER_CYCLE,
3854
        ]:
3855
      if result.payload is not None:
3856
        errs.append("%s is expected to not return payload but got '%s'" %
3857
                    (self.op.command, result.payload))
3858

    
3859
    if errs:
3860
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3861
                               utils.CommaJoin(errs))
3862

    
3863
class _OsQuery(_QueryBase):
3864
  FIELDS = query.OS_FIELDS
3865

    
3866
  def ExpandNames(self, lu):
3867
    # Lock all nodes in shared mode
3868
    # Temporary removal of locks, should be reverted later
3869
    # TODO: reintroduce locks when they are lighter-weight
3870
    lu.needed_locks = {}
3871
    #self.share_locks[locking.LEVEL_NODE] = 1
3872
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3873

    
3874
    # The following variables interact with _QueryBase._GetNames
3875
    if self.names:
3876
      self.wanted = self.names
3877
    else:
3878
      self.wanted = locking.ALL_SET
3879

    
3880
    self.do_locking = self.use_locking
3881

    
3882
  def DeclareLocks(self, lu, level):
3883
    pass
3884

    
3885
  @staticmethod
3886
  def _DiagnoseByOS(rlist):
3887
    """Remaps a per-node return list into an a per-os per-node dictionary
3888

3889
    @param rlist: a map with node names as keys and OS objects as values
3890

3891
    @rtype: dict
3892
    @return: a dictionary with osnames as keys and as value another
3893
        map, with nodes as keys and tuples of (path, status, diagnose,
3894
        variants, parameters, api_versions) as values, eg::
3895

3896
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3897
                                     (/srv/..., False, "invalid api")],
3898
                           "node2": [(/srv/..., True, "", [], [])]}
3899
          }
3900

3901
    """
3902
    all_os = {}
3903
    # we build here the list of nodes that didn't fail the RPC (at RPC
3904
    # level), so that nodes with a non-responding node daemon don't
3905
    # make all OSes invalid
3906
    good_nodes = [node_name for node_name in rlist
3907
                  if not rlist[node_name].fail_msg]
3908
    for node_name, nr in rlist.items():
3909
      if nr.fail_msg or not nr.payload:
3910
        continue
3911
      for (name, path, status, diagnose, variants,
3912
           params, api_versions) in nr.payload:
3913
        if name not in all_os:
3914
          # build a list of nodes for this os containing empty lists
3915
          # for each node in node_list
3916
          all_os[name] = {}
3917
          for nname in good_nodes:
3918
            all_os[name][nname] = []
3919
        # convert params from [name, help] to (name, help)
3920
        params = [tuple(v) for v in params]
3921
        all_os[name][node_name].append((path, status, diagnose,
3922
                                        variants, params, api_versions))
3923
    return all_os
3924

    
3925
  def _GetQueryData(self, lu):
3926
    """Computes the list of nodes and their attributes.
3927

3928
    """
3929
    # Locking is not used
3930
    assert not (compat.any(lu.glm.is_owned(level)
3931
                           for level in locking.LEVELS
3932
                           if level != locking.LEVEL_CLUSTER) or
3933
                self.do_locking or self.use_locking)
3934

    
3935
    valid_nodes = [node.name
3936
                   for node in lu.cfg.GetAllNodesInfo().values()
3937
                   if not node.offline and node.vm_capable]
3938
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3939
    cluster = lu.cfg.GetClusterInfo()
3940

    
3941
    data = {}
3942

    
3943
    for (os_name, os_data) in pol.items():
3944
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3945
                          hidden=(os_name in cluster.hidden_os),
3946
                          blacklisted=(os_name in cluster.blacklisted_os))
3947

    
3948
      variants = set()
3949
      parameters = set()
3950
      api_versions = set()
3951

    
3952
      for idx, osl in enumerate(os_data.values()):
3953
        info.valid = bool(info.valid and osl and osl[0][1])
3954
        if not info.valid:
3955
          break
3956

    
3957
        (node_variants, node_params, node_api) = osl[0][3:6]
3958
        if idx == 0:
3959
          # First entry
3960
          variants.update(node_variants)
3961
          parameters.update(node_params)
3962
          api_versions.update(node_api)
3963
        else:
3964
          # Filter out inconsistent values
3965
          variants.intersection_update(node_variants)
3966
          parameters.intersection_update(node_params)
3967
          api_versions.intersection_update(node_api)
3968

    
3969
      info.variants = list(variants)
3970
      info.parameters = list(parameters)
3971
      info.api_versions = list(api_versions)
3972

    
3973
      data[os_name] = info
3974

    
3975
    # Prepare data in requested order
3976
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3977
            if name in data]
3978

    
3979

    
3980
class LUOsDiagnose(NoHooksLU):
3981
  """Logical unit for OS diagnose/query.
3982

3983
  """
3984
  REQ_BGL = False
3985

    
3986
  @staticmethod
3987
  def _BuildFilter(fields, names):
3988
    """Builds a filter for querying OSes.
3989

3990
    """
3991
    name_filter = qlang.MakeSimpleFilter("name", names)
3992

    
3993
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
3994
    # respective field is not requested
3995
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
3996
                     for fname in ["hidden", "blacklisted"]
3997
                     if fname not in fields]
3998
    if "valid" not in fields:
3999
      status_filter.append([qlang.OP_TRUE, "valid"])
4000

    
4001
    if status_filter:
4002
      status_filter.insert(0, qlang.OP_AND)
4003
    else:
4004
      status_filter = None
4005

    
4006
    if name_filter and status_filter:
4007
      return [qlang.OP_AND, name_filter, status_filter]
4008
    elif name_filter:
4009
      return name_filter
4010
    else:
4011
      return status_filter
4012

    
4013
  def CheckArguments(self):
4014
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
4015
                       self.op.output_fields, False)
4016

    
4017
  def ExpandNames(self):
4018
    self.oq.ExpandNames(self)
4019

    
4020
  def Exec(self, feedback_fn):
4021
    return self.oq.OldStyleQuery(self)
4022

    
4023

    
4024
class LUNodeRemove(LogicalUnit):
4025
  """Logical unit for removing a node.
4026

4027
  """
4028
  HPATH = "node-remove"
4029
  HTYPE = constants.HTYPE_NODE
4030

    
4031
  def BuildHooksEnv(self):
4032
    """Build hooks env.
4033

4034
    This doesn't run on the target node in the pre phase as a failed
4035
    node would then be impossible to remove.
4036

4037
    """
4038
    return {
4039
      "OP_TARGET": self.op.node_name,
4040
      "NODE_NAME": self.op.node_name,
4041
      }
4042

    
4043
  def BuildHooksNodes(self):
4044
    """Build hooks nodes.
4045

4046
    """
4047
    all_nodes = self.cfg.GetNodeList()
4048
    try:
4049
      all_nodes.remove(self.op.node_name)
4050
    except ValueError:
4051
      logging.warning("Node '%s', which is about to be removed, was not found"
4052
                      " in the list of all nodes", self.op.node_name)
4053
    return (all_nodes, all_nodes)
4054

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

4058
    This checks:
4059
     - the node exists in the configuration
4060
     - it does not have primary or secondary instances
4061
     - it's not the master
4062

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

4065
    """
4066
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4067
    node = self.cfg.GetNodeInfo(self.op.node_name)
4068
    assert node is not None
4069

    
4070
    instance_list = self.cfg.GetInstanceList()
4071

    
4072
    masternode = self.cfg.GetMasterNode()
4073
    if node.name == masternode:
4074
      raise errors.OpPrereqError("Node is the master node, failover to another"
4075
                                 " node is required", errors.ECODE_INVAL)
4076

    
4077
    for instance_name in instance_list:
4078
      instance = self.cfg.GetInstanceInfo(instance_name)
4079
      if node.name in instance.all_nodes:
4080
        raise errors.OpPrereqError("Instance %s is still running on the node,"
4081
                                   " please remove first" % instance_name,
4082
                                   errors.ECODE_INVAL)
4083
    self.op.node_name = node.name
4084
    self.node = node
4085

    
4086
  def Exec(self, feedback_fn):
4087
    """Removes the node from the cluster.
4088

4089
    """
4090
    node = self.node
4091
    logging.info("Stopping the node daemon and removing configs from node %s",
4092
                 node.name)
4093

    
4094
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
4095

    
4096
    # Promote nodes to master candidate as needed
4097
    _AdjustCandidatePool(self, exceptions=[node.name])
4098
    self.context.RemoveNode(node.name)
4099

    
4100
    # Run post hooks on the node before it's removed
4101
    _RunPostHook(self, node.name)
4102

    
4103
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
4104
    msg = result.fail_msg
4105
    if msg:
4106
      self.LogWarning("Errors encountered on the remote node while leaving"
4107
                      " the cluster: %s", msg)
4108

    
4109
    # Remove node from our /etc/hosts
4110
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4111
      master_node = self.cfg.GetMasterNode()
4112
      result = self.rpc.call_etc_hosts_modify(master_node,
4113
                                              constants.ETC_HOSTS_REMOVE,
4114
                                              node.name, None)
4115
      result.Raise("Can't update hosts file with new host data")
4116
      _RedistributeAncillaryFiles(self)
4117

    
4118

    
4119
class _NodeQuery(_QueryBase):
4120
  FIELDS = query.NODE_FIELDS
4121

    
4122
  def ExpandNames(self, lu):
4123
    lu.needed_locks = {}
4124
    lu.share_locks[locking.LEVEL_NODE] = 1
4125

    
4126
    if self.names:
4127
      self.wanted = _GetWantedNodes(lu, self.names)
4128
    else:
4129
      self.wanted = locking.ALL_SET
4130

    
4131
    self.do_locking = (self.use_locking and
4132
                       query.NQ_LIVE in self.requested_data)
4133

    
4134
    if self.do_locking:
4135
      # if we don't request only static fields, we need to lock the nodes
4136
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
4137

    
4138
  def DeclareLocks(self, lu, level):
4139
    pass
4140

    
4141
  def _GetQueryData(self, lu):
4142
    """Computes the list of nodes and their attributes.
4143

4144
    """
4145
    all_info = lu.cfg.GetAllNodesInfo()
4146

    
4147
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
4148

    
4149
    # Gather data as requested
4150
    if query.NQ_LIVE in self.requested_data:
4151
      # filter out non-vm_capable nodes
4152
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
4153

    
4154
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
4155
                                        lu.cfg.GetHypervisorType())
4156
      live_data = dict((name, nresult.payload)
4157
                       for (name, nresult) in node_data.items()
4158
                       if not nresult.fail_msg and nresult.payload)
4159
    else:
4160
      live_data = None
4161

    
4162
    if query.NQ_INST in self.requested_data:
4163
      node_to_primary = dict([(name, set()) for name in nodenames])
4164
      node_to_secondary = dict([(name, set()) for name in nodenames])
4165

    
4166
      inst_data = lu.cfg.GetAllInstancesInfo()
4167

    
4168
      for inst in inst_data.values():
4169
        if inst.primary_node in node_to_primary:
4170
          node_to_primary[inst.primary_node].add(inst.name)
4171
        for secnode in inst.secondary_nodes:
4172
          if secnode in node_to_secondary:
4173
            node_to_secondary[secnode].add(inst.name)
4174
    else:
4175
      node_to_primary = None
4176
      node_to_secondary = None
4177

    
4178
    if query.NQ_OOB in self.requested_data:
4179
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
4180
                         for name, node in all_info.iteritems())
4181
    else:
4182
      oob_support = None
4183

    
4184
    if query.NQ_GROUP in self.requested_data:
4185
      groups = lu.cfg.GetAllNodeGroupsInfo()
4186
    else:
4187
      groups = {}
4188

    
4189
    return query.NodeQueryData([all_info[name] for name in nodenames],
4190
                               live_data, lu.cfg.GetMasterNode(),
4191
                               node_to_primary, node_to_secondary, groups,
4192
                               oob_support, lu.cfg.GetClusterInfo())
4193

    
4194

    
4195
class LUNodeQuery(NoHooksLU):
4196
  """Logical unit for querying nodes.
4197

4198
  """
4199
  # pylint: disable-msg=W0142
4200
  REQ_BGL = False
4201

    
4202
  def CheckArguments(self):
4203
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4204
                         self.op.output_fields, self.op.use_locking)
4205

    
4206
  def ExpandNames(self):
4207
    self.nq.ExpandNames(self)
4208

    
4209
  def Exec(self, feedback_fn):
4210
    return self.nq.OldStyleQuery(self)
4211

    
4212

    
4213
class LUNodeQueryvols(NoHooksLU):
4214
  """Logical unit for getting volumes on node(s).
4215

4216
  """
4217
  REQ_BGL = False
4218
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4219
  _FIELDS_STATIC = utils.FieldSet("node")
4220

    
4221
  def CheckArguments(self):
4222
    _CheckOutputFields(static=self._FIELDS_STATIC,
4223
                       dynamic=self._FIELDS_DYNAMIC,
4224
                       selected=self.op.output_fields)
4225

    
4226
  def ExpandNames(self):
4227
    self.needed_locks = {}
4228
    self.share_locks[locking.LEVEL_NODE] = 1
4229
    if not self.op.nodes:
4230
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4231
    else:
4232
      self.needed_locks[locking.LEVEL_NODE] = \
4233
        _GetWantedNodes(self, self.op.nodes)
4234

    
4235
  def Exec(self, feedback_fn):
4236
    """Computes the list of nodes and their attributes.
4237

4238
    """
4239
    nodenames = self.glm.list_owned(locking.LEVEL_NODE)
4240
    volumes = self.rpc.call_node_volumes(nodenames)
4241

    
4242
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
4243
             in self.cfg.GetInstanceList()]
4244

    
4245
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
4246

    
4247
    output = []
4248
    for node in nodenames:
4249
      nresult = volumes[node]
4250
      if nresult.offline:
4251
        continue
4252
      msg = nresult.fail_msg
4253
      if msg:
4254
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4255
        continue
4256

    
4257
      node_vols = nresult.payload[:]
4258
      node_vols.sort(key=lambda vol: vol['dev'])
4259

    
4260
      for vol in node_vols:
4261
        node_output = []
4262
        for field in self.op.output_fields:
4263
          if field == "node":
4264
            val = node
4265
          elif field == "phys":
4266
            val = vol['dev']
4267
          elif field == "vg":
4268
            val = vol['vg']
4269
          elif field == "name":
4270
            val = vol['name']
4271
          elif field == "size":
4272
            val = int(float(vol['size']))
4273
          elif field == "instance":
4274
            for inst in ilist:
4275
              if node not in lv_by_node[inst]:
4276
                continue
4277
              if vol['name'] in lv_by_node[inst][node]:
4278
                val = inst.name
4279
                break
4280
            else:
4281
              val = '-'
4282
          else:
4283
            raise errors.ParameterError(field)
4284
          node_output.append(str(val))
4285

    
4286
        output.append(node_output)
4287

    
4288
    return output
4289

    
4290

    
4291
class LUNodeQueryStorage(NoHooksLU):
4292
  """Logical unit for getting information on storage units on node(s).
4293

4294
  """
4295
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4296
  REQ_BGL = False
4297

    
4298
  def CheckArguments(self):
4299
    _CheckOutputFields(static=self._FIELDS_STATIC,
4300
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4301
                       selected=self.op.output_fields)
4302

    
4303
  def ExpandNames(self):
4304
    self.needed_locks = {}
4305
    self.share_locks[locking.LEVEL_NODE] = 1
4306

    
4307
    if self.op.nodes:
4308
      self.needed_locks[locking.LEVEL_NODE] = \
4309
        _GetWantedNodes(self, self.op.nodes)
4310
    else:
4311
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4312

    
4313
  def Exec(self, feedback_fn):
4314
    """Computes the list of nodes and their attributes.
4315

4316
    """
4317
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
4318

    
4319
    # Always get name to sort by
4320
    if constants.SF_NAME in self.op.output_fields:
4321
      fields = self.op.output_fields[:]
4322
    else:
4323
      fields = [constants.SF_NAME] + self.op.output_fields
4324

    
4325
    # Never ask for node or type as it's only known to the LU
4326
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4327
      while extra in fields:
4328
        fields.remove(extra)
4329

    
4330
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4331
    name_idx = field_idx[constants.SF_NAME]
4332

    
4333
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4334
    data = self.rpc.call_storage_list(self.nodes,
4335
                                      self.op.storage_type, st_args,
4336
                                      self.op.name, fields)
4337

    
4338
    result = []
4339

    
4340
    for node in utils.NiceSort(self.nodes):
4341
      nresult = data[node]
4342
      if nresult.offline:
4343
        continue
4344

    
4345
      msg = nresult.fail_msg
4346
      if msg:
4347
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4348
        continue
4349

    
4350
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4351

    
4352
      for name in utils.NiceSort(rows.keys()):
4353
        row = rows[name]
4354

    
4355
        out = []
4356

    
4357
        for field in self.op.output_fields:
4358
          if field == constants.SF_NODE:
4359
            val = node
4360
          elif field == constants.SF_TYPE:
4361
            val = self.op.storage_type
4362
          elif field in field_idx:
4363
            val = row[field_idx[field]]
4364
          else:
4365
            raise errors.ParameterError(field)
4366

    
4367
          out.append(val)
4368

    
4369
        result.append(out)
4370

    
4371
    return result
4372

    
4373

    
4374
class _InstanceQuery(_QueryBase):
4375
  FIELDS = query.INSTANCE_FIELDS
4376

    
4377
  def ExpandNames(self, lu):
4378
    lu.needed_locks = {}
4379
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
4380
    lu.share_locks[locking.LEVEL_NODE] = 1
4381

    
4382
    if self.names:
4383
      self.wanted = _GetWantedInstances(lu, self.names)
4384
    else:
4385
      self.wanted = locking.ALL_SET
4386

    
4387
    self.do_locking = (self.use_locking and
4388
                       query.IQ_LIVE in self.requested_data)
4389
    if self.do_locking:
4390
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4391
      lu.needed_locks[locking.LEVEL_NODE] = []
4392
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4393

    
4394
  def DeclareLocks(self, lu, level):
4395
    if level == locking.LEVEL_NODE and self.do_locking:
4396
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
4397

    
4398
  def _GetQueryData(self, lu):
4399
    """Computes the list of instances and their attributes.
4400

4401
    """
4402
    cluster = lu.cfg.GetClusterInfo()
4403
    all_info = lu.cfg.GetAllInstancesInfo()
4404

    
4405
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4406

    
4407
    instance_list = [all_info[name] for name in instance_names]
4408
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4409
                                        for inst in instance_list)))
4410
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4411
    bad_nodes = []
4412
    offline_nodes = []
4413
    wrongnode_inst = set()
4414

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

    
4443
    if query.IQ_DISKUSAGE in self.requested_data:
4444
      disk_usage = dict((inst.name,
4445
                         _ComputeDiskSize(inst.disk_template,
4446
                                          [{constants.IDISK_SIZE: disk.size}
4447
                                           for disk in inst.disks]))
4448
                        for inst in instance_list)
4449
    else:
4450
      disk_usage = None
4451

    
4452
    if query.IQ_CONSOLE in self.requested_data:
4453
      consinfo = {}
4454
      for inst in instance_list:
4455
        if inst.name in live_data:
4456
          # Instance is running
4457
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4458
        else:
4459
          consinfo[inst.name] = None
4460
      assert set(consinfo.keys()) == set(instance_names)
4461
    else:
4462
      consinfo = None
4463

    
4464
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4465
                                   disk_usage, offline_nodes, bad_nodes,
4466
                                   live_data, wrongnode_inst, consinfo)
4467

    
4468

    
4469
class LUQuery(NoHooksLU):
4470
  """Query for resources/items of a certain kind.
4471

4472
  """
4473
  # pylint: disable-msg=W0142
4474
  REQ_BGL = False
4475

    
4476
  def CheckArguments(self):
4477
    qcls = _GetQueryImplementation(self.op.what)
4478

    
4479
    self.impl = qcls(self.op.filter, self.op.fields, False)
4480

    
4481
  def ExpandNames(self):
4482
    self.impl.ExpandNames(self)
4483

    
4484
  def DeclareLocks(self, level):
4485
    self.impl.DeclareLocks(self, level)
4486

    
4487
  def Exec(self, feedback_fn):
4488
    return self.impl.NewStyleQuery(self)
4489

    
4490

    
4491
class LUQueryFields(NoHooksLU):
4492
  """Query for resources/items of a certain kind.
4493

4494
  """
4495
  # pylint: disable-msg=W0142
4496
  REQ_BGL = False
4497

    
4498
  def CheckArguments(self):
4499
    self.qcls = _GetQueryImplementation(self.op.what)
4500

    
4501
  def ExpandNames(self):
4502
    self.needed_locks = {}
4503

    
4504
  def Exec(self, feedback_fn):
4505
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4506

    
4507

    
4508
class LUNodeModifyStorage(NoHooksLU):
4509
  """Logical unit for modifying a storage volume on a node.
4510

4511
  """
4512
  REQ_BGL = False
4513

    
4514
  def CheckArguments(self):
4515
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4516

    
4517
    storage_type = self.op.storage_type
4518

    
4519
    try:
4520
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4521
    except KeyError:
4522
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4523
                                 " modified" % storage_type,
4524
                                 errors.ECODE_INVAL)
4525

    
4526
    diff = set(self.op.changes.keys()) - modifiable
4527
    if diff:
4528
      raise errors.OpPrereqError("The following fields can not be modified for"
4529
                                 " storage units of type '%s': %r" %
4530
                                 (storage_type, list(diff)),
4531
                                 errors.ECODE_INVAL)
4532

    
4533
  def ExpandNames(self):
4534
    self.needed_locks = {
4535
      locking.LEVEL_NODE: self.op.node_name,
4536
      }
4537

    
4538
  def Exec(self, feedback_fn):
4539
    """Computes the list of nodes and their attributes.
4540

4541
    """
4542
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4543
    result = self.rpc.call_storage_modify(self.op.node_name,
4544
                                          self.op.storage_type, st_args,
4545
                                          self.op.name, self.op.changes)
4546
    result.Raise("Failed to modify storage unit '%s' on %s" %
4547
                 (self.op.name, self.op.node_name))
4548

    
4549

    
4550
class LUNodeAdd(LogicalUnit):
4551
  """Logical unit for adding node to the cluster.
4552

4553
  """
4554
  HPATH = "node-add"
4555
  HTYPE = constants.HTYPE_NODE
4556
  _NFLAGS = ["master_capable", "vm_capable"]
4557

    
4558
  def CheckArguments(self):
4559
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4560
    # validate/normalize the node name
4561
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4562
                                         family=self.primary_ip_family)
4563
    self.op.node_name = self.hostname.name
4564

    
4565
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4566
      raise errors.OpPrereqError("Cannot readd the master node",
4567
                                 errors.ECODE_STATE)
4568

    
4569
    if self.op.readd and self.op.group:
4570
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4571
                                 " being readded", errors.ECODE_INVAL)
4572

    
4573
  def BuildHooksEnv(self):
4574
    """Build hooks env.
4575

4576
    This will run on all nodes before, and on all nodes + the new node after.
4577

4578
    """
4579
    return {
4580
      "OP_TARGET": self.op.node_name,
4581
      "NODE_NAME": self.op.node_name,
4582
      "NODE_PIP": self.op.primary_ip,
4583
      "NODE_SIP": self.op.secondary_ip,
4584
      "MASTER_CAPABLE": str(self.op.master_capable),
4585
      "VM_CAPABLE": str(self.op.vm_capable),
4586
      }
4587

    
4588
  def BuildHooksNodes(self):
4589
    """Build hooks nodes.
4590

4591
    """
4592
    # Exclude added node
4593
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4594
    post_nodes = pre_nodes + [self.op.node_name, ]
4595

    
4596
    return (pre_nodes, post_nodes)
4597

    
4598
  def CheckPrereq(self):
4599
    """Check prerequisites.
4600

4601
    This checks:
4602
     - the new node is not already in the config
4603
     - it is resolvable
4604
     - its parameters (single/dual homed) matches the cluster
4605

4606
    Any errors are signaled by raising errors.OpPrereqError.
4607

4608
    """
4609
    cfg = self.cfg
4610
    hostname = self.hostname
4611
    node = hostname.name
4612
    primary_ip = self.op.primary_ip = hostname.ip
4613
    if self.op.secondary_ip is None:
4614
      if self.primary_ip_family == netutils.IP6Address.family:
4615
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4616
                                   " IPv4 address must be given as secondary",
4617
                                   errors.ECODE_INVAL)
4618
      self.op.secondary_ip = primary_ip
4619

    
4620
    secondary_ip = self.op.secondary_ip
4621
    if not netutils.IP4Address.IsValid(secondary_ip):
4622
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4623
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4624

    
4625
    node_list = cfg.GetNodeList()
4626
    if not self.op.readd and node in node_list:
4627
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4628
                                 node, errors.ECODE_EXISTS)
4629
    elif self.op.readd and node not in node_list:
4630
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4631
                                 errors.ECODE_NOENT)
4632

    
4633
    self.changed_primary_ip = False
4634

    
4635
    for existing_node_name in node_list:
4636
      existing_node = cfg.GetNodeInfo(existing_node_name)
4637

    
4638
      if self.op.readd and node == existing_node_name:
4639
        if existing_node.secondary_ip != secondary_ip:
4640
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4641
                                     " address configuration as before",
4642
                                     errors.ECODE_INVAL)
4643
        if existing_node.primary_ip != primary_ip:
4644
          self.changed_primary_ip = True
4645

    
4646
        continue
4647

    
4648
      if (existing_node.primary_ip == primary_ip or
4649
          existing_node.secondary_ip == primary_ip or
4650
          existing_node.primary_ip == secondary_ip or
4651
          existing_node.secondary_ip == secondary_ip):
4652
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4653
                                   " existing node %s" % existing_node.name,
4654
                                   errors.ECODE_NOTUNIQUE)
4655

    
4656
    # After this 'if' block, None is no longer a valid value for the
4657
    # _capable op attributes
4658
    if self.op.readd:
4659
      old_node = self.cfg.GetNodeInfo(node)
4660
      assert old_node is not None, "Can't retrieve locked node %s" % node
4661
      for attr in self._NFLAGS:
4662
        if getattr(self.op, attr) is None:
4663
          setattr(self.op, attr, getattr(old_node, attr))
4664
    else:
4665
      for attr in self._NFLAGS:
4666
        if getattr(self.op, attr) is None:
4667
          setattr(self.op, attr, True)
4668

    
4669
    if self.op.readd and not self.op.vm_capable:
4670
      pri, sec = cfg.GetNodeInstances(node)
4671
      if pri or sec:
4672
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4673
                                   " flag set to false, but it already holds"
4674
                                   " instances" % node,
4675
                                   errors.ECODE_STATE)
4676

    
4677
    # check that the type of the node (single versus dual homed) is the
4678
    # same as for the master
4679
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4680
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4681
    newbie_singlehomed = secondary_ip == primary_ip
4682
    if master_singlehomed != newbie_singlehomed:
4683
      if master_singlehomed:
4684
        raise errors.OpPrereqError("The master has no secondary ip but the"
4685
                                   " new node has one",
4686
                                   errors.ECODE_INVAL)
4687
      else:
4688
        raise errors.OpPrereqError("The master has a secondary ip but the"
4689
                                   " new node doesn't have one",
4690
                                   errors.ECODE_INVAL)
4691

    
4692
    # checks reachability
4693
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4694
      raise errors.OpPrereqError("Node not reachable by ping",
4695
                                 errors.ECODE_ENVIRON)
4696

    
4697
    if not newbie_singlehomed:
4698
      # check reachability from my secondary ip to newbie's secondary ip
4699
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4700
                           source=myself.secondary_ip):
4701
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4702
                                   " based ping to node daemon port",
4703
                                   errors.ECODE_ENVIRON)
4704

    
4705
    if self.op.readd:
4706
      exceptions = [node]
4707
    else:
4708
      exceptions = []
4709

    
4710
    if self.op.master_capable:
4711
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4712
    else:
4713
      self.master_candidate = False
4714

    
4715
    if self.op.readd:
4716
      self.new_node = old_node
4717
    else:
4718
      node_group = cfg.LookupNodeGroup(self.op.group)
4719
      self.new_node = objects.Node(name=node,
4720
                                   primary_ip=primary_ip,
4721
                                   secondary_ip=secondary_ip,
4722
                                   master_candidate=self.master_candidate,
4723
                                   offline=False, drained=False,
4724
                                   group=node_group)
4725

    
4726
    if self.op.ndparams:
4727
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4728

    
4729
  def Exec(self, feedback_fn):
4730
    """Adds the new node to the cluster.
4731

4732
    """
4733
    new_node = self.new_node
4734
    node = new_node.name
4735

    
4736
    # We adding a new node so we assume it's powered
4737
    new_node.powered = True
4738

    
4739
    # for re-adds, reset the offline/drained/master-candidate flags;
4740
    # we need to reset here, otherwise offline would prevent RPC calls
4741
    # later in the procedure; this also means that if the re-add
4742
    # fails, we are left with a non-offlined, broken node
4743
    if self.op.readd:
4744
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4745
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4746
      # if we demote the node, we do cleanup later in the procedure
4747
      new_node.master_candidate = self.master_candidate
4748
      if self.changed_primary_ip:
4749
        new_node.primary_ip = self.op.primary_ip
4750

    
4751
    # copy the master/vm_capable flags
4752
    for attr in self._NFLAGS:
4753
      setattr(new_node, attr, getattr(self.op, attr))
4754

    
4755
    # notify the user about any possible mc promotion
4756
    if new_node.master_candidate:
4757
      self.LogInfo("Node will be a master candidate")
4758

    
4759
    if self.op.ndparams:
4760
      new_node.ndparams = self.op.ndparams
4761
    else:
4762
      new_node.ndparams = {}
4763

    
4764
    # check connectivity
4765
    result = self.rpc.call_version([node])[node]
4766
    result.Raise("Can't get version information from node %s" % node)
4767
    if constants.PROTOCOL_VERSION == result.payload:
4768
      logging.info("Communication to node %s fine, sw version %s match",
4769
                   node, result.payload)
4770
    else:
4771
      raise errors.OpExecError("Version mismatch master version %s,"
4772
                               " node version %s" %
4773
                               (constants.PROTOCOL_VERSION, result.payload))
4774

    
4775
    # Add node to our /etc/hosts, and add key to known_hosts
4776
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4777
      master_node = self.cfg.GetMasterNode()
4778
      result = self.rpc.call_etc_hosts_modify(master_node,
4779
                                              constants.ETC_HOSTS_ADD,
4780
                                              self.hostname.name,
4781
                                              self.hostname.ip)
4782
      result.Raise("Can't update hosts file with new host data")
4783

    
4784
    if new_node.secondary_ip != new_node.primary_ip:
4785
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4786
                               False)
4787

    
4788
    node_verify_list = [self.cfg.GetMasterNode()]
4789
    node_verify_param = {
4790
      constants.NV_NODELIST: [node],
4791
      # TODO: do a node-net-test as well?
4792
    }
4793

    
4794
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4795
                                       self.cfg.GetClusterName())
4796
    for verifier in node_verify_list:
4797
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4798
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4799
      if nl_payload:
4800
        for failed in nl_payload:
4801
          feedback_fn("ssh/hostname verification failed"
4802
                      " (checking from %s): %s" %
4803
                      (verifier, nl_payload[failed]))
4804
        raise errors.OpExecError("ssh/hostname verification failed")
4805

    
4806
    if self.op.readd:
4807
      _RedistributeAncillaryFiles(self)
4808
      self.context.ReaddNode(new_node)
4809
      # make sure we redistribute the config
4810
      self.cfg.Update(new_node, feedback_fn)
4811
      # and make sure the new node will not have old files around
4812
      if not new_node.master_candidate:
4813
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4814
        msg = result.fail_msg
4815
        if msg:
4816
          self.LogWarning("Node failed to demote itself from master"
4817
                          " candidate status: %s" % msg)
4818
    else:
4819
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4820
                                  additional_vm=self.op.vm_capable)
4821
      self.context.AddNode(new_node, self.proc.GetECId())
4822

    
4823

    
4824
class LUNodeSetParams(LogicalUnit):
4825
  """Modifies the parameters of a node.
4826

4827
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4828
      to the node role (as _ROLE_*)
4829
  @cvar _R2F: a dictionary from node role to tuples of flags
4830
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4831

4832
  """
4833
  HPATH = "node-modify"
4834
  HTYPE = constants.HTYPE_NODE
4835
  REQ_BGL = False
4836
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4837
  _F2R = {
4838
    (True, False, False): _ROLE_CANDIDATE,
4839
    (False, True, False): _ROLE_DRAINED,
4840
    (False, False, True): _ROLE_OFFLINE,
4841
    (False, False, False): _ROLE_REGULAR,
4842
    }
4843
  _R2F = dict((v, k) for k, v in _F2R.items())
4844
  _FLAGS = ["master_candidate", "drained", "offline"]
4845

    
4846
  def CheckArguments(self):
4847
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4848
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4849
                self.op.master_capable, self.op.vm_capable,
4850
                self.op.secondary_ip, self.op.ndparams]
4851
    if all_mods.count(None) == len(all_mods):
4852
      raise errors.OpPrereqError("Please pass at least one modification",
4853
                                 errors.ECODE_INVAL)
4854
    if all_mods.count(True) > 1:
4855
      raise errors.OpPrereqError("Can't set the node into more than one"
4856
                                 " state at the same time",
4857
                                 errors.ECODE_INVAL)
4858

    
4859
    # Boolean value that tells us whether we might be demoting from MC
4860
    self.might_demote = (self.op.master_candidate == False or
4861
                         self.op.offline == True or
4862
                         self.op.drained == True or
4863
                         self.op.master_capable == False)
4864

    
4865
    if self.op.secondary_ip:
4866
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4867
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4868
                                   " address" % self.op.secondary_ip,
4869
                                   errors.ECODE_INVAL)
4870

    
4871
    self.lock_all = self.op.auto_promote and self.might_demote
4872
    self.lock_instances = self.op.secondary_ip is not None
4873

    
4874
  def ExpandNames(self):
4875
    if self.lock_all:
4876
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4877
    else:
4878
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4879

    
4880
    if self.lock_instances:
4881
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4882

    
4883
  def DeclareLocks(self, level):
4884
    # If we have locked all instances, before waiting to lock nodes, release
4885
    # all the ones living on nodes unrelated to the current operation.
4886
    if level == locking.LEVEL_NODE and self.lock_instances:
4887
      self.affected_instances = []
4888
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4889
        instances_keep = []
4890

    
4891
        # Build list of instances to release
4892
        for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
4893
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4894
          if (instance.disk_template in constants.DTS_INT_MIRROR and
4895
              self.op.node_name in instance.all_nodes):
4896
            instances_keep.append(instance_name)
4897
            self.affected_instances.append(instance)
4898

    
4899
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
4900

    
4901
        assert (set(self.glm.list_owned(locking.LEVEL_INSTANCE)) ==
4902
                set(instances_keep))
4903

    
4904
  def BuildHooksEnv(self):
4905
    """Build hooks env.
4906

4907
    This runs on the master node.
4908

4909
    """
4910
    return {
4911
      "OP_TARGET": self.op.node_name,
4912
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4913
      "OFFLINE": str(self.op.offline),
4914
      "DRAINED": str(self.op.drained),
4915
      "MASTER_CAPABLE": str(self.op.master_capable),
4916
      "VM_CAPABLE": str(self.op.vm_capable),
4917
      }
4918

    
4919
  def BuildHooksNodes(self):
4920
    """Build hooks nodes.
4921

4922
    """
4923
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
4924
    return (nl, nl)
4925

    
4926
  def CheckPrereq(self):
4927
    """Check prerequisites.
4928

4929
    This only checks the instance list against the existing names.
4930

4931
    """
4932
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4933

    
4934
    if (self.op.master_candidate is not None or
4935
        self.op.drained is not None or
4936
        self.op.offline is not None):
4937
      # we can't change the master's node flags
4938
      if self.op.node_name == self.cfg.GetMasterNode():
4939
        raise errors.OpPrereqError("The master role can be changed"
4940
                                   " only via master-failover",
4941
                                   errors.ECODE_INVAL)
4942

    
4943
    if self.op.master_candidate and not node.master_capable:
4944
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4945
                                 " it a master candidate" % node.name,
4946
                                 errors.ECODE_STATE)
4947

    
4948
    if self.op.vm_capable == False:
4949
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4950
      if ipri or isec:
4951
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4952
                                   " the vm_capable flag" % node.name,
4953
                                   errors.ECODE_STATE)
4954

    
4955
    if node.master_candidate and self.might_demote and not self.lock_all:
4956
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4957
      # check if after removing the current node, we're missing master
4958
      # candidates
4959
      (mc_remaining, mc_should, _) = \
4960
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4961
      if mc_remaining < mc_should:
4962
        raise errors.OpPrereqError("Not enough master candidates, please"
4963
                                   " pass auto promote option to allow"
4964
                                   " promotion", errors.ECODE_STATE)
4965

    
4966
    self.old_flags = old_flags = (node.master_candidate,
4967
                                  node.drained, node.offline)
4968
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
4969
    self.old_role = old_role = self._F2R[old_flags]
4970

    
4971
    # Check for ineffective changes
4972
    for attr in self._FLAGS:
4973
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4974
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4975
        setattr(self.op, attr, None)
4976

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

    
4980
    # TODO: We might query the real power state if it supports OOB
4981
    if _SupportsOob(self.cfg, node):
4982
      if self.op.offline is False and not (node.powered or
4983
                                           self.op.powered == True):
4984
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
4985
                                    " offline status can be reset") %
4986
                                   self.op.node_name)
4987
    elif self.op.powered is not None:
4988
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4989
                                  " as it does not support out-of-band"
4990
                                  " handling") % self.op.node_name)
4991

    
4992
    # If we're being deofflined/drained, we'll MC ourself if needed
4993
    if (self.op.drained == False or self.op.offline == False or
4994
        (self.op.master_capable and not node.master_capable)):
4995
      if _DecideSelfPromotion(self):
4996
        self.op.master_candidate = True
4997
        self.LogInfo("Auto-promoting node to master candidate")
4998

    
4999
    # If we're no longer master capable, we'll demote ourselves from MC
5000
    if self.op.master_capable == False and node.master_candidate:
5001
      self.LogInfo("Demoting from master candidate")
5002
      self.op.master_candidate = False
5003

    
5004
    # Compute new role
5005
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
5006
    if self.op.master_candidate:
5007
      new_role = self._ROLE_CANDIDATE
5008
    elif self.op.drained:
5009
      new_role = self._ROLE_DRAINED
5010
    elif self.op.offline:
5011
      new_role = self._ROLE_OFFLINE
5012
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
5013
      # False is still in new flags, which means we're un-setting (the
5014
      # only) True flag
5015
      new_role = self._ROLE_REGULAR
5016
    else: # no new flags, nothing, keep old role
5017
      new_role = old_role
5018

    
5019
    self.new_role = new_role
5020

    
5021
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
5022
      # Trying to transition out of offline status
5023
      result = self.rpc.call_version([node.name])[node.name]
5024
      if result.fail_msg:
5025
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
5026
                                   " to report its version: %s" %
5027
                                   (node.name, result.fail_msg),
5028
                                   errors.ECODE_STATE)
5029
      else:
5030
        self.LogWarning("Transitioning node from offline to online state"
5031
                        " without using re-add. Please make sure the node"
5032
                        " is healthy!")
5033

    
5034
    if self.op.secondary_ip:
5035
      # Ok even without locking, because this can't be changed by any LU
5036
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
5037
      master_singlehomed = master.secondary_ip == master.primary_ip
5038
      if master_singlehomed and self.op.secondary_ip:
5039
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
5040
                                   " homed cluster", errors.ECODE_INVAL)
5041

    
5042
      if node.offline:
5043
        if self.affected_instances:
5044
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
5045
                                     " node has instances (%s) configured"
5046
                                     " to use it" % self.affected_instances)
5047
      else:
5048
        # On online nodes, check that no instances are running, and that
5049
        # the node has the new ip and we can reach it.
5050
        for instance in self.affected_instances:
5051
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
5052

    
5053
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
5054
        if master.name != node.name:
5055
          # check reachability from master secondary ip to new secondary ip
5056
          if not netutils.TcpPing(self.op.secondary_ip,
5057
                                  constants.DEFAULT_NODED_PORT,
5058
                                  source=master.secondary_ip):
5059
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5060
                                       " based ping to node daemon port",
5061
                                       errors.ECODE_ENVIRON)
5062

    
5063
    if self.op.ndparams:
5064
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
5065
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
5066
      self.new_ndparams = new_ndparams
5067

    
5068
  def Exec(self, feedback_fn):
5069
    """Modifies a node.
5070

5071
    """
5072
    node = self.node
5073
    old_role = self.old_role
5074
    new_role = self.new_role
5075

    
5076
    result = []
5077

    
5078
    if self.op.ndparams:
5079
      node.ndparams = self.new_ndparams
5080

    
5081
    if self.op.powered is not None:
5082
      node.powered = self.op.powered
5083

    
5084
    for attr in ["master_capable", "vm_capable"]:
5085
      val = getattr(self.op, attr)
5086
      if val is not None:
5087
        setattr(node, attr, val)
5088
        result.append((attr, str(val)))
5089

    
5090
    if new_role != old_role:
5091
      # Tell the node to demote itself, if no longer MC and not offline
5092
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5093
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5094
        if msg:
5095
          self.LogWarning("Node failed to demote itself: %s", msg)
5096

    
5097
      new_flags = self._R2F[new_role]
5098
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5099
        if of != nf:
5100
          result.append((desc, str(nf)))
5101
      (node.master_candidate, node.drained, node.offline) = new_flags
5102

    
5103
      # we locked all nodes, we adjust the CP before updating this node
5104
      if self.lock_all:
5105
        _AdjustCandidatePool(self, [node.name])
5106

    
5107
    if self.op.secondary_ip:
5108
      node.secondary_ip = self.op.secondary_ip
5109
      result.append(("secondary_ip", self.op.secondary_ip))
5110

    
5111
    # this will trigger configuration file update, if needed
5112
    self.cfg.Update(node, feedback_fn)
5113

    
5114
    # this will trigger job queue propagation or cleanup if the mc
5115
    # flag changed
5116
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5117
      self.context.ReaddNode(node)
5118

    
5119
    return result
5120

    
5121

    
5122
class LUNodePowercycle(NoHooksLU):
5123
  """Powercycles a node.
5124

5125
  """
5126
  REQ_BGL = False
5127

    
5128
  def CheckArguments(self):
5129
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5130
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5131
      raise errors.OpPrereqError("The node is the master and the force"
5132
                                 " parameter was not set",
5133
                                 errors.ECODE_INVAL)
5134

    
5135
  def ExpandNames(self):
5136
    """Locking for PowercycleNode.
5137

5138
    This is a last-resort option and shouldn't block on other
5139
    jobs. Therefore, we grab no locks.
5140

5141
    """
5142
    self.needed_locks = {}
5143

    
5144
  def Exec(self, feedback_fn):
5145
    """Reboots a node.
5146

5147
    """
5148
    result = self.rpc.call_node_powercycle(self.op.node_name,
5149
                                           self.cfg.GetHypervisorType())
5150
    result.Raise("Failed to schedule the reboot")
5151
    return result.payload
5152

    
5153

    
5154
class LUClusterQuery(NoHooksLU):
5155
  """Query cluster configuration.
5156

5157
  """
5158
  REQ_BGL = False
5159

    
5160
  def ExpandNames(self):
5161
    self.needed_locks = {}
5162

    
5163
  def Exec(self, feedback_fn):
5164
    """Return cluster config.
5165

5166
    """
5167
    cluster = self.cfg.GetClusterInfo()
5168
    os_hvp = {}
5169

    
5170
    # Filter just for enabled hypervisors
5171
    for os_name, hv_dict in cluster.os_hvp.items():
5172
      os_hvp[os_name] = {}
5173
      for hv_name, hv_params in hv_dict.items():
5174
        if hv_name in cluster.enabled_hypervisors:
5175
          os_hvp[os_name][hv_name] = hv_params
5176

    
5177
    # Convert ip_family to ip_version
5178
    primary_ip_version = constants.IP4_VERSION
5179
    if cluster.primary_ip_family == netutils.IP6Address.family:
5180
      primary_ip_version = constants.IP6_VERSION
5181

    
5182
    result = {
5183
      "software_version": constants.RELEASE_VERSION,
5184
      "protocol_version": constants.PROTOCOL_VERSION,
5185
      "config_version": constants.CONFIG_VERSION,
5186
      "os_api_version": max(constants.OS_API_VERSIONS),
5187
      "export_version": constants.EXPORT_VERSION,
5188
      "architecture": (platform.architecture()[0], platform.machine()),
5189
      "name": cluster.cluster_name,
5190
      "master": cluster.master_node,
5191
      "default_hypervisor": cluster.enabled_hypervisors[0],
5192
      "enabled_hypervisors": cluster.enabled_hypervisors,
5193
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5194
                        for hypervisor_name in cluster.enabled_hypervisors]),
5195
      "os_hvp": os_hvp,
5196
      "beparams": cluster.beparams,
5197
      "osparams": cluster.osparams,
5198
      "nicparams": cluster.nicparams,
5199
      "ndparams": cluster.ndparams,
5200
      "candidate_pool_size": cluster.candidate_pool_size,
5201
      "master_netdev": cluster.master_netdev,
5202
      "volume_group_name": cluster.volume_group_name,
5203
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5204
      "file_storage_dir": cluster.file_storage_dir,
5205
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5206
      "maintain_node_health": cluster.maintain_node_health,
5207
      "ctime": cluster.ctime,
5208
      "mtime": cluster.mtime,
5209
      "uuid": cluster.uuid,
5210
      "tags": list(cluster.GetTags()),
5211
      "uid_pool": cluster.uid_pool,
5212
      "default_iallocator": cluster.default_iallocator,
5213
      "reserved_lvs": cluster.reserved_lvs,
5214
      "primary_ip_version": primary_ip_version,
5215
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5216
      "hidden_os": cluster.hidden_os,
5217
      "blacklisted_os": cluster.blacklisted_os,
5218
      }
5219

    
5220
    return result
5221

    
5222

    
5223
class LUClusterConfigQuery(NoHooksLU):
5224
  """Return configuration values.
5225

5226
  """
5227
  REQ_BGL = False
5228
  _FIELDS_DYNAMIC = utils.FieldSet()
5229
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5230
                                  "watcher_pause", "volume_group_name")
5231

    
5232
  def CheckArguments(self):
5233
    _CheckOutputFields(static=self._FIELDS_STATIC,
5234
                       dynamic=self._FIELDS_DYNAMIC,
5235
                       selected=self.op.output_fields)
5236

    
5237
  def ExpandNames(self):
5238
    self.needed_locks = {}
5239

    
5240
  def Exec(self, feedback_fn):
5241
    """Dump a representation of the cluster config to the standard output.
5242

5243
    """
5244
    values = []
5245
    for field in self.op.output_fields:
5246
      if field == "cluster_name":
5247
        entry = self.cfg.GetClusterName()
5248
      elif field == "master_node":
5249
        entry = self.cfg.GetMasterNode()
5250
      elif field == "drain_flag":
5251
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5252
      elif field == "watcher_pause":
5253
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5254
      elif field == "volume_group_name":
5255
        entry = self.cfg.GetVGName()
5256
      else:
5257
        raise errors.ParameterError(field)
5258
      values.append(entry)
5259
    return values
5260

    
5261

    
5262
class LUInstanceActivateDisks(NoHooksLU):
5263
  """Bring up an instance's disks.
5264

5265
  """
5266
  REQ_BGL = False
5267

    
5268
  def ExpandNames(self):
5269
    self._ExpandAndLockInstance()
5270
    self.needed_locks[locking.LEVEL_NODE] = []
5271
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5272

    
5273
  def DeclareLocks(self, level):
5274
    if level == locking.LEVEL_NODE:
5275
      self._LockInstancesNodes()
5276

    
5277
  def CheckPrereq(self):
5278
    """Check prerequisites.
5279

5280
    This checks that the instance is in the cluster.
5281

5282
    """
5283
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5284
    assert self.instance is not None, \
5285
      "Cannot retrieve locked instance %s" % self.op.instance_name
5286
    _CheckNodeOnline(self, self.instance.primary_node)
5287

    
5288
  def Exec(self, feedback_fn):
5289
    """Activate the disks.
5290

5291
    """
5292
    disks_ok, disks_info = \
5293
              _AssembleInstanceDisks(self, self.instance,
5294
                                     ignore_size=self.op.ignore_size)
5295
    if not disks_ok:
5296
      raise errors.OpExecError("Cannot activate block devices")
5297

    
5298
    return disks_info
5299

    
5300

    
5301
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5302
                           ignore_size=False):
5303
  """Prepare the block devices for an instance.
5304

5305
  This sets up the block devices on all nodes.
5306

5307
  @type lu: L{LogicalUnit}
5308
  @param lu: the logical unit on whose behalf we execute
5309
  @type instance: L{objects.Instance}
5310
  @param instance: the instance for whose disks we assemble
5311
  @type disks: list of L{objects.Disk} or None
5312
  @param disks: which disks to assemble (or all, if None)
5313
  @type ignore_secondaries: boolean
5314
  @param ignore_secondaries: if true, errors on secondary nodes
5315
      won't result in an error return from the function
5316
  @type ignore_size: boolean
5317
  @param ignore_size: if true, the current known size of the disk
5318
      will not be used during the disk activation, useful for cases
5319
      when the size is wrong
5320
  @return: False if the operation failed, otherwise a list of
5321
      (host, instance_visible_name, node_visible_name)
5322
      with the mapping from node devices to instance devices
5323

5324
  """
5325
  device_info = []
5326
  disks_ok = True
5327
  iname = instance.name
5328
  disks = _ExpandCheckDisks(instance, disks)
5329

    
5330
  # With the two passes mechanism we try to reduce the window of
5331
  # opportunity for the race condition of switching DRBD to primary
5332
  # before handshaking occured, but we do not eliminate it
5333

    
5334
  # The proper fix would be to wait (with some limits) until the
5335
  # connection has been made and drbd transitions from WFConnection
5336
  # into any other network-connected state (Connected, SyncTarget,
5337
  # SyncSource, etc.)
5338

    
5339
  # 1st pass, assemble on all nodes in secondary mode
5340
  for idx, inst_disk in enumerate(disks):
5341
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5342
      if ignore_size:
5343
        node_disk = node_disk.Copy()
5344
        node_disk.UnsetSize()
5345
      lu.cfg.SetDiskID(node_disk, node)
5346
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5347
      msg = result.fail_msg
5348
      if msg:
5349
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5350
                           " (is_primary=False, pass=1): %s",
5351
                           inst_disk.iv_name, node, msg)
5352
        if not ignore_secondaries:
5353
          disks_ok = False
5354

    
5355
  # FIXME: race condition on drbd migration to primary
5356

    
5357
  # 2nd pass, do only the primary node
5358
  for idx, inst_disk in enumerate(disks):
5359
    dev_path = None
5360

    
5361
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5362
      if node != instance.primary_node:
5363
        continue
5364
      if ignore_size:
5365
        node_disk = node_disk.Copy()
5366
        node_disk.UnsetSize()
5367
      lu.cfg.SetDiskID(node_disk, node)
5368
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5369
      msg = result.fail_msg
5370
      if msg:
5371
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5372
                           " (is_primary=True, pass=2): %s",
5373
                           inst_disk.iv_name, node, msg)
5374
        disks_ok = False
5375
      else:
5376
        dev_path = result.payload
5377

    
5378
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5379

    
5380
  # leave the disks configured for the primary node
5381
  # this is a workaround that would be fixed better by
5382
  # improving the logical/physical id handling
5383
  for disk in disks:
5384
    lu.cfg.SetDiskID(disk, instance.primary_node)
5385

    
5386
  return disks_ok, device_info
5387

    
5388

    
5389
def _StartInstanceDisks(lu, instance, force):
5390
  """Start the disks of an instance.
5391

5392
  """
5393
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5394
                                           ignore_secondaries=force)
5395
  if not disks_ok:
5396
    _ShutdownInstanceDisks(lu, instance)
5397
    if force is not None and not force:
5398
      lu.proc.LogWarning("", hint="If the message above refers to a"
5399
                         " secondary node,"
5400
                         " you can retry the operation using '--force'.")
5401
    raise errors.OpExecError("Disk consistency error")
5402

    
5403

    
5404
class LUInstanceDeactivateDisks(NoHooksLU):
5405
  """Shutdown an instance's disks.
5406

5407
  """
5408
  REQ_BGL = False
5409

    
5410
  def ExpandNames(self):
5411
    self._ExpandAndLockInstance()
5412
    self.needed_locks[locking.LEVEL_NODE] = []
5413
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5414

    
5415
  def DeclareLocks(self, level):
5416
    if level == locking.LEVEL_NODE:
5417
      self._LockInstancesNodes()
5418

    
5419
  def CheckPrereq(self):
5420
    """Check prerequisites.
5421

5422
    This checks that the instance is in the cluster.
5423

5424
    """
5425
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5426
    assert self.instance is not None, \
5427
      "Cannot retrieve locked instance %s" % self.op.instance_name
5428

    
5429
  def Exec(self, feedback_fn):
5430
    """Deactivate the disks
5431

5432
    """
5433
    instance = self.instance
5434
    if self.op.force:
5435
      _ShutdownInstanceDisks(self, instance)
5436
    else:
5437
      _SafeShutdownInstanceDisks(self, instance)
5438

    
5439

    
5440
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5441
  """Shutdown block devices of an instance.
5442

5443
  This function checks if an instance is running, before calling
5444
  _ShutdownInstanceDisks.
5445

5446
  """
5447
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5448
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5449

    
5450

    
5451
def _ExpandCheckDisks(instance, disks):
5452
  """Return the instance disks selected by the disks list
5453

5454
  @type disks: list of L{objects.Disk} or None
5455
  @param disks: selected disks
5456
  @rtype: list of L{objects.Disk}
5457
  @return: selected instance disks to act on
5458

5459
  """
5460
  if disks is None:
5461
    return instance.disks
5462
  else:
5463
    if not set(disks).issubset(instance.disks):
5464
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5465
                                   " target instance")
5466
    return disks
5467

    
5468

    
5469
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5470
  """Shutdown block devices of an instance.
5471

5472
  This does the shutdown on all nodes of the instance.
5473

5474
  If the ignore_primary is false, errors on the primary node are
5475
  ignored.
5476

5477
  """
5478
  all_result = True
5479
  disks = _ExpandCheckDisks(instance, disks)
5480

    
5481
  for disk in disks:
5482
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5483
      lu.cfg.SetDiskID(top_disk, node)
5484
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5485
      msg = result.fail_msg
5486
      if msg:
5487
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5488
                      disk.iv_name, node, msg)
5489
        if ((node == instance.primary_node and not ignore_primary) or
5490
            (node != instance.primary_node and not result.offline)):
5491
          all_result = False
5492
  return all_result
5493

    
5494

    
5495
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5496
  """Checks if a node has enough free memory.
5497

5498
  This function check if a given node has the needed amount of free
5499
  memory. In case the node has less memory or we cannot get the
5500
  information from the node, this function raise an OpPrereqError
5501
  exception.
5502

5503
  @type lu: C{LogicalUnit}
5504
  @param lu: a logical unit from which we get configuration data
5505
  @type node: C{str}
5506
  @param node: the node to check
5507
  @type reason: C{str}
5508
  @param reason: string to use in the error message
5509
  @type requested: C{int}
5510
  @param requested: the amount of memory in MiB to check for
5511
  @type hypervisor_name: C{str}
5512
  @param hypervisor_name: the hypervisor to ask for memory stats
5513
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5514
      we cannot check the node
5515

5516
  """
5517
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5518
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5519
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5520
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5521
  if not isinstance(free_mem, int):
5522
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5523
                               " was '%s'" % (node, free_mem),
5524
                               errors.ECODE_ENVIRON)
5525
  if requested > free_mem:
5526
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5527
                               " needed %s MiB, available %s MiB" %
5528
                               (node, reason, requested, free_mem),
5529
                               errors.ECODE_NORES)
5530

    
5531

    
5532
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5533
  """Checks if nodes have enough free disk space in the all VGs.
5534

5535
  This function check if all given nodes have the needed amount of
5536
  free disk. In case any node has less disk or we cannot get the
5537
  information from the node, this function raise an OpPrereqError
5538
  exception.
5539

5540
  @type lu: C{LogicalUnit}
5541
  @param lu: a logical unit from which we get configuration data
5542
  @type nodenames: C{list}
5543
  @param nodenames: the list of node names to check
5544
  @type req_sizes: C{dict}
5545
  @param req_sizes: the hash of vg and corresponding amount of disk in
5546
      MiB to check for
5547
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5548
      or we cannot check the node
5549

5550
  """
5551
  for vg, req_size in req_sizes.items():
5552
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5553

    
5554

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

5558
  This function check if all given nodes have the needed amount of
5559
  free disk. In case any node has less disk or we cannot get the
5560
  information from the node, this function raise an OpPrereqError
5561
  exception.
5562

5563
  @type lu: C{LogicalUnit}
5564
  @param lu: a logical unit from which we get configuration data
5565
  @type nodenames: C{list}
5566
  @param nodenames: the list of node names to check
5567
  @type vg: C{str}
5568
  @param vg: the volume group to check
5569
  @type requested: C{int}
5570
  @param requested: the amount of disk in MiB to check for
5571
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5572
      or we cannot check the node
5573

5574
  """
5575
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5576
  for node in nodenames:
5577
    info = nodeinfo[node]
5578
    info.Raise("Cannot get current information from node %s" % node,
5579
               prereq=True, ecode=errors.ECODE_ENVIRON)
5580
    vg_free = info.payload.get("vg_free", None)
5581
    if not isinstance(vg_free, int):
5582
      raise errors.OpPrereqError("Can't compute free disk space on node"
5583
                                 " %s for vg %s, result was '%s'" %
5584
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5585
    if requested > vg_free:
5586
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5587
                                 " vg %s: required %d MiB, available %d MiB" %
5588
                                 (node, vg, requested, vg_free),
5589
                                 errors.ECODE_NORES)
5590

    
5591

    
5592
class LUInstanceStartup(LogicalUnit):
5593
  """Starts an instance.
5594

5595
  """
5596
  HPATH = "instance-start"
5597
  HTYPE = constants.HTYPE_INSTANCE
5598
  REQ_BGL = False
5599

    
5600
  def CheckArguments(self):
5601
    # extra beparams
5602
    if self.op.beparams:
5603
      # fill the beparams dict
5604
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5605

    
5606
  def ExpandNames(self):
5607
    self._ExpandAndLockInstance()
5608

    
5609
  def BuildHooksEnv(self):
5610
    """Build hooks env.
5611

5612
    This runs on master, primary and secondary nodes of the instance.
5613

5614
    """
5615
    env = {
5616
      "FORCE": self.op.force,
5617
      }
5618

    
5619
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5620

    
5621
    return env
5622

    
5623
  def BuildHooksNodes(self):
5624
    """Build hooks nodes.
5625

5626
    """
5627
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5628
    return (nl, nl)
5629

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

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

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

    
5640
    # extra hvparams
5641
    if self.op.hvparams:
5642
      # check hypervisor parameter syntax (locally)
5643
      cluster = self.cfg.GetClusterInfo()
5644
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5645
      filled_hvp = cluster.FillHV(instance)
5646
      filled_hvp.update(self.op.hvparams)
5647
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5648
      hv_type.CheckParameterSyntax(filled_hvp)
5649
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5650

    
5651
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5652

    
5653
    if self.primary_offline and self.op.ignore_offline_nodes:
5654
      self.proc.LogWarning("Ignoring offline primary node")
5655

    
5656
      if self.op.hvparams or self.op.beparams:
5657
        self.proc.LogWarning("Overridden parameters are ignored")
5658
    else:
5659
      _CheckNodeOnline(self, instance.primary_node)
5660

    
5661
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5662

    
5663
      # check bridges existence
5664
      _CheckInstanceBridgesExist(self, instance)
5665

    
5666
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5667
                                                instance.name,
5668
                                                instance.hypervisor)
5669
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5670
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5671
      if not remote_info.payload: # not running already
5672
        _CheckNodeFreeMemory(self, instance.primary_node,
5673
                             "starting instance %s" % instance.name,
5674
                             bep[constants.BE_MEMORY], instance.hypervisor)
5675

    
5676
  def Exec(self, feedback_fn):
5677
    """Start the instance.
5678

5679
    """
5680
    instance = self.instance
5681
    force = self.op.force
5682

    
5683
    if not self.op.no_remember:
5684
      self.cfg.MarkInstanceUp(instance.name)
5685

    
5686
    if self.primary_offline:
5687
      assert self.op.ignore_offline_nodes
5688
      self.proc.LogInfo("Primary node offline, marked instance as started")
5689
    else:
5690
      node_current = instance.primary_node
5691

    
5692
      _StartInstanceDisks(self, instance, force)
5693

    
5694
      result = self.rpc.call_instance_start(node_current, instance,
5695
                                            self.op.hvparams, self.op.beparams)
5696
      msg = result.fail_msg
5697
      if msg:
5698
        _ShutdownInstanceDisks(self, instance)
5699
        raise errors.OpExecError("Could not start instance: %s" % msg)
5700

    
5701

    
5702
class LUInstanceReboot(LogicalUnit):
5703
  """Reboot an instance.
5704

5705
  """
5706
  HPATH = "instance-reboot"
5707
  HTYPE = constants.HTYPE_INSTANCE
5708
  REQ_BGL = False
5709

    
5710
  def ExpandNames(self):
5711
    self._ExpandAndLockInstance()
5712

    
5713
  def BuildHooksEnv(self):
5714
    """Build hooks env.
5715

5716
    This runs on master, primary and secondary nodes of the instance.
5717

5718
    """
5719
    env = {
5720
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5721
      "REBOOT_TYPE": self.op.reboot_type,
5722
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5723
      }
5724

    
5725
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5726

    
5727
    return env
5728

    
5729
  def BuildHooksNodes(self):
5730
    """Build hooks nodes.
5731

5732
    """
5733
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5734
    return (nl, nl)
5735

    
5736
  def CheckPrereq(self):
5737
    """Check prerequisites.
5738

5739
    This checks that the instance is in the cluster.
5740

5741
    """
5742
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5743
    assert self.instance is not None, \
5744
      "Cannot retrieve locked instance %s" % self.op.instance_name
5745

    
5746
    _CheckNodeOnline(self, instance.primary_node)
5747

    
5748
    # check bridges existence
5749
    _CheckInstanceBridgesExist(self, instance)
5750

    
5751
  def Exec(self, feedback_fn):
5752
    """Reboot the instance.
5753

5754
    """
5755
    instance = self.instance
5756
    ignore_secondaries = self.op.ignore_secondaries
5757
    reboot_type = self.op.reboot_type
5758

    
5759
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5760
                                              instance.name,
5761
                                              instance.hypervisor)
5762
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5763
    instance_running = bool(remote_info.payload)
5764

    
5765
    node_current = instance.primary_node
5766

    
5767
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5768
                                            constants.INSTANCE_REBOOT_HARD]:
5769
      for disk in instance.disks:
5770
        self.cfg.SetDiskID(disk, node_current)
5771
      result = self.rpc.call_instance_reboot(node_current, instance,
5772
                                             reboot_type,
5773
                                             self.op.shutdown_timeout)
5774
      result.Raise("Could not reboot instance")
5775
    else:
5776
      if instance_running:
5777
        result = self.rpc.call_instance_shutdown(node_current, instance,
5778
                                                 self.op.shutdown_timeout)
5779
        result.Raise("Could not shutdown instance for full reboot")
5780
        _ShutdownInstanceDisks(self, instance)
5781
      else:
5782
        self.LogInfo("Instance %s was already stopped, starting now",
5783
                     instance.name)
5784
      _StartInstanceDisks(self, instance, ignore_secondaries)
5785
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5786
      msg = result.fail_msg
5787
      if msg:
5788
        _ShutdownInstanceDisks(self, instance)
5789
        raise errors.OpExecError("Could not start instance for"
5790
                                 " full reboot: %s" % msg)
5791

    
5792
    self.cfg.MarkInstanceUp(instance.name)
5793

    
5794

    
5795
class LUInstanceShutdown(LogicalUnit):
5796
  """Shutdown an instance.
5797

5798
  """
5799
  HPATH = "instance-stop"
5800
  HTYPE = constants.HTYPE_INSTANCE
5801
  REQ_BGL = False
5802

    
5803
  def ExpandNames(self):
5804
    self._ExpandAndLockInstance()
5805

    
5806
  def BuildHooksEnv(self):
5807
    """Build hooks env.
5808

5809
    This runs on master, primary and secondary nodes of the instance.
5810

5811
    """
5812
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5813
    env["TIMEOUT"] = self.op.timeout
5814
    return env
5815

    
5816
  def BuildHooksNodes(self):
5817
    """Build hooks nodes.
5818

5819
    """
5820
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5821
    return (nl, nl)
5822

    
5823
  def CheckPrereq(self):
5824
    """Check prerequisites.
5825

5826
    This checks that the instance is in the cluster.
5827

5828
    """
5829
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5830
    assert self.instance is not None, \
5831
      "Cannot retrieve locked instance %s" % self.op.instance_name
5832

    
5833
    self.primary_offline = \
5834
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5835

    
5836
    if self.primary_offline and self.op.ignore_offline_nodes:
5837
      self.proc.LogWarning("Ignoring offline primary node")
5838
    else:
5839
      _CheckNodeOnline(self, self.instance.primary_node)
5840

    
5841
  def Exec(self, feedback_fn):
5842
    """Shutdown the instance.
5843

5844
    """
5845
    instance = self.instance
5846
    node_current = instance.primary_node
5847
    timeout = self.op.timeout
5848

    
5849
    if not self.op.no_remember:
5850
      self.cfg.MarkInstanceDown(instance.name)
5851

    
5852
    if self.primary_offline:
5853
      assert self.op.ignore_offline_nodes
5854
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5855
    else:
5856
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5857
      msg = result.fail_msg
5858
      if msg:
5859
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5860

    
5861
      _ShutdownInstanceDisks(self, instance)
5862

    
5863

    
5864
class LUInstanceReinstall(LogicalUnit):
5865
  """Reinstall an instance.
5866

5867
  """
5868
  HPATH = "instance-reinstall"
5869
  HTYPE = constants.HTYPE_INSTANCE
5870
  REQ_BGL = False
5871

    
5872
  def ExpandNames(self):
5873
    self._ExpandAndLockInstance()
5874

    
5875
  def BuildHooksEnv(self):
5876
    """Build hooks env.
5877

5878
    This runs on master, primary and secondary nodes of the instance.
5879

5880
    """
5881
    return _BuildInstanceHookEnvByObject(self, self.instance)
5882

    
5883
  def BuildHooksNodes(self):
5884
    """Build hooks nodes.
5885

5886
    """
5887
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5888
    return (nl, nl)
5889

    
5890
  def CheckPrereq(self):
5891
    """Check prerequisites.
5892

5893
    This checks that the instance is in the cluster and is not running.
5894

5895
    """
5896
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5897
    assert instance is not None, \
5898
      "Cannot retrieve locked instance %s" % self.op.instance_name
5899
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5900
                     " offline, cannot reinstall")
5901
    for node in instance.secondary_nodes:
5902
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5903
                       " cannot reinstall")
5904

    
5905
    if instance.disk_template == constants.DT_DISKLESS:
5906
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5907
                                 self.op.instance_name,
5908
                                 errors.ECODE_INVAL)
5909
    _CheckInstanceDown(self, instance, "cannot reinstall")
5910

    
5911
    if self.op.os_type is not None:
5912
      # OS verification
5913
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5914
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5915
      instance_os = self.op.os_type
5916
    else:
5917
      instance_os = instance.os
5918

    
5919
    nodelist = list(instance.all_nodes)
5920

    
5921
    if self.op.osparams:
5922
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5923
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5924
      self.os_inst = i_osdict # the new dict (without defaults)
5925
    else:
5926
      self.os_inst = None
5927

    
5928
    self.instance = instance
5929

    
5930
  def Exec(self, feedback_fn):
5931
    """Reinstall the instance.
5932

5933
    """
5934
    inst = self.instance
5935

    
5936
    if self.op.os_type is not None:
5937
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5938
      inst.os = self.op.os_type
5939
      # Write to configuration
5940
      self.cfg.Update(inst, feedback_fn)
5941

    
5942
    _StartInstanceDisks(self, inst, None)
5943
    try:
5944
      feedback_fn("Running the instance OS create scripts...")
5945
      # FIXME: pass debug option from opcode to backend
5946
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5947
                                             self.op.debug_level,
5948
                                             osparams=self.os_inst)
5949
      result.Raise("Could not install OS for instance %s on node %s" %
5950
                   (inst.name, inst.primary_node))
5951
    finally:
5952
      _ShutdownInstanceDisks(self, inst)
5953

    
5954

    
5955
class LUInstanceRecreateDisks(LogicalUnit):
5956
  """Recreate an instance's missing disks.
5957

5958
  """
5959
  HPATH = "instance-recreate-disks"
5960
  HTYPE = constants.HTYPE_INSTANCE
5961
  REQ_BGL = False
5962

    
5963
  def CheckArguments(self):
5964
    # normalise the disk list
5965
    self.op.disks = sorted(frozenset(self.op.disks))
5966

    
5967
  def ExpandNames(self):
5968
    self._ExpandAndLockInstance()
5969
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5970
    if self.op.nodes:
5971
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5972
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5973
    else:
5974
      self.needed_locks[locking.LEVEL_NODE] = []
5975

    
5976
  def DeclareLocks(self, level):
5977
    if level == locking.LEVEL_NODE:
5978
      # if we replace the nodes, we only need to lock the old primary,
5979
      # otherwise we need to lock all nodes for disk re-creation
5980
      primary_only = bool(self.op.nodes)
5981
      self._LockInstancesNodes(primary_only=primary_only)
5982

    
5983
  def BuildHooksEnv(self):
5984
    """Build hooks env.
5985

5986
    This runs on master, primary and secondary nodes of the instance.
5987

5988
    """
5989
    return _BuildInstanceHookEnvByObject(self, self.instance)
5990

    
5991
  def BuildHooksNodes(self):
5992
    """Build hooks nodes.
5993

5994
    """
5995
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5996
    return (nl, nl)
5997

    
5998
  def CheckPrereq(self):
5999
    """Check prerequisites.
6000

6001
    This checks that the instance is in the cluster and is not running.
6002

6003
    """
6004
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6005
    assert instance is not None, \
6006
      "Cannot retrieve locked instance %s" % self.op.instance_name
6007
    if self.op.nodes:
6008
      if len(self.op.nodes) != len(instance.all_nodes):
6009
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6010
                                   " %d replacement nodes were specified" %
6011
                                   (instance.name, len(instance.all_nodes),
6012
                                    len(self.op.nodes)),
6013
                                   errors.ECODE_INVAL)
6014
      assert instance.disk_template != constants.DT_DRBD8 or \
6015
          len(self.op.nodes) == 2
6016
      assert instance.disk_template != constants.DT_PLAIN or \
6017
          len(self.op.nodes) == 1
6018
      primary_node = self.op.nodes[0]
6019
    else:
6020
      primary_node = instance.primary_node
6021
    _CheckNodeOnline(self, primary_node)
6022

    
6023
    if instance.disk_template == constants.DT_DISKLESS:
6024
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6025
                                 self.op.instance_name, errors.ECODE_INVAL)
6026
    # if we replace nodes *and* the old primary is offline, we don't
6027
    # check
6028
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
6029
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6030
    if not (self.op.nodes and old_pnode.offline):
6031
      _CheckInstanceDown(self, instance, "cannot recreate disks")
6032

    
6033
    if not self.op.disks:
6034
      self.op.disks = range(len(instance.disks))
6035
    else:
6036
      for idx in self.op.disks:
6037
        if idx >= len(instance.disks):
6038
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6039
                                     errors.ECODE_INVAL)
6040
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6041
      raise errors.OpPrereqError("Can't recreate disks partially and"
6042
                                 " change the nodes at the same time",
6043
                                 errors.ECODE_INVAL)
6044
    self.instance = instance
6045

    
6046
  def Exec(self, feedback_fn):
6047
    """Recreate the disks.
6048

6049
    """
6050
    # change primary node, if needed
6051
    if self.op.nodes:
6052
      self.instance.primary_node = self.op.nodes[0]
6053
      self.LogWarning("Changing the instance's nodes, you will have to"
6054
                      " remove any disks left on the older nodes manually")
6055

    
6056
    to_skip = []
6057
    for idx, disk in enumerate(self.instance.disks):
6058
      if idx not in self.op.disks: # disk idx has not been passed in
6059
        to_skip.append(idx)
6060
        continue
6061
      # update secondaries for disks, if needed
6062
      if self.op.nodes:
6063
        if disk.dev_type == constants.LD_DRBD8:
6064
          # need to update the nodes
6065
          assert len(self.op.nodes) == 2
6066
          logical_id = list(disk.logical_id)
6067
          logical_id[0] = self.op.nodes[0]
6068
          logical_id[1] = self.op.nodes[1]
6069
          disk.logical_id = tuple(logical_id)
6070

    
6071
    if self.op.nodes:
6072
      self.cfg.Update(self.instance, feedback_fn)
6073

    
6074
    _CreateDisks(self, self.instance, to_skip=to_skip)
6075

    
6076

    
6077
class LUInstanceRename(LogicalUnit):
6078
  """Rename an instance.
6079

6080
  """
6081
  HPATH = "instance-rename"
6082
  HTYPE = constants.HTYPE_INSTANCE
6083

    
6084
  def CheckArguments(self):
6085
    """Check arguments.
6086

6087
    """
6088
    if self.op.ip_check and not self.op.name_check:
6089
      # TODO: make the ip check more flexible and not depend on the name check
6090
      raise errors.OpPrereqError("IP address check requires a name check",
6091
                                 errors.ECODE_INVAL)
6092

    
6093
  def BuildHooksEnv(self):
6094
    """Build hooks env.
6095

6096
    This runs on master, primary and secondary nodes of the instance.
6097

6098
    """
6099
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6100
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6101
    return env
6102

    
6103
  def BuildHooksNodes(self):
6104
    """Build hooks nodes.
6105

6106
    """
6107
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6108
    return (nl, nl)
6109

    
6110
  def CheckPrereq(self):
6111
    """Check prerequisites.
6112

6113
    This checks that the instance is in the cluster and is not running.
6114

6115
    """
6116
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6117
                                                self.op.instance_name)
6118
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6119
    assert instance is not None
6120
    _CheckNodeOnline(self, instance.primary_node)
6121
    _CheckInstanceDown(self, instance, "cannot rename")
6122
    self.instance = instance
6123

    
6124
    new_name = self.op.new_name
6125
    if self.op.name_check:
6126
      hostname = netutils.GetHostname(name=new_name)
6127
      if hostname != new_name:
6128
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6129
                     hostname.name)
6130
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6131
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6132
                                    " same as given hostname '%s'") %
6133
                                    (hostname.name, self.op.new_name),
6134
                                    errors.ECODE_INVAL)
6135
      new_name = self.op.new_name = hostname.name
6136
      if (self.op.ip_check and
6137
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6138
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6139
                                   (hostname.ip, new_name),
6140
                                   errors.ECODE_NOTUNIQUE)
6141

    
6142
    instance_list = self.cfg.GetInstanceList()
6143
    if new_name in instance_list and new_name != instance.name:
6144
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6145
                                 new_name, errors.ECODE_EXISTS)
6146

    
6147
  def Exec(self, feedback_fn):
6148
    """Rename the instance.
6149

6150
    """
6151
    inst = self.instance
6152
    old_name = inst.name
6153

    
6154
    rename_file_storage = False
6155
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
6156
        self.op.new_name != inst.name):
6157
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6158
      rename_file_storage = True
6159

    
6160
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6161
    # Change the instance lock. This is definitely safe while we hold the BGL.
6162
    # Otherwise the new lock would have to be added in acquired mode.
6163
    assert self.REQ_BGL
6164
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6165
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6166

    
6167
    # re-read the instance from the configuration after rename
6168
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6169

    
6170
    if rename_file_storage:
6171
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6172
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6173
                                                     old_file_storage_dir,
6174
                                                     new_file_storage_dir)
6175
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6176
                   " (but the instance has been renamed in Ganeti)" %
6177
                   (inst.primary_node, old_file_storage_dir,
6178
                    new_file_storage_dir))
6179

    
6180
    _StartInstanceDisks(self, inst, None)
6181
    try:
6182
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6183
                                                 old_name, self.op.debug_level)
6184
      msg = result.fail_msg
6185
      if msg:
6186
        msg = ("Could not run OS rename script for instance %s on node %s"
6187
               " (but the instance has been renamed in Ganeti): %s" %
6188
               (inst.name, inst.primary_node, msg))
6189
        self.proc.LogWarning(msg)
6190
    finally:
6191
      _ShutdownInstanceDisks(self, inst)
6192

    
6193
    return inst.name
6194

    
6195

    
6196
class LUInstanceRemove(LogicalUnit):
6197
  """Remove an instance.
6198

6199
  """
6200
  HPATH = "instance-remove"
6201
  HTYPE = constants.HTYPE_INSTANCE
6202
  REQ_BGL = False
6203

    
6204
  def ExpandNames(self):
6205
    self._ExpandAndLockInstance()
6206
    self.needed_locks[locking.LEVEL_NODE] = []
6207
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6208

    
6209
  def DeclareLocks(self, level):
6210
    if level == locking.LEVEL_NODE:
6211
      self._LockInstancesNodes()
6212

    
6213
  def BuildHooksEnv(self):
6214
    """Build hooks env.
6215

6216
    This runs on master, primary and secondary nodes of the instance.
6217

6218
    """
6219
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6220
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6221
    return env
6222

    
6223
  def BuildHooksNodes(self):
6224
    """Build hooks nodes.
6225

6226
    """
6227
    nl = [self.cfg.GetMasterNode()]
6228
    nl_post = list(self.instance.all_nodes) + nl
6229
    return (nl, nl_post)
6230

    
6231
  def CheckPrereq(self):
6232
    """Check prerequisites.
6233

6234
    This checks that the instance is in the cluster.
6235

6236
    """
6237
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6238
    assert self.instance is not None, \
6239
      "Cannot retrieve locked instance %s" % self.op.instance_name
6240

    
6241
  def Exec(self, feedback_fn):
6242
    """Remove the instance.
6243

6244
    """
6245
    instance = self.instance
6246
    logging.info("Shutting down instance %s on node %s",
6247
                 instance.name, instance.primary_node)
6248

    
6249
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6250
                                             self.op.shutdown_timeout)
6251
    msg = result.fail_msg
6252
    if msg:
6253
      if self.op.ignore_failures:
6254
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6255
      else:
6256
        raise errors.OpExecError("Could not shutdown instance %s on"
6257
                                 " node %s: %s" %
6258
                                 (instance.name, instance.primary_node, msg))
6259

    
6260
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6261

    
6262

    
6263
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6264
  """Utility function to remove an instance.
6265

6266
  """
6267
  logging.info("Removing block devices for instance %s", instance.name)
6268

    
6269
  if not _RemoveDisks(lu, instance):
6270
    if not ignore_failures:
6271
      raise errors.OpExecError("Can't remove instance's disks")
6272
    feedback_fn("Warning: can't remove instance's disks")
6273

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

    
6276
  lu.cfg.RemoveInstance(instance.name)
6277

    
6278
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6279
    "Instance lock removal conflict"
6280

    
6281
  # Remove lock for the instance
6282
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6283

    
6284

    
6285
class LUInstanceQuery(NoHooksLU):
6286
  """Logical unit for querying instances.
6287

6288
  """
6289
  # pylint: disable-msg=W0142
6290
  REQ_BGL = False
6291

    
6292
  def CheckArguments(self):
6293
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6294
                             self.op.output_fields, self.op.use_locking)
6295

    
6296
  def ExpandNames(self):
6297
    self.iq.ExpandNames(self)
6298

    
6299
  def DeclareLocks(self, level):
6300
    self.iq.DeclareLocks(self, level)
6301

    
6302
  def Exec(self, feedback_fn):
6303
    return self.iq.OldStyleQuery(self)
6304

    
6305

    
6306
class LUInstanceFailover(LogicalUnit):
6307
  """Failover an instance.
6308

6309
  """
6310
  HPATH = "instance-failover"
6311
  HTYPE = constants.HTYPE_INSTANCE
6312
  REQ_BGL = False
6313

    
6314
  def CheckArguments(self):
6315
    """Check the arguments.
6316

6317
    """
6318
    self.iallocator = getattr(self.op, "iallocator", None)
6319
    self.target_node = getattr(self.op, "target_node", None)
6320

    
6321
  def ExpandNames(self):
6322
    self._ExpandAndLockInstance()
6323

    
6324
    if self.op.target_node is not None:
6325
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6326

    
6327
    self.needed_locks[locking.LEVEL_NODE] = []
6328
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6329

    
6330
    ignore_consistency = self.op.ignore_consistency
6331
    shutdown_timeout = self.op.shutdown_timeout
6332
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6333
                                       cleanup=False,
6334
                                       failover=True,
6335
                                       ignore_consistency=ignore_consistency,
6336
                                       shutdown_timeout=shutdown_timeout)
6337
    self.tasklets = [self._migrater]
6338

    
6339
  def DeclareLocks(self, level):
6340
    if level == locking.LEVEL_NODE:
6341
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6342
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6343
        if self.op.target_node is None:
6344
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6345
        else:
6346
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6347
                                                   self.op.target_node]
6348
        del self.recalculate_locks[locking.LEVEL_NODE]
6349
      else:
6350
        self._LockInstancesNodes()
6351

    
6352
  def BuildHooksEnv(self):
6353
    """Build hooks env.
6354

6355
    This runs on master, primary and secondary nodes of the instance.
6356

6357
    """
6358
    instance = self._migrater.instance
6359
    source_node = instance.primary_node
6360
    target_node = self.op.target_node
6361
    env = {
6362
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6363
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6364
      "OLD_PRIMARY": source_node,
6365
      "NEW_PRIMARY": target_node,
6366
      }
6367

    
6368
    if instance.disk_template in constants.DTS_INT_MIRROR:
6369
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6370
      env["NEW_SECONDARY"] = source_node
6371
    else:
6372
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6373

    
6374
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6375

    
6376
    return env
6377

    
6378
  def BuildHooksNodes(self):
6379
    """Build hooks nodes.
6380

6381
    """
6382
    instance = self._migrater.instance
6383
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6384
    return (nl, nl + [instance.primary_node])
6385

    
6386

    
6387
class LUInstanceMigrate(LogicalUnit):
6388
  """Migrate an instance.
6389

6390
  This is migration without shutting down, compared to the failover,
6391
  which is done with shutdown.
6392

6393
  """
6394
  HPATH = "instance-migrate"
6395
  HTYPE = constants.HTYPE_INSTANCE
6396
  REQ_BGL = False
6397

    
6398
  def ExpandNames(self):
6399
    self._ExpandAndLockInstance()
6400

    
6401
    if self.op.target_node is not None:
6402
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6403

    
6404
    self.needed_locks[locking.LEVEL_NODE] = []
6405
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6406

    
6407
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6408
                                       cleanup=self.op.cleanup,
6409
                                       failover=False,
6410
                                       fallback=self.op.allow_failover)
6411
    self.tasklets = [self._migrater]
6412

    
6413
  def DeclareLocks(self, level):
6414
    if level == locking.LEVEL_NODE:
6415
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6416
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6417
        if self.op.target_node is None:
6418
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6419
        else:
6420
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6421
                                                   self.op.target_node]
6422
        del self.recalculate_locks[locking.LEVEL_NODE]
6423
      else:
6424
        self._LockInstancesNodes()
6425

    
6426
  def BuildHooksEnv(self):
6427
    """Build hooks env.
6428

6429
    This runs on master, primary and secondary nodes of the instance.
6430

6431
    """
6432
    instance = self._migrater.instance
6433
    source_node = instance.primary_node
6434
    target_node = self.op.target_node
6435
    env = _BuildInstanceHookEnvByObject(self, instance)
6436
    env.update({
6437
      "MIGRATE_LIVE": self._migrater.live,
6438
      "MIGRATE_CLEANUP": self.op.cleanup,
6439
      "OLD_PRIMARY": source_node,
6440
      "NEW_PRIMARY": target_node,
6441
      })
6442

    
6443
    if instance.disk_template in constants.DTS_INT_MIRROR:
6444
      env["OLD_SECONDARY"] = target_node
6445
      env["NEW_SECONDARY"] = source_node
6446
    else:
6447
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6448

    
6449
    return env
6450

    
6451
  def BuildHooksNodes(self):
6452
    """Build hooks nodes.
6453

6454
    """
6455
    instance = self._migrater.instance
6456
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6457
    return (nl, nl + [instance.primary_node])
6458

    
6459

    
6460
class LUInstanceMove(LogicalUnit):
6461
  """Move an instance by data-copying.
6462

6463
  """
6464
  HPATH = "instance-move"
6465
  HTYPE = constants.HTYPE_INSTANCE
6466
  REQ_BGL = False
6467

    
6468
  def ExpandNames(self):
6469
    self._ExpandAndLockInstance()
6470
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6471
    self.op.target_node = target_node
6472
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6473
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6474

    
6475
  def DeclareLocks(self, level):
6476
    if level == locking.LEVEL_NODE:
6477
      self._LockInstancesNodes(primary_only=True)
6478

    
6479
  def BuildHooksEnv(self):
6480
    """Build hooks env.
6481

6482
    This runs on master, primary and secondary nodes of the instance.
6483

6484
    """
6485
    env = {
6486
      "TARGET_NODE": self.op.target_node,
6487
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6488
      }
6489
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6490
    return env
6491

    
6492
  def BuildHooksNodes(self):
6493
    """Build hooks nodes.
6494

6495
    """
6496
    nl = [
6497
      self.cfg.GetMasterNode(),
6498
      self.instance.primary_node,
6499
      self.op.target_node,
6500
      ]
6501
    return (nl, nl)
6502

    
6503
  def CheckPrereq(self):
6504
    """Check prerequisites.
6505

6506
    This checks that the instance is in the cluster.
6507

6508
    """
6509
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6510
    assert self.instance is not None, \
6511
      "Cannot retrieve locked instance %s" % self.op.instance_name
6512

    
6513
    node = self.cfg.GetNodeInfo(self.op.target_node)
6514
    assert node is not None, \
6515
      "Cannot retrieve locked node %s" % self.op.target_node
6516

    
6517
    self.target_node = target_node = node.name
6518

    
6519
    if target_node == instance.primary_node:
6520
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6521
                                 (instance.name, target_node),
6522
                                 errors.ECODE_STATE)
6523

    
6524
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6525

    
6526
    for idx, dsk in enumerate(instance.disks):
6527
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6528
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6529
                                   " cannot copy" % idx, errors.ECODE_STATE)
6530

    
6531
    _CheckNodeOnline(self, target_node)
6532
    _CheckNodeNotDrained(self, target_node)
6533
    _CheckNodeVmCapable(self, target_node)
6534

    
6535
    if instance.admin_up:
6536
      # check memory requirements on the secondary node
6537
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6538
                           instance.name, bep[constants.BE_MEMORY],
6539
                           instance.hypervisor)
6540
    else:
6541
      self.LogInfo("Not checking memory on the secondary node as"
6542
                   " instance will not be started")
6543

    
6544
    # check bridge existance
6545
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6546

    
6547
  def Exec(self, feedback_fn):
6548
    """Move an instance.
6549

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

6553
    """
6554
    instance = self.instance
6555

    
6556
    source_node = instance.primary_node
6557
    target_node = self.target_node
6558

    
6559
    self.LogInfo("Shutting down instance %s on source node %s",
6560
                 instance.name, source_node)
6561

    
6562
    result = self.rpc.call_instance_shutdown(source_node, instance,
6563
                                             self.op.shutdown_timeout)
6564
    msg = result.fail_msg
6565
    if msg:
6566
      if self.op.ignore_consistency:
6567
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6568
                             " Proceeding anyway. Please make sure node"
6569
                             " %s is down. Error details: %s",
6570
                             instance.name, source_node, source_node, msg)
6571
      else:
6572
        raise errors.OpExecError("Could not shutdown instance %s on"
6573
                                 " node %s: %s" %
6574
                                 (instance.name, source_node, msg))
6575

    
6576
    # create the target disks
6577
    try:
6578
      _CreateDisks(self, instance, target_node=target_node)
6579
    except errors.OpExecError:
6580
      self.LogWarning("Device creation failed, reverting...")
6581
      try:
6582
        _RemoveDisks(self, instance, target_node=target_node)
6583
      finally:
6584
        self.cfg.ReleaseDRBDMinors(instance.name)
6585
        raise
6586

    
6587
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6588

    
6589
    errs = []
6590
    # activate, get path, copy the data over
6591
    for idx, disk in enumerate(instance.disks):
6592
      self.LogInfo("Copying data for disk %d", idx)
6593
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6594
                                               instance.name, True, idx)
6595
      if result.fail_msg:
6596
        self.LogWarning("Can't assemble newly created disk %d: %s",
6597
                        idx, result.fail_msg)
6598
        errs.append(result.fail_msg)
6599
        break
6600
      dev_path = result.payload
6601
      result = self.rpc.call_blockdev_export(source_node, disk,
6602
                                             target_node, dev_path,
6603
                                             cluster_name)
6604
      if result.fail_msg:
6605
        self.LogWarning("Can't copy data over for disk %d: %s",
6606
                        idx, result.fail_msg)
6607
        errs.append(result.fail_msg)
6608
        break
6609

    
6610
    if errs:
6611
      self.LogWarning("Some disks failed to copy, aborting")
6612
      try:
6613
        _RemoveDisks(self, instance, target_node=target_node)
6614
      finally:
6615
        self.cfg.ReleaseDRBDMinors(instance.name)
6616
        raise errors.OpExecError("Errors during disk copy: %s" %
6617
                                 (",".join(errs),))
6618

    
6619
    instance.primary_node = target_node
6620
    self.cfg.Update(instance, feedback_fn)
6621

    
6622
    self.LogInfo("Removing the disks on the original node")
6623
    _RemoveDisks(self, instance, target_node=source_node)
6624

    
6625
    # Only start the instance if it's marked as up
6626
    if instance.admin_up:
6627
      self.LogInfo("Starting instance %s on node %s",
6628
                   instance.name, target_node)
6629

    
6630
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6631
                                           ignore_secondaries=True)
6632
      if not disks_ok:
6633
        _ShutdownInstanceDisks(self, instance)
6634
        raise errors.OpExecError("Can't activate the instance's disks")
6635

    
6636
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6637
      msg = result.fail_msg
6638
      if msg:
6639
        _ShutdownInstanceDisks(self, instance)
6640
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6641
                                 (instance.name, target_node, msg))
6642

    
6643

    
6644
class LUNodeMigrate(LogicalUnit):
6645
  """Migrate all instances from a node.
6646

6647
  """
6648
  HPATH = "node-migrate"
6649
  HTYPE = constants.HTYPE_NODE
6650
  REQ_BGL = False
6651

    
6652
  def CheckArguments(self):
6653
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6654

    
6655
  def ExpandNames(self):
6656
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6657

    
6658
    self.needed_locks = {}
6659

    
6660
    # Create tasklets for migrating instances for all instances on this node
6661
    names = []
6662
    tasklets = []
6663

    
6664
    self.lock_all_nodes = False
6665

    
6666
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6667
      logging.debug("Migrating instance %s", inst.name)
6668
      names.append(inst.name)
6669

    
6670
      tasklets.append(TLMigrateInstance(self, inst.name, cleanup=False))
6671

    
6672
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6673
        # We need to lock all nodes, as the iallocator will choose the
6674
        # destination nodes afterwards
6675
        self.lock_all_nodes = True
6676

    
6677
    self.tasklets = tasklets
6678

    
6679
    # Declare node locks
6680
    if self.lock_all_nodes:
6681
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6682
    else:
6683
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6684
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6685

    
6686
    # Declare instance locks
6687
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6688

    
6689
  def DeclareLocks(self, level):
6690
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6691
      self._LockInstancesNodes()
6692

    
6693
  def BuildHooksEnv(self):
6694
    """Build hooks env.
6695

6696
    This runs on the master, the primary and all the secondaries.
6697

6698
    """
6699
    return {
6700
      "NODE_NAME": self.op.node_name,
6701
      }
6702

    
6703
  def BuildHooksNodes(self):
6704
    """Build hooks nodes.
6705

6706
    """
6707
    nl = [self.cfg.GetMasterNode()]
6708
    return (nl, nl)
6709

    
6710

    
6711
class TLMigrateInstance(Tasklet):
6712
  """Tasklet class for instance migration.
6713

6714
  @type live: boolean
6715
  @ivar live: whether the migration will be done live or non-live;
6716
      this variable is initalized only after CheckPrereq has run
6717
  @type cleanup: boolean
6718
  @ivar cleanup: Wheater we cleanup from a failed migration
6719
  @type iallocator: string
6720
  @ivar iallocator: The iallocator used to determine target_node
6721
  @type target_node: string
6722
  @ivar target_node: If given, the target_node to reallocate the instance to
6723
  @type failover: boolean
6724
  @ivar failover: Whether operation results in failover or migration
6725
  @type fallback: boolean
6726
  @ivar fallback: Whether fallback to failover is allowed if migration not
6727
                  possible
6728
  @type ignore_consistency: boolean
6729
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6730
                            and target node
6731
  @type shutdown_timeout: int
6732
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6733

6734
  """
6735
  def __init__(self, lu, instance_name, cleanup=False,
6736
               failover=False, fallback=False,
6737
               ignore_consistency=False,
6738
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6739
    """Initializes this class.
6740

6741
    """
6742
    Tasklet.__init__(self, lu)
6743

    
6744
    # Parameters
6745
    self.instance_name = instance_name
6746
    self.cleanup = cleanup
6747
    self.live = False # will be overridden later
6748
    self.failover = failover
6749
    self.fallback = fallback
6750
    self.ignore_consistency = ignore_consistency
6751
    self.shutdown_timeout = shutdown_timeout
6752

    
6753
  def CheckPrereq(self):
6754
    """Check prerequisites.
6755

6756
    This checks that the instance is in the cluster.
6757

6758
    """
6759
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6760
    instance = self.cfg.GetInstanceInfo(instance_name)
6761
    assert instance is not None
6762
    self.instance = instance
6763

    
6764
    if (not self.cleanup and not instance.admin_up and not self.failover and
6765
        self.fallback):
6766
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6767
                      " to failover")
6768
      self.failover = True
6769

    
6770
    if instance.disk_template not in constants.DTS_MIRRORED:
6771
      if self.failover:
6772
        text = "failovers"
6773
      else:
6774
        text = "migrations"
6775
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6776
                                 " %s" % (instance.disk_template, text),
6777
                                 errors.ECODE_STATE)
6778

    
6779
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6780
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6781

    
6782
      if self.lu.op.iallocator:
6783
        self._RunAllocator()
6784
      else:
6785
        # We set set self.target_node as it is required by
6786
        # BuildHooksEnv
6787
        self.target_node = self.lu.op.target_node
6788

    
6789
      # self.target_node is already populated, either directly or by the
6790
      # iallocator run
6791
      target_node = self.target_node
6792
      if self.target_node == instance.primary_node:
6793
        raise errors.OpPrereqError("Cannot migrate instance %s"
6794
                                   " to its primary (%s)" %
6795
                                   (instance.name, instance.primary_node))
6796

    
6797
      if len(self.lu.tasklets) == 1:
6798
        # It is safe to release locks only when we're the only tasklet
6799
        # in the LU
6800
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6801
                      keep=[instance.primary_node, self.target_node])
6802

    
6803
    else:
6804
      secondary_nodes = instance.secondary_nodes
6805
      if not secondary_nodes:
6806
        raise errors.ConfigurationError("No secondary node but using"
6807
                                        " %s disk template" %
6808
                                        instance.disk_template)
6809
      target_node = secondary_nodes[0]
6810
      if self.lu.op.iallocator or (self.lu.op.target_node and
6811
                                   self.lu.op.target_node != target_node):
6812
        if self.failover:
6813
          text = "failed over"
6814
        else:
6815
          text = "migrated"
6816
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6817
                                   " be %s to arbitrary nodes"
6818
                                   " (neither an iallocator nor a target"
6819
                                   " node can be passed)" %
6820
                                   (instance.disk_template, text),
6821
                                   errors.ECODE_INVAL)
6822

    
6823
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6824

    
6825
    # check memory requirements on the secondary node
6826
    if not self.failover or instance.admin_up:
6827
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6828
                           instance.name, i_be[constants.BE_MEMORY],
6829
                           instance.hypervisor)
6830
    else:
6831
      self.lu.LogInfo("Not checking memory on the secondary node as"
6832
                      " instance will not be started")
6833

    
6834
    # check bridge existance
6835
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6836

    
6837
    if not self.cleanup:
6838
      _CheckNodeNotDrained(self.lu, target_node)
6839
      if not self.failover:
6840
        result = self.rpc.call_instance_migratable(instance.primary_node,
6841
                                                   instance)
6842
        if result.fail_msg and self.fallback:
6843
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6844
                          " failover")
6845
          self.failover = True
6846
        else:
6847
          result.Raise("Can't migrate, please use failover",
6848
                       prereq=True, ecode=errors.ECODE_STATE)
6849

    
6850
    assert not (self.failover and self.cleanup)
6851

    
6852
    if not self.failover:
6853
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6854
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6855
                                   " parameters are accepted",
6856
                                   errors.ECODE_INVAL)
6857
      if self.lu.op.live is not None:
6858
        if self.lu.op.live:
6859
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6860
        else:
6861
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6862
        # reset the 'live' parameter to None so that repeated
6863
        # invocations of CheckPrereq do not raise an exception
6864
        self.lu.op.live = None
6865
      elif self.lu.op.mode is None:
6866
        # read the default value from the hypervisor
6867
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6868
                                                skip_globals=False)
6869
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6870

    
6871
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6872
    else:
6873
      # Failover is never live
6874
      self.live = False
6875

    
6876
  def _RunAllocator(self):
6877
    """Run the allocator based on input opcode.
6878

6879
    """
6880
    ial = IAllocator(self.cfg, self.rpc,
6881
                     mode=constants.IALLOCATOR_MODE_RELOC,
6882
                     name=self.instance_name,
6883
                     # TODO See why hail breaks with a single node below
6884
                     relocate_from=[self.instance.primary_node,
6885
                                    self.instance.primary_node],
6886
                     )
6887

    
6888
    ial.Run(self.lu.op.iallocator)
6889

    
6890
    if not ial.success:
6891
      raise errors.OpPrereqError("Can't compute nodes using"
6892
                                 " iallocator '%s': %s" %
6893
                                 (self.lu.op.iallocator, ial.info),
6894
                                 errors.ECODE_NORES)
6895
    if len(ial.result) != ial.required_nodes:
6896
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6897
                                 " of nodes (%s), required %s" %
6898
                                 (self.lu.op.iallocator, len(ial.result),
6899
                                  ial.required_nodes), errors.ECODE_FAULT)
6900
    self.target_node = ial.result[0]
6901
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6902
                 self.instance_name, self.lu.op.iallocator,
6903
                 utils.CommaJoin(ial.result))
6904

    
6905
  def _WaitUntilSync(self):
6906
    """Poll with custom rpc for disk sync.
6907

6908
    This uses our own step-based rpc call.
6909

6910
    """
6911
    self.feedback_fn("* wait until resync is done")
6912
    all_done = False
6913
    while not all_done:
6914
      all_done = True
6915
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6916
                                            self.nodes_ip,
6917
                                            self.instance.disks)
6918
      min_percent = 100
6919
      for node, nres in result.items():
6920
        nres.Raise("Cannot resync disks on node %s" % node)
6921
        node_done, node_percent = nres.payload
6922
        all_done = all_done and node_done
6923
        if node_percent is not None:
6924
          min_percent = min(min_percent, node_percent)
6925
      if not all_done:
6926
        if min_percent < 100:
6927
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6928
        time.sleep(2)
6929

    
6930
  def _EnsureSecondary(self, node):
6931
    """Demote a node to secondary.
6932

6933
    """
6934
    self.feedback_fn("* switching node %s to secondary mode" % node)
6935

    
6936
    for dev in self.instance.disks:
6937
      self.cfg.SetDiskID(dev, node)
6938

    
6939
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6940
                                          self.instance.disks)
6941
    result.Raise("Cannot change disk to secondary on node %s" % node)
6942

    
6943
  def _GoStandalone(self):
6944
    """Disconnect from the network.
6945

6946
    """
6947
    self.feedback_fn("* changing into standalone mode")
6948
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6949
                                               self.instance.disks)
6950
    for node, nres in result.items():
6951
      nres.Raise("Cannot disconnect disks node %s" % node)
6952

    
6953
  def _GoReconnect(self, multimaster):
6954
    """Reconnect to the network.
6955

6956
    """
6957
    if multimaster:
6958
      msg = "dual-master"
6959
    else:
6960
      msg = "single-master"
6961
    self.feedback_fn("* changing disks into %s mode" % msg)
6962
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6963
                                           self.instance.disks,
6964
                                           self.instance.name, multimaster)
6965
    for node, nres in result.items():
6966
      nres.Raise("Cannot change disks config on node %s" % node)
6967

    
6968
  def _ExecCleanup(self):
6969
    """Try to cleanup after a failed migration.
6970

6971
    The cleanup is done by:
6972
      - check that the instance is running only on one node
6973
        (and update the config if needed)
6974
      - change disks on its secondary node to secondary
6975
      - wait until disks are fully synchronized
6976
      - disconnect from the network
6977
      - change disks into single-master mode
6978
      - wait again until disks are fully synchronized
6979

6980
    """
6981
    instance = self.instance
6982
    target_node = self.target_node
6983
    source_node = self.source_node
6984

    
6985
    # check running on only one node
6986
    self.feedback_fn("* checking where the instance actually runs"
6987
                     " (if this hangs, the hypervisor might be in"
6988
                     " a bad state)")
6989
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6990
    for node, result in ins_l.items():
6991
      result.Raise("Can't contact node %s" % node)
6992

    
6993
    runningon_source = instance.name in ins_l[source_node].payload
6994
    runningon_target = instance.name in ins_l[target_node].payload
6995

    
6996
    if runningon_source and runningon_target:
6997
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6998
                               " or the hypervisor is confused; you will have"
6999
                               " to ensure manually that it runs only on one"
7000
                               " and restart this operation")
7001

    
7002
    if not (runningon_source or runningon_target):
7003
      raise errors.OpExecError("Instance does not seem to be running at all;"
7004
                               " in this case it's safer to repair by"
7005
                               " running 'gnt-instance stop' to ensure disk"
7006
                               " shutdown, and then restarting it")
7007

    
7008
    if runningon_target:
7009
      # the migration has actually succeeded, we need to update the config
7010
      self.feedback_fn("* instance running on secondary node (%s),"
7011
                       " updating config" % target_node)
7012
      instance.primary_node = target_node
7013
      self.cfg.Update(instance, self.feedback_fn)
7014
      demoted_node = source_node
7015
    else:
7016
      self.feedback_fn("* instance confirmed to be running on its"
7017
                       " primary node (%s)" % source_node)
7018
      demoted_node = target_node
7019

    
7020
    if instance.disk_template in constants.DTS_INT_MIRROR:
7021
      self._EnsureSecondary(demoted_node)
7022
      try:
7023
        self._WaitUntilSync()
7024
      except errors.OpExecError:
7025
        # we ignore here errors, since if the device is standalone, it
7026
        # won't be able to sync
7027
        pass
7028
      self._GoStandalone()
7029
      self._GoReconnect(False)
7030
      self._WaitUntilSync()
7031

    
7032
    self.feedback_fn("* done")
7033

    
7034
  def _RevertDiskStatus(self):
7035
    """Try to revert the disk status after a failed migration.
7036

7037
    """
7038
    target_node = self.target_node
7039
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7040
      return
7041

    
7042
    try:
7043
      self._EnsureSecondary(target_node)
7044
      self._GoStandalone()
7045
      self._GoReconnect(False)
7046
      self._WaitUntilSync()
7047
    except errors.OpExecError, err:
7048
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7049
                         " please try to recover the instance manually;"
7050
                         " error '%s'" % str(err))
7051

    
7052
  def _AbortMigration(self):
7053
    """Call the hypervisor code to abort a started migration.
7054

7055
    """
7056
    instance = self.instance
7057
    target_node = self.target_node
7058
    migration_info = self.migration_info
7059

    
7060
    abort_result = self.rpc.call_finalize_migration(target_node,
7061
                                                    instance,
7062
                                                    migration_info,
7063
                                                    False)
7064
    abort_msg = abort_result.fail_msg
7065
    if abort_msg:
7066
      logging.error("Aborting migration failed on target node %s: %s",
7067
                    target_node, abort_msg)
7068
      # Don't raise an exception here, as we stil have to try to revert the
7069
      # disk status, even if this step failed.
7070

    
7071
  def _ExecMigration(self):
7072
    """Migrate an instance.
7073

7074
    The migrate is done by:
7075
      - change the disks into dual-master mode
7076
      - wait until disks are fully synchronized again
7077
      - migrate the instance
7078
      - change disks on the new secondary node (the old primary) to secondary
7079
      - wait until disks are fully synchronized
7080
      - change disks into single-master mode
7081

7082
    """
7083
    instance = self.instance
7084
    target_node = self.target_node
7085
    source_node = self.source_node
7086

    
7087
    self.feedback_fn("* checking disk consistency between source and target")
7088
    for dev in instance.disks:
7089
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7090
        raise errors.OpExecError("Disk %s is degraded or not fully"
7091
                                 " synchronized on target node,"
7092
                                 " aborting migration" % dev.iv_name)
7093

    
7094
    # First get the migration information from the remote node
7095
    result = self.rpc.call_migration_info(source_node, instance)
7096
    msg = result.fail_msg
7097
    if msg:
7098
      log_err = ("Failed fetching source migration information from %s: %s" %
7099
                 (source_node, msg))
7100
      logging.error(log_err)
7101
      raise errors.OpExecError(log_err)
7102

    
7103
    self.migration_info = migration_info = result.payload
7104

    
7105
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7106
      # Then switch the disks to master/master mode
7107
      self._EnsureSecondary(target_node)
7108
      self._GoStandalone()
7109
      self._GoReconnect(True)
7110
      self._WaitUntilSync()
7111

    
7112
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7113
    result = self.rpc.call_accept_instance(target_node,
7114
                                           instance,
7115
                                           migration_info,
7116
                                           self.nodes_ip[target_node])
7117

    
7118
    msg = result.fail_msg
7119
    if msg:
7120
      logging.error("Instance pre-migration failed, trying to revert"
7121
                    " disk status: %s", msg)
7122
      self.feedback_fn("Pre-migration failed, aborting")
7123
      self._AbortMigration()
7124
      self._RevertDiskStatus()
7125
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7126
                               (instance.name, msg))
7127

    
7128
    self.feedback_fn("* migrating instance to %s" % target_node)
7129
    result = self.rpc.call_instance_migrate(source_node, instance,
7130
                                            self.nodes_ip[target_node],
7131
                                            self.live)
7132
    msg = result.fail_msg
7133
    if msg:
7134
      logging.error("Instance migration failed, trying to revert"
7135
                    " disk status: %s", msg)
7136
      self.feedback_fn("Migration failed, aborting")
7137
      self._AbortMigration()
7138
      self._RevertDiskStatus()
7139
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7140
                               (instance.name, msg))
7141

    
7142
    instance.primary_node = target_node
7143
    # distribute new instance config to the other nodes
7144
    self.cfg.Update(instance, self.feedback_fn)
7145

    
7146
    result = self.rpc.call_finalize_migration(target_node,
7147
                                              instance,
7148
                                              migration_info,
7149
                                              True)
7150
    msg = result.fail_msg
7151
    if msg:
7152
      logging.error("Instance migration succeeded, but finalization failed:"
7153
                    " %s", msg)
7154
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7155
                               msg)
7156

    
7157
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7158
      self._EnsureSecondary(source_node)
7159
      self._WaitUntilSync()
7160
      self._GoStandalone()
7161
      self._GoReconnect(False)
7162
      self._WaitUntilSync()
7163

    
7164
    self.feedback_fn("* done")
7165

    
7166
  def _ExecFailover(self):
7167
    """Failover an instance.
7168

7169
    The failover is done by shutting it down on its present node and
7170
    starting it on the secondary.
7171

7172
    """
7173
    instance = self.instance
7174
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7175

    
7176
    source_node = instance.primary_node
7177
    target_node = self.target_node
7178

    
7179
    if instance.admin_up:
7180
      self.feedback_fn("* checking disk consistency between source and target")
7181
      for dev in instance.disks:
7182
        # for drbd, these are drbd over lvm
7183
        if not _CheckDiskConsistency(self, dev, target_node, False):
7184
          if not self.ignore_consistency:
7185
            raise errors.OpExecError("Disk %s is degraded on target node,"
7186
                                     " aborting failover" % dev.iv_name)
7187
    else:
7188
      self.feedback_fn("* not checking disk consistency as instance is not"
7189
                       " running")
7190

    
7191
    self.feedback_fn("* shutting down instance on source node")
7192
    logging.info("Shutting down instance %s on node %s",
7193
                 instance.name, source_node)
7194

    
7195
    result = self.rpc.call_instance_shutdown(source_node, instance,
7196
                                             self.shutdown_timeout)
7197
    msg = result.fail_msg
7198
    if msg:
7199
      if self.ignore_consistency or primary_node.offline:
7200
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7201
                           " proceeding anyway; please make sure node"
7202
                           " %s is down; error details: %s",
7203
                           instance.name, source_node, source_node, msg)
7204
      else:
7205
        raise errors.OpExecError("Could not shutdown instance %s on"
7206
                                 " node %s: %s" %
7207
                                 (instance.name, source_node, msg))
7208

    
7209
    self.feedback_fn("* deactivating the instance's disks on source node")
7210
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
7211
      raise errors.OpExecError("Can't shut down the instance's disks.")
7212

    
7213
    instance.primary_node = target_node
7214
    # distribute new instance config to the other nodes
7215
    self.cfg.Update(instance, self.feedback_fn)
7216

    
7217
    # Only start the instance if it's marked as up
7218
    if instance.admin_up:
7219
      self.feedback_fn("* activating the instance's disks on target node")
7220
      logging.info("Starting instance %s on node %s",
7221
                   instance.name, target_node)
7222

    
7223
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7224
                                           ignore_secondaries=True)
7225
      if not disks_ok:
7226
        _ShutdownInstanceDisks(self, instance)
7227
        raise errors.OpExecError("Can't activate the instance's disks")
7228

    
7229
      self.feedback_fn("* starting the instance on the target node")
7230
      result = self.rpc.call_instance_start(target_node, instance, None, None)
7231
      msg = result.fail_msg
7232
      if msg:
7233
        _ShutdownInstanceDisks(self, instance)
7234
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7235
                                 (instance.name, target_node, msg))
7236

    
7237
  def Exec(self, feedback_fn):
7238
    """Perform the migration.
7239

7240
    """
7241
    self.feedback_fn = feedback_fn
7242
    self.source_node = self.instance.primary_node
7243

    
7244
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7245
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7246
      self.target_node = self.instance.secondary_nodes[0]
7247
      # Otherwise self.target_node has been populated either
7248
      # directly, or through an iallocator.
7249

    
7250
    self.all_nodes = [self.source_node, self.target_node]
7251
    self.nodes_ip = {
7252
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7253
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7254
      }
7255

    
7256
    if self.failover:
7257
      feedback_fn("Failover instance %s" % self.instance.name)
7258
      self._ExecFailover()
7259
    else:
7260
      feedback_fn("Migrating instance %s" % self.instance.name)
7261

    
7262
      if self.cleanup:
7263
        return self._ExecCleanup()
7264
      else:
7265
        return self._ExecMigration()
7266

    
7267

    
7268
def _CreateBlockDev(lu, node, instance, device, force_create,
7269
                    info, force_open):
7270
  """Create a tree of block devices on a given node.
7271

7272
  If this device type has to be created on secondaries, create it and
7273
  all its children.
7274

7275
  If not, just recurse to children keeping the same 'force' value.
7276

7277
  @param lu: the lu on whose behalf we execute
7278
  @param node: the node on which to create the device
7279
  @type instance: L{objects.Instance}
7280
  @param instance: the instance which owns the device
7281
  @type device: L{objects.Disk}
7282
  @param device: the device to create
7283
  @type force_create: boolean
7284
  @param force_create: whether to force creation of this device; this
7285
      will be change to True whenever we find a device which has
7286
      CreateOnSecondary() attribute
7287
  @param info: the extra 'metadata' we should attach to the device
7288
      (this will be represented as a LVM tag)
7289
  @type force_open: boolean
7290
  @param force_open: this parameter will be passes to the
7291
      L{backend.BlockdevCreate} function where it specifies
7292
      whether we run on primary or not, and it affects both
7293
      the child assembly and the device own Open() execution
7294

7295
  """
7296
  if device.CreateOnSecondary():
7297
    force_create = True
7298

    
7299
  if device.children:
7300
    for child in device.children:
7301
      _CreateBlockDev(lu, node, instance, child, force_create,
7302
                      info, force_open)
7303

    
7304
  if not force_create:
7305
    return
7306

    
7307
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7308

    
7309

    
7310
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7311
  """Create a single block device on a given node.
7312

7313
  This will not recurse over children of the device, so they must be
7314
  created in advance.
7315

7316
  @param lu: the lu on whose behalf we execute
7317
  @param node: the node on which to create the device
7318
  @type instance: L{objects.Instance}
7319
  @param instance: the instance which owns the device
7320
  @type device: L{objects.Disk}
7321
  @param device: the device to create
7322
  @param info: the extra 'metadata' we should attach to the device
7323
      (this will be represented as a LVM tag)
7324
  @type force_open: boolean
7325
  @param force_open: this parameter will be passes to the
7326
      L{backend.BlockdevCreate} function where it specifies
7327
      whether we run on primary or not, and it affects both
7328
      the child assembly and the device own Open() execution
7329

7330
  """
7331
  lu.cfg.SetDiskID(device, node)
7332
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7333
                                       instance.name, force_open, info)
7334
  result.Raise("Can't create block device %s on"
7335
               " node %s for instance %s" % (device, node, instance.name))
7336
  if device.physical_id is None:
7337
    device.physical_id = result.payload
7338

    
7339

    
7340
def _GenerateUniqueNames(lu, exts):
7341
  """Generate a suitable LV name.
7342

7343
  This will generate a logical volume name for the given instance.
7344

7345
  """
7346
  results = []
7347
  for val in exts:
7348
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7349
    results.append("%s%s" % (new_id, val))
7350
  return results
7351

    
7352

    
7353
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7354
                         iv_name, p_minor, s_minor):
7355
  """Generate a drbd8 device complete with its children.
7356

7357
  """
7358
  assert len(vgnames) == len(names) == 2
7359
  port = lu.cfg.AllocatePort()
7360
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7361
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7362
                          logical_id=(vgnames[0], names[0]))
7363
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7364
                          logical_id=(vgnames[1], names[1]))
7365
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7366
                          logical_id=(primary, secondary, port,
7367
                                      p_minor, s_minor,
7368
                                      shared_secret),
7369
                          children=[dev_data, dev_meta],
7370
                          iv_name=iv_name)
7371
  return drbd_dev
7372

    
7373

    
7374
def _GenerateDiskTemplate(lu, template_name,
7375
                          instance_name, primary_node,
7376
                          secondary_nodes, disk_info,
7377
                          file_storage_dir, file_driver,
7378
                          base_index, feedback_fn):
7379
  """Generate the entire disk layout for a given template type.
7380

7381
  """
7382
  #TODO: compute space requirements
7383

    
7384
  vgname = lu.cfg.GetVGName()
7385
  disk_count = len(disk_info)
7386
  disks = []
7387
  if template_name == constants.DT_DISKLESS:
7388
    pass
7389
  elif template_name == constants.DT_PLAIN:
7390
    if len(secondary_nodes) != 0:
7391
      raise errors.ProgrammerError("Wrong template configuration")
7392

    
7393
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7394
                                      for i in range(disk_count)])
7395
    for idx, disk in enumerate(disk_info):
7396
      disk_index = idx + base_index
7397
      vg = disk.get(constants.IDISK_VG, vgname)
7398
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7399
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7400
                              size=disk[constants.IDISK_SIZE],
7401
                              logical_id=(vg, names[idx]),
7402
                              iv_name="disk/%d" % disk_index,
7403
                              mode=disk[constants.IDISK_MODE])
7404
      disks.append(disk_dev)
7405
  elif template_name == constants.DT_DRBD8:
7406
    if len(secondary_nodes) != 1:
7407
      raise errors.ProgrammerError("Wrong template configuration")
7408
    remote_node = secondary_nodes[0]
7409
    minors = lu.cfg.AllocateDRBDMinor(
7410
      [primary_node, remote_node] * len(disk_info), instance_name)
7411

    
7412
    names = []
7413
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7414
                                               for i in range(disk_count)]):
7415
      names.append(lv_prefix + "_data")
7416
      names.append(lv_prefix + "_meta")
7417
    for idx, disk in enumerate(disk_info):
7418
      disk_index = idx + base_index
7419
      data_vg = disk.get(constants.IDISK_VG, vgname)
7420
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7421
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7422
                                      disk[constants.IDISK_SIZE],
7423
                                      [data_vg, meta_vg],
7424
                                      names[idx * 2:idx * 2 + 2],
7425
                                      "disk/%d" % disk_index,
7426
                                      minors[idx * 2], minors[idx * 2 + 1])
7427
      disk_dev.mode = disk[constants.IDISK_MODE]
7428
      disks.append(disk_dev)
7429
  elif template_name == constants.DT_FILE:
7430
    if len(secondary_nodes) != 0:
7431
      raise errors.ProgrammerError("Wrong template configuration")
7432

    
7433
    opcodes.RequireFileStorage()
7434

    
7435
    for idx, disk in enumerate(disk_info):
7436
      disk_index = idx + base_index
7437
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7438
                              size=disk[constants.IDISK_SIZE],
7439
                              iv_name="disk/%d" % disk_index,
7440
                              logical_id=(file_driver,
7441
                                          "%s/disk%d" % (file_storage_dir,
7442
                                                         disk_index)),
7443
                              mode=disk[constants.IDISK_MODE])
7444
      disks.append(disk_dev)
7445
  elif template_name == constants.DT_SHARED_FILE:
7446
    if len(secondary_nodes) != 0:
7447
      raise errors.ProgrammerError("Wrong template configuration")
7448

    
7449
    opcodes.RequireSharedFileStorage()
7450

    
7451
    for idx, disk in enumerate(disk_info):
7452
      disk_index = idx + base_index
7453
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7454
                              size=disk[constants.IDISK_SIZE],
7455
                              iv_name="disk/%d" % disk_index,
7456
                              logical_id=(file_driver,
7457
                                          "%s/disk%d" % (file_storage_dir,
7458
                                                         disk_index)),
7459
                              mode=disk[constants.IDISK_MODE])
7460
      disks.append(disk_dev)
7461
  elif template_name == constants.DT_BLOCK:
7462
    if len(secondary_nodes) != 0:
7463
      raise errors.ProgrammerError("Wrong template configuration")
7464

    
7465
    for idx, disk in enumerate(disk_info):
7466
      disk_index = idx + base_index
7467
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7468
                              size=disk[constants.IDISK_SIZE],
7469
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7470
                                          disk[constants.IDISK_ADOPT]),
7471
                              iv_name="disk/%d" % disk_index,
7472
                              mode=disk[constants.IDISK_MODE])
7473
      disks.append(disk_dev)
7474

    
7475
  else:
7476
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7477
  return disks
7478

    
7479

    
7480
def _GetInstanceInfoText(instance):
7481
  """Compute that text that should be added to the disk's metadata.
7482

7483
  """
7484
  return "originstname+%s" % instance.name
7485

    
7486

    
7487
def _CalcEta(time_taken, written, total_size):
7488
  """Calculates the ETA based on size written and total size.
7489

7490
  @param time_taken: The time taken so far
7491
  @param written: amount written so far
7492
  @param total_size: The total size of data to be written
7493
  @return: The remaining time in seconds
7494

7495
  """
7496
  avg_time = time_taken / float(written)
7497
  return (total_size - written) * avg_time
7498

    
7499

    
7500
def _WipeDisks(lu, instance):
7501
  """Wipes instance disks.
7502

7503
  @type lu: L{LogicalUnit}
7504
  @param lu: the logical unit on whose behalf we execute
7505
  @type instance: L{objects.Instance}
7506
  @param instance: the instance whose disks we should create
7507
  @return: the success of the wipe
7508

7509
  """
7510
  node = instance.primary_node
7511

    
7512
  for device in instance.disks:
7513
    lu.cfg.SetDiskID(device, node)
7514

    
7515
  logging.info("Pause sync of instance %s disks", instance.name)
7516
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7517

    
7518
  for idx, success in enumerate(result.payload):
7519
    if not success:
7520
      logging.warn("pause-sync of instance %s for disks %d failed",
7521
                   instance.name, idx)
7522

    
7523
  try:
7524
    for idx, device in enumerate(instance.disks):
7525
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7526
      # MAX_WIPE_CHUNK at max
7527
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7528
                            constants.MIN_WIPE_CHUNK_PERCENT)
7529
      # we _must_ make this an int, otherwise rounding errors will
7530
      # occur
7531
      wipe_chunk_size = int(wipe_chunk_size)
7532

    
7533
      lu.LogInfo("* Wiping disk %d", idx)
7534
      logging.info("Wiping disk %d for instance %s, node %s using"
7535
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7536

    
7537
      offset = 0
7538
      size = device.size
7539
      last_output = 0
7540
      start_time = time.time()
7541

    
7542
      while offset < size:
7543
        wipe_size = min(wipe_chunk_size, size - offset)
7544
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7545
                      idx, offset, wipe_size)
7546
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7547
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7548
                     (idx, offset, wipe_size))
7549
        now = time.time()
7550
        offset += wipe_size
7551
        if now - last_output >= 60:
7552
          eta = _CalcEta(now - start_time, offset, size)
7553
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7554
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7555
          last_output = now
7556
  finally:
7557
    logging.info("Resume sync of instance %s disks", instance.name)
7558

    
7559
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7560

    
7561
    for idx, success in enumerate(result.payload):
7562
      if not success:
7563
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7564
                      " look at the status and troubleshoot the issue", idx)
7565
        logging.warn("resume-sync of instance %s for disks %d failed",
7566
                     instance.name, idx)
7567

    
7568

    
7569
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7570
  """Create all disks for an instance.
7571

7572
  This abstracts away some work from AddInstance.
7573

7574
  @type lu: L{LogicalUnit}
7575
  @param lu: the logical unit on whose behalf we execute
7576
  @type instance: L{objects.Instance}
7577
  @param instance: the instance whose disks we should create
7578
  @type to_skip: list
7579
  @param to_skip: list of indices to skip
7580
  @type target_node: string
7581
  @param target_node: if passed, overrides the target node for creation
7582
  @rtype: boolean
7583
  @return: the success of the creation
7584

7585
  """
7586
  info = _GetInstanceInfoText(instance)
7587
  if target_node is None:
7588
    pnode = instance.primary_node
7589
    all_nodes = instance.all_nodes
7590
  else:
7591
    pnode = target_node
7592
    all_nodes = [pnode]
7593

    
7594
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
7595
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7596
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7597

    
7598
    result.Raise("Failed to create directory '%s' on"
7599
                 " node %s" % (file_storage_dir, pnode))
7600

    
7601
  # Note: this needs to be kept in sync with adding of disks in
7602
  # LUInstanceSetParams
7603
  for idx, device in enumerate(instance.disks):
7604
    if to_skip and idx in to_skip:
7605
      continue
7606
    logging.info("Creating volume %s for instance %s",
7607
                 device.iv_name, instance.name)
7608
    #HARDCODE
7609
    for node in all_nodes:
7610
      f_create = node == pnode
7611
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7612

    
7613

    
7614
def _RemoveDisks(lu, instance, target_node=None):
7615
  """Remove all disks for an instance.
7616

7617
  This abstracts away some work from `AddInstance()` and
7618
  `RemoveInstance()`. Note that in case some of the devices couldn't
7619
  be removed, the removal will continue with the other ones (compare
7620
  with `_CreateDisks()`).
7621

7622
  @type lu: L{LogicalUnit}
7623
  @param lu: the logical unit on whose behalf we execute
7624
  @type instance: L{objects.Instance}
7625
  @param instance: the instance whose disks we should remove
7626
  @type target_node: string
7627
  @param target_node: used to override the node on which to remove the disks
7628
  @rtype: boolean
7629
  @return: the success of the removal
7630

7631
  """
7632
  logging.info("Removing block devices for instance %s", instance.name)
7633

    
7634
  all_result = True
7635
  for device in instance.disks:
7636
    if target_node:
7637
      edata = [(target_node, device)]
7638
    else:
7639
      edata = device.ComputeNodeTree(instance.primary_node)
7640
    for node, disk in edata:
7641
      lu.cfg.SetDiskID(disk, node)
7642
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7643
      if msg:
7644
        lu.LogWarning("Could not remove block device %s on node %s,"
7645
                      " continuing anyway: %s", device.iv_name, node, msg)
7646
        all_result = False
7647

    
7648
  if instance.disk_template == constants.DT_FILE:
7649
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7650
    if target_node:
7651
      tgt = target_node
7652
    else:
7653
      tgt = instance.primary_node
7654
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7655
    if result.fail_msg:
7656
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7657
                    file_storage_dir, instance.primary_node, result.fail_msg)
7658
      all_result = False
7659

    
7660
  return all_result
7661

    
7662

    
7663
def _ComputeDiskSizePerVG(disk_template, disks):
7664
  """Compute disk size requirements in the volume group
7665

7666
  """
7667
  def _compute(disks, payload):
7668
    """Universal algorithm.
7669

7670
    """
7671
    vgs = {}
7672
    for disk in disks:
7673
      vgs[disk[constants.IDISK_VG]] = \
7674
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7675

    
7676
    return vgs
7677

    
7678
  # Required free disk space as a function of disk and swap space
7679
  req_size_dict = {
7680
    constants.DT_DISKLESS: {},
7681
    constants.DT_PLAIN: _compute(disks, 0),
7682
    # 128 MB are added for drbd metadata for each disk
7683
    constants.DT_DRBD8: _compute(disks, 128),
7684
    constants.DT_FILE: {},
7685
    constants.DT_SHARED_FILE: {},
7686
  }
7687

    
7688
  if disk_template not in req_size_dict:
7689
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7690
                                 " is unknown" %  disk_template)
7691

    
7692
  return req_size_dict[disk_template]
7693

    
7694

    
7695
def _ComputeDiskSize(disk_template, disks):
7696
  """Compute disk size requirements in the volume group
7697

7698
  """
7699
  # Required free disk space as a function of disk and swap space
7700
  req_size_dict = {
7701
    constants.DT_DISKLESS: None,
7702
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7703
    # 128 MB are added for drbd metadata for each disk
7704
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7705
    constants.DT_FILE: None,
7706
    constants.DT_SHARED_FILE: 0,
7707
    constants.DT_BLOCK: 0,
7708
  }
7709

    
7710
  if disk_template not in req_size_dict:
7711
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7712
                                 " is unknown" %  disk_template)
7713

    
7714
  return req_size_dict[disk_template]
7715

    
7716

    
7717
def _FilterVmNodes(lu, nodenames):
7718
  """Filters out non-vm_capable nodes from a list.
7719

7720
  @type lu: L{LogicalUnit}
7721
  @param lu: the logical unit for which we check
7722
  @type nodenames: list
7723
  @param nodenames: the list of nodes on which we should check
7724
  @rtype: list
7725
  @return: the list of vm-capable nodes
7726

7727
  """
7728
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7729
  return [name for name in nodenames if name not in vm_nodes]
7730

    
7731

    
7732
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7733
  """Hypervisor parameter validation.
7734

7735
  This function abstract the hypervisor parameter validation to be
7736
  used in both instance create and instance modify.
7737

7738
  @type lu: L{LogicalUnit}
7739
  @param lu: the logical unit for which we check
7740
  @type nodenames: list
7741
  @param nodenames: the list of nodes on which we should check
7742
  @type hvname: string
7743
  @param hvname: the name of the hypervisor we should use
7744
  @type hvparams: dict
7745
  @param hvparams: the parameters which we need to check
7746
  @raise errors.OpPrereqError: if the parameters are not valid
7747

7748
  """
7749
  nodenames = _FilterVmNodes(lu, nodenames)
7750
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7751
                                                  hvname,
7752
                                                  hvparams)
7753
  for node in nodenames:
7754
    info = hvinfo[node]
7755
    if info.offline:
7756
      continue
7757
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7758

    
7759

    
7760
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7761
  """OS parameters validation.
7762

7763
  @type lu: L{LogicalUnit}
7764
  @param lu: the logical unit for which we check
7765
  @type required: boolean
7766
  @param required: whether the validation should fail if the OS is not
7767
      found
7768
  @type nodenames: list
7769
  @param nodenames: the list of nodes on which we should check
7770
  @type osname: string
7771
  @param osname: the name of the hypervisor we should use
7772
  @type osparams: dict
7773
  @param osparams: the parameters which we need to check
7774
  @raise errors.OpPrereqError: if the parameters are not valid
7775

7776
  """
7777
  nodenames = _FilterVmNodes(lu, nodenames)
7778
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7779
                                   [constants.OS_VALIDATE_PARAMETERS],
7780
                                   osparams)
7781
  for node, nres in result.items():
7782
    # we don't check for offline cases since this should be run only
7783
    # against the master node and/or an instance's nodes
7784
    nres.Raise("OS Parameters validation failed on node %s" % node)
7785
    if not nres.payload:
7786
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7787
                 osname, node)
7788

    
7789

    
7790
class LUInstanceCreate(LogicalUnit):
7791
  """Create an instance.
7792

7793
  """
7794
  HPATH = "instance-add"
7795
  HTYPE = constants.HTYPE_INSTANCE
7796
  REQ_BGL = False
7797

    
7798
  def CheckArguments(self):
7799
    """Check arguments.
7800

7801
    """
7802
    # do not require name_check to ease forward/backward compatibility
7803
    # for tools
7804
    if self.op.no_install and self.op.start:
7805
      self.LogInfo("No-installation mode selected, disabling startup")
7806
      self.op.start = False
7807
    # validate/normalize the instance name
7808
    self.op.instance_name = \
7809
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7810

    
7811
    if self.op.ip_check and not self.op.name_check:
7812
      # TODO: make the ip check more flexible and not depend on the name check
7813
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7814
                                 " check", errors.ECODE_INVAL)
7815

    
7816
    # check nics' parameter names
7817
    for nic in self.op.nics:
7818
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7819

    
7820
    # check disks. parameter names and consistent adopt/no-adopt strategy
7821
    has_adopt = has_no_adopt = False
7822
    for disk in self.op.disks:
7823
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7824
      if constants.IDISK_ADOPT in disk:
7825
        has_adopt = True
7826
      else:
7827
        has_no_adopt = True
7828
    if has_adopt and has_no_adopt:
7829
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7830
                                 errors.ECODE_INVAL)
7831
    if has_adopt:
7832
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7833
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7834
                                   " '%s' disk template" %
7835
                                   self.op.disk_template,
7836
                                   errors.ECODE_INVAL)
7837
      if self.op.iallocator is not None:
7838
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7839
                                   " iallocator script", errors.ECODE_INVAL)
7840
      if self.op.mode == constants.INSTANCE_IMPORT:
7841
        raise errors.OpPrereqError("Disk adoption not allowed for"
7842
                                   " instance import", errors.ECODE_INVAL)
7843
    else:
7844
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7845
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7846
                                   " but no 'adopt' parameter given" %
7847
                                   self.op.disk_template,
7848
                                   errors.ECODE_INVAL)
7849

    
7850
    self.adopt_disks = has_adopt
7851

    
7852
    # instance name verification
7853
    if self.op.name_check:
7854
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7855
      self.op.instance_name = self.hostname1.name
7856
      # used in CheckPrereq for ip ping check
7857
      self.check_ip = self.hostname1.ip
7858
    else:
7859
      self.check_ip = None
7860

    
7861
    # file storage checks
7862
    if (self.op.file_driver and
7863
        not self.op.file_driver in constants.FILE_DRIVER):
7864
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7865
                                 self.op.file_driver, errors.ECODE_INVAL)
7866

    
7867
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7868
      raise errors.OpPrereqError("File storage directory path not absolute",
7869
                                 errors.ECODE_INVAL)
7870

    
7871
    ### Node/iallocator related checks
7872
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7873

    
7874
    if self.op.pnode is not None:
7875
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7876
        if self.op.snode is None:
7877
          raise errors.OpPrereqError("The networked disk templates need"
7878
                                     " a mirror node", errors.ECODE_INVAL)
7879
      elif self.op.snode:
7880
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7881
                        " template")
7882
        self.op.snode = None
7883

    
7884
    self._cds = _GetClusterDomainSecret()
7885

    
7886
    if self.op.mode == constants.INSTANCE_IMPORT:
7887
      # On import force_variant must be True, because if we forced it at
7888
      # initial install, our only chance when importing it back is that it
7889
      # works again!
7890
      self.op.force_variant = True
7891

    
7892
      if self.op.no_install:
7893
        self.LogInfo("No-installation mode has no effect during import")
7894

    
7895
    elif self.op.mode == constants.INSTANCE_CREATE:
7896
      if self.op.os_type is None:
7897
        raise errors.OpPrereqError("No guest OS specified",
7898
                                   errors.ECODE_INVAL)
7899
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7900
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7901
                                   " installation" % self.op.os_type,
7902
                                   errors.ECODE_STATE)
7903
      if self.op.disk_template is None:
7904
        raise errors.OpPrereqError("No disk template specified",
7905
                                   errors.ECODE_INVAL)
7906

    
7907
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7908
      # Check handshake to ensure both clusters have the same domain secret
7909
      src_handshake = self.op.source_handshake
7910
      if not src_handshake:
7911
        raise errors.OpPrereqError("Missing source handshake",
7912
                                   errors.ECODE_INVAL)
7913

    
7914
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7915
                                                           src_handshake)
7916
      if errmsg:
7917
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7918
                                   errors.ECODE_INVAL)
7919

    
7920
      # Load and check source CA
7921
      self.source_x509_ca_pem = self.op.source_x509_ca
7922
      if not self.source_x509_ca_pem:
7923
        raise errors.OpPrereqError("Missing source X509 CA",
7924
                                   errors.ECODE_INVAL)
7925

    
7926
      try:
7927
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7928
                                                    self._cds)
7929
      except OpenSSL.crypto.Error, err:
7930
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7931
                                   (err, ), errors.ECODE_INVAL)
7932

    
7933
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7934
      if errcode is not None:
7935
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7936
                                   errors.ECODE_INVAL)
7937

    
7938
      self.source_x509_ca = cert
7939

    
7940
      src_instance_name = self.op.source_instance_name
7941
      if not src_instance_name:
7942
        raise errors.OpPrereqError("Missing source instance name",
7943
                                   errors.ECODE_INVAL)
7944

    
7945
      self.source_instance_name = \
7946
          netutils.GetHostname(name=src_instance_name).name
7947

    
7948
    else:
7949
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7950
                                 self.op.mode, errors.ECODE_INVAL)
7951

    
7952
  def ExpandNames(self):
7953
    """ExpandNames for CreateInstance.
7954

7955
    Figure out the right locks for instance creation.
7956

7957
    """
7958
    self.needed_locks = {}
7959

    
7960
    instance_name = self.op.instance_name
7961
    # this is just a preventive check, but someone might still add this
7962
    # instance in the meantime, and creation will fail at lock-add time
7963
    if instance_name in self.cfg.GetInstanceList():
7964
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7965
                                 instance_name, errors.ECODE_EXISTS)
7966

    
7967
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7968

    
7969
    if self.op.iallocator:
7970
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7971
    else:
7972
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7973
      nodelist = [self.op.pnode]
7974
      if self.op.snode is not None:
7975
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7976
        nodelist.append(self.op.snode)
7977
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7978

    
7979
    # in case of import lock the source node too
7980
    if self.op.mode == constants.INSTANCE_IMPORT:
7981
      src_node = self.op.src_node
7982
      src_path = self.op.src_path
7983

    
7984
      if src_path is None:
7985
        self.op.src_path = src_path = self.op.instance_name
7986

    
7987
      if src_node is None:
7988
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7989
        self.op.src_node = None
7990
        if os.path.isabs(src_path):
7991
          raise errors.OpPrereqError("Importing an instance from an absolute"
7992
                                     " path requires a source node option",
7993
                                     errors.ECODE_INVAL)
7994
      else:
7995
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7996
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7997
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7998
        if not os.path.isabs(src_path):
7999
          self.op.src_path = src_path = \
8000
            utils.PathJoin(constants.EXPORT_DIR, src_path)
8001

    
8002
  def _RunAllocator(self):
8003
    """Run the allocator based on input opcode.
8004

8005
    """
8006
    nics = [n.ToDict() for n in self.nics]
8007
    ial = IAllocator(self.cfg, self.rpc,
8008
                     mode=constants.IALLOCATOR_MODE_ALLOC,
8009
                     name=self.op.instance_name,
8010
                     disk_template=self.op.disk_template,
8011
                     tags=[],
8012
                     os=self.op.os_type,
8013
                     vcpus=self.be_full[constants.BE_VCPUS],
8014
                     mem_size=self.be_full[constants.BE_MEMORY],
8015
                     disks=self.disks,
8016
                     nics=nics,
8017
                     hypervisor=self.op.hypervisor,
8018
                     )
8019

    
8020
    ial.Run(self.op.iallocator)
8021

    
8022
    if not ial.success:
8023
      raise errors.OpPrereqError("Can't compute nodes using"
8024
                                 " iallocator '%s': %s" %
8025
                                 (self.op.iallocator, ial.info),
8026
                                 errors.ECODE_NORES)
8027
    if len(ial.result) != ial.required_nodes:
8028
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8029
                                 " of nodes (%s), required %s" %
8030
                                 (self.op.iallocator, len(ial.result),
8031
                                  ial.required_nodes), errors.ECODE_FAULT)
8032
    self.op.pnode = ial.result[0]
8033
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8034
                 self.op.instance_name, self.op.iallocator,
8035
                 utils.CommaJoin(ial.result))
8036
    if ial.required_nodes == 2:
8037
      self.op.snode = ial.result[1]
8038

    
8039
  def BuildHooksEnv(self):
8040
    """Build hooks env.
8041

8042
    This runs on master, primary and secondary nodes of the instance.
8043

8044
    """
8045
    env = {
8046
      "ADD_MODE": self.op.mode,
8047
      }
8048
    if self.op.mode == constants.INSTANCE_IMPORT:
8049
      env["SRC_NODE"] = self.op.src_node
8050
      env["SRC_PATH"] = self.op.src_path
8051
      env["SRC_IMAGES"] = self.src_images
8052

    
8053
    env.update(_BuildInstanceHookEnv(
8054
      name=self.op.instance_name,
8055
      primary_node=self.op.pnode,
8056
      secondary_nodes=self.secondaries,
8057
      status=self.op.start,
8058
      os_type=self.op.os_type,
8059
      memory=self.be_full[constants.BE_MEMORY],
8060
      vcpus=self.be_full[constants.BE_VCPUS],
8061
      nics=_NICListToTuple(self, self.nics),
8062
      disk_template=self.op.disk_template,
8063
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8064
             for d in self.disks],
8065
      bep=self.be_full,
8066
      hvp=self.hv_full,
8067
      hypervisor_name=self.op.hypervisor,
8068
    ))
8069

    
8070
    return env
8071

    
8072
  def BuildHooksNodes(self):
8073
    """Build hooks nodes.
8074

8075
    """
8076
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8077
    return nl, nl
8078

    
8079
  def _ReadExportInfo(self):
8080
    """Reads the export information from disk.
8081

8082
    It will override the opcode source node and path with the actual
8083
    information, if these two were not specified before.
8084

8085
    @return: the export information
8086

8087
    """
8088
    assert self.op.mode == constants.INSTANCE_IMPORT
8089

    
8090
    src_node = self.op.src_node
8091
    src_path = self.op.src_path
8092

    
8093
    if src_node is None:
8094
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
8095
      exp_list = self.rpc.call_export_list(locked_nodes)
8096
      found = False
8097
      for node in exp_list:
8098
        if exp_list[node].fail_msg:
8099
          continue
8100
        if src_path in exp_list[node].payload:
8101
          found = True
8102
          self.op.src_node = src_node = node
8103
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8104
                                                       src_path)
8105
          break
8106
      if not found:
8107
        raise errors.OpPrereqError("No export found for relative path %s" %
8108
                                    src_path, errors.ECODE_INVAL)
8109

    
8110
    _CheckNodeOnline(self, src_node)
8111
    result = self.rpc.call_export_info(src_node, src_path)
8112
    result.Raise("No export or invalid export found in dir %s" % src_path)
8113

    
8114
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8115
    if not export_info.has_section(constants.INISECT_EXP):
8116
      raise errors.ProgrammerError("Corrupted export config",
8117
                                   errors.ECODE_ENVIRON)
8118

    
8119
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8120
    if (int(ei_version) != constants.EXPORT_VERSION):
8121
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8122
                                 (ei_version, constants.EXPORT_VERSION),
8123
                                 errors.ECODE_ENVIRON)
8124
    return export_info
8125

    
8126
  def _ReadExportParams(self, einfo):
8127
    """Use export parameters as defaults.
8128

8129
    In case the opcode doesn't specify (as in override) some instance
8130
    parameters, then try to use them from the export information, if
8131
    that declares them.
8132

8133
    """
8134
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8135

    
8136
    if self.op.disk_template is None:
8137
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8138
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8139
                                          "disk_template")
8140
      else:
8141
        raise errors.OpPrereqError("No disk template specified and the export"
8142
                                   " is missing the disk_template information",
8143
                                   errors.ECODE_INVAL)
8144

    
8145
    if not self.op.disks:
8146
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
8147
        disks = []
8148
        # TODO: import the disk iv_name too
8149
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8150
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8151
          disks.append({constants.IDISK_SIZE: disk_sz})
8152
        self.op.disks = disks
8153
      else:
8154
        raise errors.OpPrereqError("No disk info specified and the export"
8155
                                   " is missing the disk information",
8156
                                   errors.ECODE_INVAL)
8157

    
8158
    if (not self.op.nics and
8159
        einfo.has_option(constants.INISECT_INS, "nic_count")):
8160
      nics = []
8161
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8162
        ndict = {}
8163
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8164
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8165
          ndict[name] = v
8166
        nics.append(ndict)
8167
      self.op.nics = nics
8168

    
8169
    if (self.op.hypervisor is None and
8170
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
8171
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8172
    if einfo.has_section(constants.INISECT_HYP):
8173
      # use the export parameters but do not override the ones
8174
      # specified by the user
8175
      for name, value in einfo.items(constants.INISECT_HYP):
8176
        if name not in self.op.hvparams:
8177
          self.op.hvparams[name] = value
8178

    
8179
    if einfo.has_section(constants.INISECT_BEP):
8180
      # use the parameters, without overriding
8181
      for name, value in einfo.items(constants.INISECT_BEP):
8182
        if name not in self.op.beparams:
8183
          self.op.beparams[name] = value
8184
    else:
8185
      # try to read the parameters old style, from the main section
8186
      for name in constants.BES_PARAMETERS:
8187
        if (name not in self.op.beparams and
8188
            einfo.has_option(constants.INISECT_INS, name)):
8189
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8190

    
8191
    if einfo.has_section(constants.INISECT_OSP):
8192
      # use the parameters, without overriding
8193
      for name, value in einfo.items(constants.INISECT_OSP):
8194
        if name not in self.op.osparams:
8195
          self.op.osparams[name] = value
8196

    
8197
  def _RevertToDefaults(self, cluster):
8198
    """Revert the instance parameters to the default values.
8199

8200
    """
8201
    # hvparams
8202
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8203
    for name in self.op.hvparams.keys():
8204
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8205
        del self.op.hvparams[name]
8206
    # beparams
8207
    be_defs = cluster.SimpleFillBE({})
8208
    for name in self.op.beparams.keys():
8209
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8210
        del self.op.beparams[name]
8211
    # nic params
8212
    nic_defs = cluster.SimpleFillNIC({})
8213
    for nic in self.op.nics:
8214
      for name in constants.NICS_PARAMETERS:
8215
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8216
          del nic[name]
8217
    # osparams
8218
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8219
    for name in self.op.osparams.keys():
8220
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8221
        del self.op.osparams[name]
8222

    
8223
  def CheckPrereq(self):
8224
    """Check prerequisites.
8225

8226
    """
8227
    if self.op.mode == constants.INSTANCE_IMPORT:
8228
      export_info = self._ReadExportInfo()
8229
      self._ReadExportParams(export_info)
8230

    
8231
    if (not self.cfg.GetVGName() and
8232
        self.op.disk_template not in constants.DTS_NOT_LVM):
8233
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8234
                                 " instances", errors.ECODE_STATE)
8235

    
8236
    if self.op.hypervisor is None:
8237
      self.op.hypervisor = self.cfg.GetHypervisorType()
8238

    
8239
    cluster = self.cfg.GetClusterInfo()
8240
    enabled_hvs = cluster.enabled_hypervisors
8241
    if self.op.hypervisor not in enabled_hvs:
8242
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8243
                                 " cluster (%s)" % (self.op.hypervisor,
8244
                                  ",".join(enabled_hvs)),
8245
                                 errors.ECODE_STATE)
8246

    
8247
    # check hypervisor parameter syntax (locally)
8248
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8249
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8250
                                      self.op.hvparams)
8251
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8252
    hv_type.CheckParameterSyntax(filled_hvp)
8253
    self.hv_full = filled_hvp
8254
    # check that we don't specify global parameters on an instance
8255
    _CheckGlobalHvParams(self.op.hvparams)
8256

    
8257
    # fill and remember the beparams dict
8258
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8259
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8260

    
8261
    # build os parameters
8262
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8263

    
8264
    # now that hvp/bep are in final format, let's reset to defaults,
8265
    # if told to do so
8266
    if self.op.identify_defaults:
8267
      self._RevertToDefaults(cluster)
8268

    
8269
    # NIC buildup
8270
    self.nics = []
8271
    for idx, nic in enumerate(self.op.nics):
8272
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8273
      nic_mode = nic_mode_req
8274
      if nic_mode is None:
8275
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8276

    
8277
      # in routed mode, for the first nic, the default ip is 'auto'
8278
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8279
        default_ip_mode = constants.VALUE_AUTO
8280
      else:
8281
        default_ip_mode = constants.VALUE_NONE
8282

    
8283
      # ip validity checks
8284
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8285
      if ip is None or ip.lower() == constants.VALUE_NONE:
8286
        nic_ip = None
8287
      elif ip.lower() == constants.VALUE_AUTO:
8288
        if not self.op.name_check:
8289
          raise errors.OpPrereqError("IP address set to auto but name checks"
8290
                                     " have been skipped",
8291
                                     errors.ECODE_INVAL)
8292
        nic_ip = self.hostname1.ip
8293
      else:
8294
        if not netutils.IPAddress.IsValid(ip):
8295
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8296
                                     errors.ECODE_INVAL)
8297
        nic_ip = ip
8298

    
8299
      # TODO: check the ip address for uniqueness
8300
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8301
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8302
                                   errors.ECODE_INVAL)
8303

    
8304
      # MAC address verification
8305
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8306
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8307
        mac = utils.NormalizeAndValidateMac(mac)
8308

    
8309
        try:
8310
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8311
        except errors.ReservationError:
8312
          raise errors.OpPrereqError("MAC address %s already in use"
8313
                                     " in cluster" % mac,
8314
                                     errors.ECODE_NOTUNIQUE)
8315

    
8316
      #  Build nic parameters
8317
      link = nic.get(constants.INIC_LINK, None)
8318
      nicparams = {}
8319
      if nic_mode_req:
8320
        nicparams[constants.NIC_MODE] = nic_mode_req
8321
      if link:
8322
        nicparams[constants.NIC_LINK] = link
8323

    
8324
      check_params = cluster.SimpleFillNIC(nicparams)
8325
      objects.NIC.CheckParameterSyntax(check_params)
8326
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8327

    
8328
    # disk checks/pre-build
8329
    default_vg = self.cfg.GetVGName()
8330
    self.disks = []
8331
    for disk in self.op.disks:
8332
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8333
      if mode not in constants.DISK_ACCESS_SET:
8334
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8335
                                   mode, errors.ECODE_INVAL)
8336
      size = disk.get(constants.IDISK_SIZE, None)
8337
      if size is None:
8338
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8339
      try:
8340
        size = int(size)
8341
      except (TypeError, ValueError):
8342
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8343
                                   errors.ECODE_INVAL)
8344

    
8345
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8346
      new_disk = {
8347
        constants.IDISK_SIZE: size,
8348
        constants.IDISK_MODE: mode,
8349
        constants.IDISK_VG: data_vg,
8350
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8351
        }
8352
      if constants.IDISK_ADOPT in disk:
8353
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8354
      self.disks.append(new_disk)
8355

    
8356
    if self.op.mode == constants.INSTANCE_IMPORT:
8357

    
8358
      # Check that the new instance doesn't have less disks than the export
8359
      instance_disks = len(self.disks)
8360
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8361
      if instance_disks < export_disks:
8362
        raise errors.OpPrereqError("Not enough disks to import."
8363
                                   " (instance: %d, export: %d)" %
8364
                                   (instance_disks, export_disks),
8365
                                   errors.ECODE_INVAL)
8366

    
8367
      disk_images = []
8368
      for idx in range(export_disks):
8369
        option = 'disk%d_dump' % idx
8370
        if export_info.has_option(constants.INISECT_INS, option):
8371
          # FIXME: are the old os-es, disk sizes, etc. useful?
8372
          export_name = export_info.get(constants.INISECT_INS, option)
8373
          image = utils.PathJoin(self.op.src_path, export_name)
8374
          disk_images.append(image)
8375
        else:
8376
          disk_images.append(False)
8377

    
8378
      self.src_images = disk_images
8379

    
8380
      old_name = export_info.get(constants.INISECT_INS, 'name')
8381
      try:
8382
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8383
      except (TypeError, ValueError), err:
8384
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8385
                                   " an integer: %s" % str(err),
8386
                                   errors.ECODE_STATE)
8387
      if self.op.instance_name == old_name:
8388
        for idx, nic in enumerate(self.nics):
8389
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8390
            nic_mac_ini = 'nic%d_mac' % idx
8391
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8392

    
8393
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8394

    
8395
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8396
    if self.op.ip_check:
8397
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8398
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8399
                                   (self.check_ip, self.op.instance_name),
8400
                                   errors.ECODE_NOTUNIQUE)
8401

    
8402
    #### mac address generation
8403
    # By generating here the mac address both the allocator and the hooks get
8404
    # the real final mac address rather than the 'auto' or 'generate' value.
8405
    # There is a race condition between the generation and the instance object
8406
    # creation, which means that we know the mac is valid now, but we're not
8407
    # sure it will be when we actually add the instance. If things go bad
8408
    # adding the instance will abort because of a duplicate mac, and the
8409
    # creation job will fail.
8410
    for nic in self.nics:
8411
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8412
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8413

    
8414
    #### allocator run
8415

    
8416
    if self.op.iallocator is not None:
8417
      self._RunAllocator()
8418

    
8419
    #### node related checks
8420

    
8421
    # check primary node
8422
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8423
    assert self.pnode is not None, \
8424
      "Cannot retrieve locked node %s" % self.op.pnode
8425
    if pnode.offline:
8426
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8427
                                 pnode.name, errors.ECODE_STATE)
8428
    if pnode.drained:
8429
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8430
                                 pnode.name, errors.ECODE_STATE)
8431
    if not pnode.vm_capable:
8432
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8433
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8434

    
8435
    self.secondaries = []
8436

    
8437
    # mirror node verification
8438
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8439
      if self.op.snode == pnode.name:
8440
        raise errors.OpPrereqError("The secondary node cannot be the"
8441
                                   " primary node", errors.ECODE_INVAL)
8442
      _CheckNodeOnline(self, self.op.snode)
8443
      _CheckNodeNotDrained(self, self.op.snode)
8444
      _CheckNodeVmCapable(self, self.op.snode)
8445
      self.secondaries.append(self.op.snode)
8446

    
8447
    nodenames = [pnode.name] + self.secondaries
8448

    
8449
    if not self.adopt_disks:
8450
      # Check lv size requirements, if not adopting
8451
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8452
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8453

    
8454
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8455
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8456
                                disk[constants.IDISK_ADOPT])
8457
                     for disk in self.disks])
8458
      if len(all_lvs) != len(self.disks):
8459
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8460
                                   errors.ECODE_INVAL)
8461
      for lv_name in all_lvs:
8462
        try:
8463
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8464
          # to ReserveLV uses the same syntax
8465
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8466
        except errors.ReservationError:
8467
          raise errors.OpPrereqError("LV named %s used by another instance" %
8468
                                     lv_name, errors.ECODE_NOTUNIQUE)
8469

    
8470
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8471
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8472

    
8473
      node_lvs = self.rpc.call_lv_list([pnode.name],
8474
                                       vg_names.payload.keys())[pnode.name]
8475
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8476
      node_lvs = node_lvs.payload
8477

    
8478
      delta = all_lvs.difference(node_lvs.keys())
8479
      if delta:
8480
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8481
                                   utils.CommaJoin(delta),
8482
                                   errors.ECODE_INVAL)
8483
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8484
      if online_lvs:
8485
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8486
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8487
                                   errors.ECODE_STATE)
8488
      # update the size of disk based on what is found
8489
      for dsk in self.disks:
8490
        dsk[constants.IDISK_SIZE] = \
8491
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8492
                                        dsk[constants.IDISK_ADOPT])][0]))
8493

    
8494
    elif self.op.disk_template == constants.DT_BLOCK:
8495
      # Normalize and de-duplicate device paths
8496
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8497
                       for disk in self.disks])
8498
      if len(all_disks) != len(self.disks):
8499
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8500
                                   errors.ECODE_INVAL)
8501
      baddisks = [d for d in all_disks
8502
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8503
      if baddisks:
8504
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8505
                                   " cannot be adopted" %
8506
                                   (", ".join(baddisks),
8507
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8508
                                   errors.ECODE_INVAL)
8509

    
8510
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8511
                                            list(all_disks))[pnode.name]
8512
      node_disks.Raise("Cannot get block device information from node %s" %
8513
                       pnode.name)
8514
      node_disks = node_disks.payload
8515
      delta = all_disks.difference(node_disks.keys())
8516
      if delta:
8517
        raise errors.OpPrereqError("Missing block device(s): %s" %
8518
                                   utils.CommaJoin(delta),
8519
                                   errors.ECODE_INVAL)
8520
      for dsk in self.disks:
8521
        dsk[constants.IDISK_SIZE] = \
8522
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8523

    
8524
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8525

    
8526
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8527
    # check OS parameters (remotely)
8528
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8529

    
8530
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8531

    
8532
    # memory check on primary node
8533
    if self.op.start:
8534
      _CheckNodeFreeMemory(self, self.pnode.name,
8535
                           "creating instance %s" % self.op.instance_name,
8536
                           self.be_full[constants.BE_MEMORY],
8537
                           self.op.hypervisor)
8538

    
8539
    self.dry_run_result = list(nodenames)
8540

    
8541
  def Exec(self, feedback_fn):
8542
    """Create and add the instance to the cluster.
8543

8544
    """
8545
    instance = self.op.instance_name
8546
    pnode_name = self.pnode.name
8547

    
8548
    ht_kind = self.op.hypervisor
8549
    if ht_kind in constants.HTS_REQ_PORT:
8550
      network_port = self.cfg.AllocatePort()
8551
    else:
8552
      network_port = None
8553

    
8554
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
8555
      # this is needed because os.path.join does not accept None arguments
8556
      if self.op.file_storage_dir is None:
8557
        string_file_storage_dir = ""
8558
      else:
8559
        string_file_storage_dir = self.op.file_storage_dir
8560

    
8561
      # build the full file storage dir path
8562
      if self.op.disk_template == constants.DT_SHARED_FILE:
8563
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8564
      else:
8565
        get_fsd_fn = self.cfg.GetFileStorageDir
8566

    
8567
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
8568
                                        string_file_storage_dir, instance)
8569
    else:
8570
      file_storage_dir = ""
8571

    
8572
    disks = _GenerateDiskTemplate(self,
8573
                                  self.op.disk_template,
8574
                                  instance, pnode_name,
8575
                                  self.secondaries,
8576
                                  self.disks,
8577
                                  file_storage_dir,
8578
                                  self.op.file_driver,
8579
                                  0,
8580
                                  feedback_fn)
8581

    
8582
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8583
                            primary_node=pnode_name,
8584
                            nics=self.nics, disks=disks,
8585
                            disk_template=self.op.disk_template,
8586
                            admin_up=False,
8587
                            network_port=network_port,
8588
                            beparams=self.op.beparams,
8589
                            hvparams=self.op.hvparams,
8590
                            hypervisor=self.op.hypervisor,
8591
                            osparams=self.op.osparams,
8592
                            )
8593

    
8594
    if self.adopt_disks:
8595
      if self.op.disk_template == constants.DT_PLAIN:
8596
        # rename LVs to the newly-generated names; we need to construct
8597
        # 'fake' LV disks with the old data, plus the new unique_id
8598
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8599
        rename_to = []
8600
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8601
          rename_to.append(t_dsk.logical_id)
8602
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8603
          self.cfg.SetDiskID(t_dsk, pnode_name)
8604
        result = self.rpc.call_blockdev_rename(pnode_name,
8605
                                               zip(tmp_disks, rename_to))
8606
        result.Raise("Failed to rename adoped LVs")
8607
    else:
8608
      feedback_fn("* creating instance disks...")
8609
      try:
8610
        _CreateDisks(self, iobj)
8611
      except errors.OpExecError:
8612
        self.LogWarning("Device creation failed, reverting...")
8613
        try:
8614
          _RemoveDisks(self, iobj)
8615
        finally:
8616
          self.cfg.ReleaseDRBDMinors(instance)
8617
          raise
8618

    
8619
    feedback_fn("adding instance %s to cluster config" % instance)
8620

    
8621
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8622

    
8623
    # Declare that we don't want to remove the instance lock anymore, as we've
8624
    # added the instance to the config
8625
    del self.remove_locks[locking.LEVEL_INSTANCE]
8626

    
8627
    if self.op.mode == constants.INSTANCE_IMPORT:
8628
      # Release unused nodes
8629
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8630
    else:
8631
      # Release all nodes
8632
      _ReleaseLocks(self, locking.LEVEL_NODE)
8633

    
8634
    disk_abort = False
8635
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8636
      feedback_fn("* wiping instance disks...")
8637
      try:
8638
        _WipeDisks(self, iobj)
8639
      except errors.OpExecError, err:
8640
        logging.exception("Wiping disks failed")
8641
        self.LogWarning("Wiping instance disks failed (%s)", err)
8642
        disk_abort = True
8643

    
8644
    if disk_abort:
8645
      # Something is already wrong with the disks, don't do anything else
8646
      pass
8647
    elif self.op.wait_for_sync:
8648
      disk_abort = not _WaitForSync(self, iobj)
8649
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8650
      # make sure the disks are not degraded (still sync-ing is ok)
8651
      time.sleep(15)
8652
      feedback_fn("* checking mirrors status")
8653
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8654
    else:
8655
      disk_abort = False
8656

    
8657
    if disk_abort:
8658
      _RemoveDisks(self, iobj)
8659
      self.cfg.RemoveInstance(iobj.name)
8660
      # Make sure the instance lock gets removed
8661
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8662
      raise errors.OpExecError("There are some degraded disks for"
8663
                               " this instance")
8664

    
8665
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8666
      if self.op.mode == constants.INSTANCE_CREATE:
8667
        if not self.op.no_install:
8668
          feedback_fn("* running the instance OS create scripts...")
8669
          # FIXME: pass debug option from opcode to backend
8670
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8671
                                                 self.op.debug_level)
8672
          result.Raise("Could not add os for instance %s"
8673
                       " on node %s" % (instance, pnode_name))
8674

    
8675
      elif self.op.mode == constants.INSTANCE_IMPORT:
8676
        feedback_fn("* running the instance OS import scripts...")
8677

    
8678
        transfers = []
8679

    
8680
        for idx, image in enumerate(self.src_images):
8681
          if not image:
8682
            continue
8683

    
8684
          # FIXME: pass debug option from opcode to backend
8685
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8686
                                             constants.IEIO_FILE, (image, ),
8687
                                             constants.IEIO_SCRIPT,
8688
                                             (iobj.disks[idx], idx),
8689
                                             None)
8690
          transfers.append(dt)
8691

    
8692
        import_result = \
8693
          masterd.instance.TransferInstanceData(self, feedback_fn,
8694
                                                self.op.src_node, pnode_name,
8695
                                                self.pnode.secondary_ip,
8696
                                                iobj, transfers)
8697
        if not compat.all(import_result):
8698
          self.LogWarning("Some disks for instance %s on node %s were not"
8699
                          " imported successfully" % (instance, pnode_name))
8700

    
8701
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8702
        feedback_fn("* preparing remote import...")
8703
        # The source cluster will stop the instance before attempting to make a
8704
        # connection. In some cases stopping an instance can take a long time,
8705
        # hence the shutdown timeout is added to the connection timeout.
8706
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8707
                           self.op.source_shutdown_timeout)
8708
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8709

    
8710
        assert iobj.primary_node == self.pnode.name
8711
        disk_results = \
8712
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8713
                                        self.source_x509_ca,
8714
                                        self._cds, timeouts)
8715
        if not compat.all(disk_results):
8716
          # TODO: Should the instance still be started, even if some disks
8717
          # failed to import (valid for local imports, too)?
8718
          self.LogWarning("Some disks for instance %s on node %s were not"
8719
                          " imported successfully" % (instance, pnode_name))
8720

    
8721
        # Run rename script on newly imported instance
8722
        assert iobj.name == instance
8723
        feedback_fn("Running rename script for %s" % instance)
8724
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8725
                                                   self.source_instance_name,
8726
                                                   self.op.debug_level)
8727
        if result.fail_msg:
8728
          self.LogWarning("Failed to run rename script for %s on node"
8729
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8730

    
8731
      else:
8732
        # also checked in the prereq part
8733
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8734
                                     % self.op.mode)
8735

    
8736
    if self.op.start:
8737
      iobj.admin_up = True
8738
      self.cfg.Update(iobj, feedback_fn)
8739
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8740
      feedback_fn("* starting instance...")
8741
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8742
      result.Raise("Could not start instance")
8743

    
8744
    return list(iobj.all_nodes)
8745

    
8746

    
8747
class LUInstanceConsole(NoHooksLU):
8748
  """Connect to an instance's console.
8749

8750
  This is somewhat special in that it returns the command line that
8751
  you need to run on the master node in order to connect to the
8752
  console.
8753

8754
  """
8755
  REQ_BGL = False
8756

    
8757
  def ExpandNames(self):
8758
    self._ExpandAndLockInstance()
8759

    
8760
  def CheckPrereq(self):
8761
    """Check prerequisites.
8762

8763
    This checks that the instance is in the cluster.
8764

8765
    """
8766
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8767
    assert self.instance is not None, \
8768
      "Cannot retrieve locked instance %s" % self.op.instance_name
8769
    _CheckNodeOnline(self, self.instance.primary_node)
8770

    
8771
  def Exec(self, feedback_fn):
8772
    """Connect to the console of an instance
8773

8774
    """
8775
    instance = self.instance
8776
    node = instance.primary_node
8777

    
8778
    node_insts = self.rpc.call_instance_list([node],
8779
                                             [instance.hypervisor])[node]
8780
    node_insts.Raise("Can't get node information from %s" % node)
8781

    
8782
    if instance.name not in node_insts.payload:
8783
      if instance.admin_up:
8784
        state = constants.INSTST_ERRORDOWN
8785
      else:
8786
        state = constants.INSTST_ADMINDOWN
8787
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8788
                               (instance.name, state))
8789

    
8790
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8791

    
8792
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8793

    
8794

    
8795
def _GetInstanceConsole(cluster, instance):
8796
  """Returns console information for an instance.
8797

8798
  @type cluster: L{objects.Cluster}
8799
  @type instance: L{objects.Instance}
8800
  @rtype: dict
8801

8802
  """
8803
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8804
  # beparams and hvparams are passed separately, to avoid editing the
8805
  # instance and then saving the defaults in the instance itself.
8806
  hvparams = cluster.FillHV(instance)
8807
  beparams = cluster.FillBE(instance)
8808
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8809

    
8810
  assert console.instance == instance.name
8811
  assert console.Validate()
8812

    
8813
  return console.ToDict()
8814

    
8815

    
8816
class LUInstanceReplaceDisks(LogicalUnit):
8817
  """Replace the disks of an instance.
8818

8819
  """
8820
  HPATH = "mirrors-replace"
8821
  HTYPE = constants.HTYPE_INSTANCE
8822
  REQ_BGL = False
8823

    
8824
  def CheckArguments(self):
8825
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8826
                                  self.op.iallocator)
8827

    
8828
  def ExpandNames(self):
8829
    self._ExpandAndLockInstance()
8830

    
8831
    assert locking.LEVEL_NODE not in self.needed_locks
8832
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8833

    
8834
    assert self.op.iallocator is None or self.op.remote_node is None, \
8835
      "Conflicting options"
8836

    
8837
    if self.op.remote_node is not None:
8838
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8839

    
8840
      # Warning: do not remove the locking of the new secondary here
8841
      # unless DRBD8.AddChildren is changed to work in parallel;
8842
      # currently it doesn't since parallel invocations of
8843
      # FindUnusedMinor will conflict
8844
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8845
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8846
    else:
8847
      self.needed_locks[locking.LEVEL_NODE] = []
8848
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8849

    
8850
      if self.op.iallocator is not None:
8851
        # iallocator will select a new node in the same group
8852
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8853

    
8854
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8855
                                   self.op.iallocator, self.op.remote_node,
8856
                                   self.op.disks, False, self.op.early_release)
8857

    
8858
    self.tasklets = [self.replacer]
8859

    
8860
  def DeclareLocks(self, level):
8861
    if level == locking.LEVEL_NODEGROUP:
8862
      assert self.op.remote_node is None
8863
      assert self.op.iallocator is not None
8864
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8865

    
8866
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8867
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8868
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8869

    
8870
    elif level == locking.LEVEL_NODE:
8871
      if self.op.iallocator is not None:
8872
        assert self.op.remote_node is None
8873
        assert not self.needed_locks[locking.LEVEL_NODE]
8874

    
8875
        # Lock member nodes of all locked groups
8876
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8877
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8878
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8879
      else:
8880
        self._LockInstancesNodes()
8881

    
8882
  def BuildHooksEnv(self):
8883
    """Build hooks env.
8884

8885
    This runs on the master, the primary and all the secondaries.
8886

8887
    """
8888
    instance = self.replacer.instance
8889
    env = {
8890
      "MODE": self.op.mode,
8891
      "NEW_SECONDARY": self.op.remote_node,
8892
      "OLD_SECONDARY": instance.secondary_nodes[0],
8893
      }
8894
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8895
    return env
8896

    
8897
  def BuildHooksNodes(self):
8898
    """Build hooks nodes.
8899

8900
    """
8901
    instance = self.replacer.instance
8902
    nl = [
8903
      self.cfg.GetMasterNode(),
8904
      instance.primary_node,
8905
      ]
8906
    if self.op.remote_node is not None:
8907
      nl.append(self.op.remote_node)
8908
    return nl, nl
8909

    
8910
  def CheckPrereq(self):
8911
    """Check prerequisites.
8912

8913
    """
8914
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8915
            self.op.iallocator is None)
8916

    
8917
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8918
    if owned_groups:
8919
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8920
      if owned_groups != groups:
8921
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8922
                                 " since lock was acquired, current list is %r,"
8923
                                 " used to be '%s'" %
8924
                                 (self.op.instance_name,
8925
                                  utils.CommaJoin(groups),
8926
                                  utils.CommaJoin(owned_groups)))
8927

    
8928
    return LogicalUnit.CheckPrereq(self)
8929

    
8930

    
8931
class TLReplaceDisks(Tasklet):
8932
  """Replaces disks for an instance.
8933

8934
  Note: Locking is not within the scope of this class.
8935

8936
  """
8937
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8938
               disks, delay_iallocator, early_release):
8939
    """Initializes this class.
8940

8941
    """
8942
    Tasklet.__init__(self, lu)
8943

    
8944
    # Parameters
8945
    self.instance_name = instance_name
8946
    self.mode = mode
8947
    self.iallocator_name = iallocator_name
8948
    self.remote_node = remote_node
8949
    self.disks = disks
8950
    self.delay_iallocator = delay_iallocator
8951
    self.early_release = early_release
8952

    
8953
    # Runtime data
8954
    self.instance = None
8955
    self.new_node = None
8956
    self.target_node = None
8957
    self.other_node = None
8958
    self.remote_node_info = None
8959
    self.node_secondary_ip = None
8960

    
8961
  @staticmethod
8962
  def CheckArguments(mode, remote_node, iallocator):
8963
    """Helper function for users of this class.
8964

8965
    """
8966
    # check for valid parameter combination
8967
    if mode == constants.REPLACE_DISK_CHG:
8968
      if remote_node is None and iallocator is None:
8969
        raise errors.OpPrereqError("When changing the secondary either an"
8970
                                   " iallocator script must be used or the"
8971
                                   " new node given", errors.ECODE_INVAL)
8972

    
8973
      if remote_node is not None and iallocator is not None:
8974
        raise errors.OpPrereqError("Give either the iallocator or the new"
8975
                                   " secondary, not both", errors.ECODE_INVAL)
8976

    
8977
    elif remote_node is not None or iallocator is not None:
8978
      # Not replacing the secondary
8979
      raise errors.OpPrereqError("The iallocator and new node options can"
8980
                                 " only be used when changing the"
8981
                                 " secondary node", errors.ECODE_INVAL)
8982

    
8983
  @staticmethod
8984
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8985
    """Compute a new secondary node using an IAllocator.
8986

8987
    """
8988
    ial = IAllocator(lu.cfg, lu.rpc,
8989
                     mode=constants.IALLOCATOR_MODE_RELOC,
8990
                     name=instance_name,
8991
                     relocate_from=relocate_from)
8992

    
8993
    ial.Run(iallocator_name)
8994

    
8995
    if not ial.success:
8996
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8997
                                 " %s" % (iallocator_name, ial.info),
8998
                                 errors.ECODE_NORES)
8999

    
9000
    if len(ial.result) != ial.required_nodes:
9001
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9002
                                 " of nodes (%s), required %s" %
9003
                                 (iallocator_name,
9004
                                  len(ial.result), ial.required_nodes),
9005
                                 errors.ECODE_FAULT)
9006

    
9007
    remote_node_name = ial.result[0]
9008

    
9009
    lu.LogInfo("Selected new secondary for instance '%s': %s",
9010
               instance_name, remote_node_name)
9011

    
9012
    return remote_node_name
9013

    
9014
  def _FindFaultyDisks(self, node_name):
9015
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9016
                                    node_name, True)
9017

    
9018
  def _CheckDisksActivated(self, instance):
9019
    """Checks if the instance disks are activated.
9020

9021
    @param instance: The instance to check disks
9022
    @return: True if they are activated, False otherwise
9023

9024
    """
9025
    nodes = instance.all_nodes
9026

    
9027
    for idx, dev in enumerate(instance.disks):
9028
      for node in nodes:
9029
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9030
        self.cfg.SetDiskID(dev, node)
9031

    
9032
        result = self.rpc.call_blockdev_find(node, dev)
9033

    
9034
        if result.offline:
9035
          continue
9036
        elif result.fail_msg or not result.payload:
9037
          return False
9038

    
9039
    return True
9040

    
9041
  def CheckPrereq(self):
9042
    """Check prerequisites.
9043

9044
    This checks that the instance is in the cluster.
9045

9046
    """
9047
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9048
    assert instance is not None, \
9049
      "Cannot retrieve locked instance %s" % self.instance_name
9050

    
9051
    if instance.disk_template != constants.DT_DRBD8:
9052
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9053
                                 " instances", errors.ECODE_INVAL)
9054

    
9055
    if len(instance.secondary_nodes) != 1:
9056
      raise errors.OpPrereqError("The instance has a strange layout,"
9057
                                 " expected one secondary but found %d" %
9058
                                 len(instance.secondary_nodes),
9059
                                 errors.ECODE_FAULT)
9060

    
9061
    if not self.delay_iallocator:
9062
      self._CheckPrereq2()
9063

    
9064
  def _CheckPrereq2(self):
9065
    """Check prerequisites, second part.
9066

9067
    This function should always be part of CheckPrereq. It was separated and is
9068
    now called from Exec because during node evacuation iallocator was only
9069
    called with an unmodified cluster model, not taking planned changes into
9070
    account.
9071

9072
    """
9073
    instance = self.instance
9074
    secondary_node = instance.secondary_nodes[0]
9075

    
9076
    if self.iallocator_name is None:
9077
      remote_node = self.remote_node
9078
    else:
9079
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
9080
                                       instance.name, instance.secondary_nodes)
9081

    
9082
    if remote_node is None:
9083
      self.remote_node_info = None
9084
    else:
9085
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
9086
             "Remote node '%s' is not locked" % remote_node
9087

    
9088
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9089
      assert self.remote_node_info is not None, \
9090
        "Cannot retrieve locked node %s" % remote_node
9091

    
9092
    if remote_node == self.instance.primary_node:
9093
      raise errors.OpPrereqError("The specified node is the primary node of"
9094
                                 " the instance", errors.ECODE_INVAL)
9095

    
9096
    if remote_node == secondary_node:
9097
      raise errors.OpPrereqError("The specified node is already the"
9098
                                 " secondary node of the instance",
9099
                                 errors.ECODE_INVAL)
9100

    
9101
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9102
                                    constants.REPLACE_DISK_CHG):
9103
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
9104
                                 errors.ECODE_INVAL)
9105

    
9106
    if self.mode == constants.REPLACE_DISK_AUTO:
9107
      if not self._CheckDisksActivated(instance):
9108
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
9109
                                   " first" % self.instance_name,
9110
                                   errors.ECODE_STATE)
9111
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
9112
      faulty_secondary = self._FindFaultyDisks(secondary_node)
9113

    
9114
      if faulty_primary and faulty_secondary:
9115
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9116
                                   " one node and can not be repaired"
9117
                                   " automatically" % self.instance_name,
9118
                                   errors.ECODE_STATE)
9119

    
9120
      if faulty_primary:
9121
        self.disks = faulty_primary
9122
        self.target_node = instance.primary_node
9123
        self.other_node = secondary_node
9124
        check_nodes = [self.target_node, self.other_node]
9125
      elif faulty_secondary:
9126
        self.disks = faulty_secondary
9127
        self.target_node = secondary_node
9128
        self.other_node = instance.primary_node
9129
        check_nodes = [self.target_node, self.other_node]
9130
      else:
9131
        self.disks = []
9132
        check_nodes = []
9133

    
9134
    else:
9135
      # Non-automatic modes
9136
      if self.mode == constants.REPLACE_DISK_PRI:
9137
        self.target_node = instance.primary_node
9138
        self.other_node = secondary_node
9139
        check_nodes = [self.target_node, self.other_node]
9140

    
9141
      elif self.mode == constants.REPLACE_DISK_SEC:
9142
        self.target_node = secondary_node
9143
        self.other_node = instance.primary_node
9144
        check_nodes = [self.target_node, self.other_node]
9145

    
9146
      elif self.mode == constants.REPLACE_DISK_CHG:
9147
        self.new_node = remote_node
9148
        self.other_node = instance.primary_node
9149
        self.target_node = secondary_node
9150
        check_nodes = [self.new_node, self.other_node]
9151

    
9152
        _CheckNodeNotDrained(self.lu, remote_node)
9153
        _CheckNodeVmCapable(self.lu, remote_node)
9154

    
9155
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
9156
        assert old_node_info is not None
9157
        if old_node_info.offline and not self.early_release:
9158
          # doesn't make sense to delay the release
9159
          self.early_release = True
9160
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9161
                          " early-release mode", secondary_node)
9162

    
9163
      else:
9164
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9165
                                     self.mode)
9166

    
9167
      # If not specified all disks should be replaced
9168
      if not self.disks:
9169
        self.disks = range(len(self.instance.disks))
9170

    
9171
    for node in check_nodes:
9172
      _CheckNodeOnline(self.lu, node)
9173

    
9174
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
9175
                                                          self.other_node,
9176
                                                          self.target_node]
9177
                              if node_name is not None)
9178

    
9179
    # Release unneeded node locks
9180
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9181

    
9182
    # Release any owned node group
9183
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9184
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9185

    
9186
    # Check whether disks are valid
9187
    for disk_idx in self.disks:
9188
      instance.FindDisk(disk_idx)
9189

    
9190
    # Get secondary node IP addresses
9191
    self.node_secondary_ip = \
9192
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
9193
           for node_name in touched_nodes)
9194

    
9195
  def Exec(self, feedback_fn):
9196
    """Execute disk replacement.
9197

9198
    This dispatches the disk replacement to the appropriate handler.
9199

9200
    """
9201
    if self.delay_iallocator:
9202
      self._CheckPrereq2()
9203

    
9204
    if __debug__:
9205
      # Verify owned locks before starting operation
9206
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9207
      assert set(owned_locks) == set(self.node_secondary_ip), \
9208
          ("Incorrect node locks, owning %s, expected %s" %
9209
           (owned_locks, self.node_secondary_ip.keys()))
9210

    
9211
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9212
      assert list(owned_locks) == [self.instance_name], \
9213
          "Instance '%s' not locked" % self.instance_name
9214

    
9215
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9216
          "Should not own any node group lock at this point"
9217

    
9218
    if not self.disks:
9219
      feedback_fn("No disks need replacement")
9220
      return
9221

    
9222
    feedback_fn("Replacing disk(s) %s for %s" %
9223
                (utils.CommaJoin(self.disks), self.instance.name))
9224

    
9225
    activate_disks = (not self.instance.admin_up)
9226

    
9227
    # Activate the instance disks if we're replacing them on a down instance
9228
    if activate_disks:
9229
      _StartInstanceDisks(self.lu, self.instance, True)
9230

    
9231
    try:
9232
      # Should we replace the secondary node?
9233
      if self.new_node is not None:
9234
        fn = self._ExecDrbd8Secondary
9235
      else:
9236
        fn = self._ExecDrbd8DiskOnly
9237

    
9238
      result = fn(feedback_fn)
9239
    finally:
9240
      # Deactivate the instance disks if we're replacing them on a
9241
      # down instance
9242
      if activate_disks:
9243
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9244

    
9245
    if __debug__:
9246
      # Verify owned locks
9247
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9248
      nodes = frozenset(self.node_secondary_ip)
9249
      assert ((self.early_release and not owned_locks) or
9250
              (not self.early_release and not (set(owned_locks) - nodes))), \
9251
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9252
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9253

    
9254
    return result
9255

    
9256
  def _CheckVolumeGroup(self, nodes):
9257
    self.lu.LogInfo("Checking volume groups")
9258

    
9259
    vgname = self.cfg.GetVGName()
9260

    
9261
    # Make sure volume group exists on all involved nodes
9262
    results = self.rpc.call_vg_list(nodes)
9263
    if not results:
9264
      raise errors.OpExecError("Can't list volume groups on the nodes")
9265

    
9266
    for node in nodes:
9267
      res = results[node]
9268
      res.Raise("Error checking node %s" % node)
9269
      if vgname not in res.payload:
9270
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9271
                                 (vgname, node))
9272

    
9273
  def _CheckDisksExistence(self, nodes):
9274
    # Check disk existence
9275
    for idx, dev in enumerate(self.instance.disks):
9276
      if idx not in self.disks:
9277
        continue
9278

    
9279
      for node in nodes:
9280
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9281
        self.cfg.SetDiskID(dev, node)
9282

    
9283
        result = self.rpc.call_blockdev_find(node, dev)
9284

    
9285
        msg = result.fail_msg
9286
        if msg or not result.payload:
9287
          if not msg:
9288
            msg = "disk not found"
9289
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9290
                                   (idx, node, msg))
9291

    
9292
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9293
    for idx, dev in enumerate(self.instance.disks):
9294
      if idx not in self.disks:
9295
        continue
9296

    
9297
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9298
                      (idx, node_name))
9299

    
9300
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9301
                                   ldisk=ldisk):
9302
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9303
                                 " replace disks for instance %s" %
9304
                                 (node_name, self.instance.name))
9305

    
9306
  def _CreateNewStorage(self, node_name):
9307
    iv_names = {}
9308

    
9309
    for idx, dev in enumerate(self.instance.disks):
9310
      if idx not in self.disks:
9311
        continue
9312

    
9313
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
9314

    
9315
      self.cfg.SetDiskID(dev, node_name)
9316

    
9317
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9318
      names = _GenerateUniqueNames(self.lu, lv_names)
9319

    
9320
      vg_data = dev.children[0].logical_id[0]
9321
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9322
                             logical_id=(vg_data, names[0]))
9323
      vg_meta = dev.children[1].logical_id[0]
9324
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9325
                             logical_id=(vg_meta, names[1]))
9326

    
9327
      new_lvs = [lv_data, lv_meta]
9328
      old_lvs = dev.children
9329
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9330

    
9331
      # we pass force_create=True to force the LVM creation
9332
      for new_lv in new_lvs:
9333
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9334
                        _GetInstanceInfoText(self.instance), False)
9335

    
9336
    return iv_names
9337

    
9338
  def _CheckDevices(self, node_name, iv_names):
9339
    for name, (dev, _, _) in iv_names.iteritems():
9340
      self.cfg.SetDiskID(dev, node_name)
9341

    
9342
      result = self.rpc.call_blockdev_find(node_name, dev)
9343

    
9344
      msg = result.fail_msg
9345
      if msg or not result.payload:
9346
        if not msg:
9347
          msg = "disk not found"
9348
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9349
                                 (name, msg))
9350

    
9351
      if result.payload.is_degraded:
9352
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9353

    
9354
  def _RemoveOldStorage(self, node_name, iv_names):
9355
    for name, (_, old_lvs, _) in iv_names.iteritems():
9356
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9357

    
9358
      for lv in old_lvs:
9359
        self.cfg.SetDiskID(lv, node_name)
9360

    
9361
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9362
        if msg:
9363
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9364
                             hint="remove unused LVs manually")
9365

    
9366
  def _ExecDrbd8DiskOnly(self, feedback_fn):
9367
    """Replace a disk on the primary or secondary for DRBD 8.
9368

9369
    The algorithm for replace is quite complicated:
9370

9371
      1. for each disk to be replaced:
9372

9373
        1. create new LVs on the target node with unique names
9374
        1. detach old LVs from the drbd device
9375
        1. rename old LVs to name_replaced.<time_t>
9376
        1. rename new LVs to old LVs
9377
        1. attach the new LVs (with the old names now) to the drbd device
9378

9379
      1. wait for sync across all devices
9380

9381
      1. for each modified disk:
9382

9383
        1. remove old LVs (which have the name name_replaces.<time_t>)
9384

9385
    Failures are not very well handled.
9386

9387
    """
9388
    steps_total = 6
9389

    
9390
    # Step: check device activation
9391
    self.lu.LogStep(1, steps_total, "Check device existence")
9392
    self._CheckDisksExistence([self.other_node, self.target_node])
9393
    self._CheckVolumeGroup([self.target_node, self.other_node])
9394

    
9395
    # Step: check other node consistency
9396
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9397
    self._CheckDisksConsistency(self.other_node,
9398
                                self.other_node == self.instance.primary_node,
9399
                                False)
9400

    
9401
    # Step: create new storage
9402
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9403
    iv_names = self._CreateNewStorage(self.target_node)
9404

    
9405
    # Step: for each lv, detach+rename*2+attach
9406
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9407
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9408
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9409

    
9410
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9411
                                                     old_lvs)
9412
      result.Raise("Can't detach drbd from local storage on node"
9413
                   " %s for device %s" % (self.target_node, dev.iv_name))
9414
      #dev.children = []
9415
      #cfg.Update(instance)
9416

    
9417
      # ok, we created the new LVs, so now we know we have the needed
9418
      # storage; as such, we proceed on the target node to rename
9419
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9420
      # using the assumption that logical_id == physical_id (which in
9421
      # turn is the unique_id on that node)
9422

    
9423
      # FIXME(iustin): use a better name for the replaced LVs
9424
      temp_suffix = int(time.time())
9425
      ren_fn = lambda d, suff: (d.physical_id[0],
9426
                                d.physical_id[1] + "_replaced-%s" % suff)
9427

    
9428
      # Build the rename list based on what LVs exist on the node
9429
      rename_old_to_new = []
9430
      for to_ren in old_lvs:
9431
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9432
        if not result.fail_msg and result.payload:
9433
          # device exists
9434
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9435

    
9436
      self.lu.LogInfo("Renaming the old LVs on the target node")
9437
      result = self.rpc.call_blockdev_rename(self.target_node,
9438
                                             rename_old_to_new)
9439
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9440

    
9441
      # Now we rename the new LVs to the old LVs
9442
      self.lu.LogInfo("Renaming the new LVs on the target node")
9443
      rename_new_to_old = [(new, old.physical_id)
9444
                           for old, new in zip(old_lvs, new_lvs)]
9445
      result = self.rpc.call_blockdev_rename(self.target_node,
9446
                                             rename_new_to_old)
9447
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9448

    
9449
      for old, new in zip(old_lvs, new_lvs):
9450
        new.logical_id = old.logical_id
9451
        self.cfg.SetDiskID(new, self.target_node)
9452

    
9453
      for disk in old_lvs:
9454
        disk.logical_id = ren_fn(disk, temp_suffix)
9455
        self.cfg.SetDiskID(disk, self.target_node)
9456

    
9457
      # Now that the new lvs have the old name, we can add them to the device
9458
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9459
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9460
                                                  new_lvs)
9461
      msg = result.fail_msg
9462
      if msg:
9463
        for new_lv in new_lvs:
9464
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9465
                                               new_lv).fail_msg
9466
          if msg2:
9467
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9468
                               hint=("cleanup manually the unused logical"
9469
                                     "volumes"))
9470
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9471

    
9472
      dev.children = new_lvs
9473

    
9474
      self.cfg.Update(self.instance, feedback_fn)
9475

    
9476
    cstep = 5
9477
    if self.early_release:
9478
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9479
      cstep += 1
9480
      self._RemoveOldStorage(self.target_node, iv_names)
9481
      # WARNING: we release both node locks here, do not do other RPCs
9482
      # than WaitForSync to the primary node
9483
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9484
                    names=[self.target_node, self.other_node])
9485

    
9486
    # Wait for sync
9487
    # This can fail as the old devices are degraded and _WaitForSync
9488
    # does a combined result over all disks, so we don't check its return value
9489
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9490
    cstep += 1
9491
    _WaitForSync(self.lu, self.instance)
9492

    
9493
    # Check all devices manually
9494
    self._CheckDevices(self.instance.primary_node, iv_names)
9495

    
9496
    # Step: remove old storage
9497
    if not self.early_release:
9498
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9499
      cstep += 1
9500
      self._RemoveOldStorage(self.target_node, iv_names)
9501

    
9502
  def _ExecDrbd8Secondary(self, feedback_fn):
9503
    """Replace the secondary node for DRBD 8.
9504

9505
    The algorithm for replace is quite complicated:
9506
      - for all disks of the instance:
9507
        - create new LVs on the new node with same names
9508
        - shutdown the drbd device on the old secondary
9509
        - disconnect the drbd network on the primary
9510
        - create the drbd device on the new secondary
9511
        - network attach the drbd on the primary, using an artifice:
9512
          the drbd code for Attach() will connect to the network if it
9513
          finds a device which is connected to the good local disks but
9514
          not network enabled
9515
      - wait for sync across all devices
9516
      - remove all disks from the old secondary
9517

9518
    Failures are not very well handled.
9519

9520
    """
9521
    steps_total = 6
9522

    
9523
    # Step: check device activation
9524
    self.lu.LogStep(1, steps_total, "Check device existence")
9525
    self._CheckDisksExistence([self.instance.primary_node])
9526
    self._CheckVolumeGroup([self.instance.primary_node])
9527

    
9528
    # Step: check other node consistency
9529
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9530
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9531

    
9532
    # Step: create new storage
9533
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9534
    for idx, dev in enumerate(self.instance.disks):
9535
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9536
                      (self.new_node, idx))
9537
      # we pass force_create=True to force LVM creation
9538
      for new_lv in dev.children:
9539
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9540
                        _GetInstanceInfoText(self.instance), False)
9541

    
9542
    # Step 4: dbrd minors and drbd setups changes
9543
    # after this, we must manually remove the drbd minors on both the
9544
    # error and the success paths
9545
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9546
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9547
                                         for dev in self.instance.disks],
9548
                                        self.instance.name)
9549
    logging.debug("Allocated minors %r", minors)
9550

    
9551
    iv_names = {}
9552
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9553
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9554
                      (self.new_node, idx))
9555
      # create new devices on new_node; note that we create two IDs:
9556
      # one without port, so the drbd will be activated without
9557
      # networking information on the new node at this stage, and one
9558
      # with network, for the latter activation in step 4
9559
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9560
      if self.instance.primary_node == o_node1:
9561
        p_minor = o_minor1
9562
      else:
9563
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9564
        p_minor = o_minor2
9565

    
9566
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9567
                      p_minor, new_minor, o_secret)
9568
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9569
                    p_minor, new_minor, o_secret)
9570

    
9571
      iv_names[idx] = (dev, dev.children, new_net_id)
9572
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9573
                    new_net_id)
9574
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9575
                              logical_id=new_alone_id,
9576
                              children=dev.children,
9577
                              size=dev.size)
9578
      try:
9579
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9580
                              _GetInstanceInfoText(self.instance), False)
9581
      except errors.GenericError:
9582
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9583
        raise
9584

    
9585
    # We have new devices, shutdown the drbd on the old secondary
9586
    for idx, dev in enumerate(self.instance.disks):
9587
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9588
      self.cfg.SetDiskID(dev, self.target_node)
9589
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9590
      if msg:
9591
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9592
                           "node: %s" % (idx, msg),
9593
                           hint=("Please cleanup this device manually as"
9594
                                 " soon as possible"))
9595

    
9596
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9597
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9598
                                               self.node_secondary_ip,
9599
                                               self.instance.disks)\
9600
                                              [self.instance.primary_node]
9601

    
9602
    msg = result.fail_msg
9603
    if msg:
9604
      # detaches didn't succeed (unlikely)
9605
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9606
      raise errors.OpExecError("Can't detach the disks from the network on"
9607
                               " old node: %s" % (msg,))
9608

    
9609
    # if we managed to detach at least one, we update all the disks of
9610
    # the instance to point to the new secondary
9611
    self.lu.LogInfo("Updating instance configuration")
9612
    for dev, _, new_logical_id in iv_names.itervalues():
9613
      dev.logical_id = new_logical_id
9614
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9615

    
9616
    self.cfg.Update(self.instance, feedback_fn)
9617

    
9618
    # and now perform the drbd attach
9619
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9620
                    " (standalone => connected)")
9621
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9622
                                            self.new_node],
9623
                                           self.node_secondary_ip,
9624
                                           self.instance.disks,
9625
                                           self.instance.name,
9626
                                           False)
9627
    for to_node, to_result in result.items():
9628
      msg = to_result.fail_msg
9629
      if msg:
9630
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9631
                           to_node, msg,
9632
                           hint=("please do a gnt-instance info to see the"
9633
                                 " status of disks"))
9634
    cstep = 5
9635
    if self.early_release:
9636
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9637
      cstep += 1
9638
      self._RemoveOldStorage(self.target_node, iv_names)
9639
      # WARNING: we release all node locks here, do not do other RPCs
9640
      # than WaitForSync to the primary node
9641
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9642
                    names=[self.instance.primary_node,
9643
                           self.target_node,
9644
                           self.new_node])
9645

    
9646
    # Wait for sync
9647
    # This can fail as the old devices are degraded and _WaitForSync
9648
    # does a combined result over all disks, so we don't check its return value
9649
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9650
    cstep += 1
9651
    _WaitForSync(self.lu, self.instance)
9652

    
9653
    # Check all devices manually
9654
    self._CheckDevices(self.instance.primary_node, iv_names)
9655

    
9656
    # Step: remove old storage
9657
    if not self.early_release:
9658
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9659
      self._RemoveOldStorage(self.target_node, iv_names)
9660

    
9661

    
9662
class LURepairNodeStorage(NoHooksLU):
9663
  """Repairs the volume group on a node.
9664

9665
  """
9666
  REQ_BGL = False
9667

    
9668
  def CheckArguments(self):
9669
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9670

    
9671
    storage_type = self.op.storage_type
9672

    
9673
    if (constants.SO_FIX_CONSISTENCY not in
9674
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9675
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9676
                                 " repaired" % storage_type,
9677
                                 errors.ECODE_INVAL)
9678

    
9679
  def ExpandNames(self):
9680
    self.needed_locks = {
9681
      locking.LEVEL_NODE: [self.op.node_name],
9682
      }
9683

    
9684
  def _CheckFaultyDisks(self, instance, node_name):
9685
    """Ensure faulty disks abort the opcode or at least warn."""
9686
    try:
9687
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9688
                                  node_name, True):
9689
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9690
                                   " node '%s'" % (instance.name, node_name),
9691
                                   errors.ECODE_STATE)
9692
    except errors.OpPrereqError, err:
9693
      if self.op.ignore_consistency:
9694
        self.proc.LogWarning(str(err.args[0]))
9695
      else:
9696
        raise
9697

    
9698
  def CheckPrereq(self):
9699
    """Check prerequisites.
9700

9701
    """
9702
    # Check whether any instance on this node has faulty disks
9703
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9704
      if not inst.admin_up:
9705
        continue
9706
      check_nodes = set(inst.all_nodes)
9707
      check_nodes.discard(self.op.node_name)
9708
      for inst_node_name in check_nodes:
9709
        self._CheckFaultyDisks(inst, inst_node_name)
9710

    
9711
  def Exec(self, feedback_fn):
9712
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9713
                (self.op.name, self.op.node_name))
9714

    
9715
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9716
    result = self.rpc.call_storage_execute(self.op.node_name,
9717
                                           self.op.storage_type, st_args,
9718
                                           self.op.name,
9719
                                           constants.SO_FIX_CONSISTENCY)
9720
    result.Raise("Failed to repair storage unit '%s' on %s" %
9721
                 (self.op.name, self.op.node_name))
9722

    
9723

    
9724
class LUNodeEvacStrategy(NoHooksLU):
9725
  """Computes the node evacuation strategy.
9726

9727
  """
9728
  REQ_BGL = False
9729

    
9730
  def CheckArguments(self):
9731
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9732

    
9733
  def ExpandNames(self):
9734
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9735
    self.needed_locks = locks = {}
9736
    if self.op.remote_node is None:
9737
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9738
    else:
9739
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9740
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9741

    
9742
  def Exec(self, feedback_fn):
9743
    if self.op.remote_node is not None:
9744
      instances = []
9745
      for node in self.op.nodes:
9746
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9747
      result = []
9748
      for i in instances:
9749
        if i.primary_node == self.op.remote_node:
9750
          raise errors.OpPrereqError("Node %s is the primary node of"
9751
                                     " instance %s, cannot use it as"
9752
                                     " secondary" %
9753
                                     (self.op.remote_node, i.name),
9754
                                     errors.ECODE_INVAL)
9755
        result.append([i.name, self.op.remote_node])
9756
    else:
9757
      ial = IAllocator(self.cfg, self.rpc,
9758
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9759
                       evac_nodes=self.op.nodes)
9760
      ial.Run(self.op.iallocator, validate=True)
9761
      if not ial.success:
9762
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9763
                                 errors.ECODE_NORES)
9764
      result = ial.result
9765
    return result
9766

    
9767

    
9768
class LUInstanceGrowDisk(LogicalUnit):
9769
  """Grow a disk of an instance.
9770

9771
  """
9772
  HPATH = "disk-grow"
9773
  HTYPE = constants.HTYPE_INSTANCE
9774
  REQ_BGL = False
9775

    
9776
  def ExpandNames(self):
9777
    self._ExpandAndLockInstance()
9778
    self.needed_locks[locking.LEVEL_NODE] = []
9779
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9780

    
9781
  def DeclareLocks(self, level):
9782
    if level == locking.LEVEL_NODE:
9783
      self._LockInstancesNodes()
9784

    
9785
  def BuildHooksEnv(self):
9786
    """Build hooks env.
9787

9788
    This runs on the master, the primary and all the secondaries.
9789

9790
    """
9791
    env = {
9792
      "DISK": self.op.disk,
9793
      "AMOUNT": self.op.amount,
9794
      }
9795
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9796
    return env
9797

    
9798
  def BuildHooksNodes(self):
9799
    """Build hooks nodes.
9800

9801
    """
9802
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9803
    return (nl, nl)
9804

    
9805
  def CheckPrereq(self):
9806
    """Check prerequisites.
9807

9808
    This checks that the instance is in the cluster.
9809

9810
    """
9811
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9812
    assert instance is not None, \
9813
      "Cannot retrieve locked instance %s" % self.op.instance_name
9814
    nodenames = list(instance.all_nodes)
9815
    for node in nodenames:
9816
      _CheckNodeOnline(self, node)
9817

    
9818
    self.instance = instance
9819

    
9820
    if instance.disk_template not in constants.DTS_GROWABLE:
9821
      raise errors.OpPrereqError("Instance's disk layout does not support"
9822
                                 " growing", errors.ECODE_INVAL)
9823

    
9824
    self.disk = instance.FindDisk(self.op.disk)
9825

    
9826
    if instance.disk_template not in (constants.DT_FILE,
9827
                                      constants.DT_SHARED_FILE):
9828
      # TODO: check the free disk space for file, when that feature will be
9829
      # supported
9830
      _CheckNodesFreeDiskPerVG(self, nodenames,
9831
                               self.disk.ComputeGrowth(self.op.amount))
9832

    
9833
  def Exec(self, feedback_fn):
9834
    """Execute disk grow.
9835

9836
    """
9837
    instance = self.instance
9838
    disk = self.disk
9839

    
9840
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9841
    if not disks_ok:
9842
      raise errors.OpExecError("Cannot activate block device to grow")
9843

    
9844
    # First run all grow ops in dry-run mode
9845
    for node in instance.all_nodes:
9846
      self.cfg.SetDiskID(disk, node)
9847
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
9848
      result.Raise("Grow request failed to node %s" % node)
9849

    
9850
    # We know that (as far as we can test) operations across different
9851
    # nodes will succeed, time to run it for real
9852
    for node in instance.all_nodes:
9853
      self.cfg.SetDiskID(disk, node)
9854
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
9855
      result.Raise("Grow request failed to node %s" % node)
9856

    
9857
      # TODO: Rewrite code to work properly
9858
      # DRBD goes into sync mode for a short amount of time after executing the
9859
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9860
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9861
      # time is a work-around.
9862
      time.sleep(5)
9863

    
9864
    disk.RecordGrow(self.op.amount)
9865
    self.cfg.Update(instance, feedback_fn)
9866
    if self.op.wait_for_sync:
9867
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9868
      if disk_abort:
9869
        self.proc.LogWarning("Disk sync-ing has not returned a good"
9870
                             " status; please check the instance")
9871
      if not instance.admin_up:
9872
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9873
    elif not instance.admin_up:
9874
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9875
                           " not supposed to be running because no wait for"
9876
                           " sync mode was requested")
9877

    
9878

    
9879
class LUInstanceQueryData(NoHooksLU):
9880
  """Query runtime instance data.
9881

9882
  """
9883
  REQ_BGL = False
9884

    
9885
  def ExpandNames(self):
9886
    self.needed_locks = {}
9887

    
9888
    # Use locking if requested or when non-static information is wanted
9889
    if not (self.op.static or self.op.use_locking):
9890
      self.LogWarning("Non-static data requested, locks need to be acquired")
9891
      self.op.use_locking = True
9892

    
9893
    if self.op.instances or not self.op.use_locking:
9894
      # Expand instance names right here
9895
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
9896
    else:
9897
      # Will use acquired locks
9898
      self.wanted_names = None
9899

    
9900
    if self.op.use_locking:
9901
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9902

    
9903
      if self.wanted_names is None:
9904
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9905
      else:
9906
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9907

    
9908
      self.needed_locks[locking.LEVEL_NODE] = []
9909
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9910
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9911

    
9912
  def DeclareLocks(self, level):
9913
    if self.op.use_locking and level == locking.LEVEL_NODE:
9914
      self._LockInstancesNodes()
9915

    
9916
  def CheckPrereq(self):
9917
    """Check prerequisites.
9918

9919
    This only checks the optional instance list against the existing names.
9920

9921
    """
9922
    if self.wanted_names is None:
9923
      assert self.op.use_locking, "Locking was not used"
9924
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
9925

    
9926
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
9927
                             for name in self.wanted_names]
9928

    
9929
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9930
    """Returns the status of a block device
9931

9932
    """
9933
    if self.op.static or not node:
9934
      return None
9935

    
9936
    self.cfg.SetDiskID(dev, node)
9937

    
9938
    result = self.rpc.call_blockdev_find(node, dev)
9939
    if result.offline:
9940
      return None
9941

    
9942
    result.Raise("Can't compute disk status for %s" % instance_name)
9943

    
9944
    status = result.payload
9945
    if status is None:
9946
      return None
9947

    
9948
    return (status.dev_path, status.major, status.minor,
9949
            status.sync_percent, status.estimated_time,
9950
            status.is_degraded, status.ldisk_status)
9951

    
9952
  def _ComputeDiskStatus(self, instance, snode, dev):
9953
    """Compute block device status.
9954

9955
    """
9956
    if dev.dev_type in constants.LDS_DRBD:
9957
      # we change the snode then (otherwise we use the one passed in)
9958
      if dev.logical_id[0] == instance.primary_node:
9959
        snode = dev.logical_id[1]
9960
      else:
9961
        snode = dev.logical_id[0]
9962

    
9963
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9964
                                              instance.name, dev)
9965
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9966

    
9967
    if dev.children:
9968
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9969
                      for child in dev.children]
9970
    else:
9971
      dev_children = []
9972

    
9973
    return {
9974
      "iv_name": dev.iv_name,
9975
      "dev_type": dev.dev_type,
9976
      "logical_id": dev.logical_id,
9977
      "physical_id": dev.physical_id,
9978
      "pstatus": dev_pstatus,
9979
      "sstatus": dev_sstatus,
9980
      "children": dev_children,
9981
      "mode": dev.mode,
9982
      "size": dev.size,
9983
      }
9984

    
9985
  def Exec(self, feedback_fn):
9986
    """Gather and return data"""
9987
    result = {}
9988

    
9989
    cluster = self.cfg.GetClusterInfo()
9990

    
9991
    for instance in self.wanted_instances:
9992
      if not self.op.static:
9993
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9994
                                                  instance.name,
9995
                                                  instance.hypervisor)
9996
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9997
        remote_info = remote_info.payload
9998
        if remote_info and "state" in remote_info:
9999
          remote_state = "up"
10000
        else:
10001
          remote_state = "down"
10002
      else:
10003
        remote_state = None
10004
      if instance.admin_up:
10005
        config_state = "up"
10006
      else:
10007
        config_state = "down"
10008

    
10009
      disks = [self._ComputeDiskStatus(instance, None, device)
10010
               for device in instance.disks]
10011

    
10012
      result[instance.name] = {
10013
        "name": instance.name,
10014
        "config_state": config_state,
10015
        "run_state": remote_state,
10016
        "pnode": instance.primary_node,
10017
        "snodes": instance.secondary_nodes,
10018
        "os": instance.os,
10019
        # this happens to be the same format used for hooks
10020
        "nics": _NICListToTuple(self, instance.nics),
10021
        "disk_template": instance.disk_template,
10022
        "disks": disks,
10023
        "hypervisor": instance.hypervisor,
10024
        "network_port": instance.network_port,
10025
        "hv_instance": instance.hvparams,
10026
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
10027
        "be_instance": instance.beparams,
10028
        "be_actual": cluster.FillBE(instance),
10029
        "os_instance": instance.osparams,
10030
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
10031
        "serial_no": instance.serial_no,
10032
        "mtime": instance.mtime,
10033
        "ctime": instance.ctime,
10034
        "uuid": instance.uuid,
10035
        }
10036

    
10037
    return result
10038

    
10039

    
10040
class LUInstanceSetParams(LogicalUnit):
10041
  """Modifies an instances's parameters.
10042

10043
  """
10044
  HPATH = "instance-modify"
10045
  HTYPE = constants.HTYPE_INSTANCE
10046
  REQ_BGL = False
10047

    
10048
  def CheckArguments(self):
10049
    if not (self.op.nics or self.op.disks or self.op.disk_template or
10050
            self.op.hvparams or self.op.beparams or self.op.os_name):
10051
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
10052

    
10053
    if self.op.hvparams:
10054
      _CheckGlobalHvParams(self.op.hvparams)
10055

    
10056
    # Disk validation
10057
    disk_addremove = 0
10058
    for disk_op, disk_dict in self.op.disks:
10059
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
10060
      if disk_op == constants.DDM_REMOVE:
10061
        disk_addremove += 1
10062
        continue
10063
      elif disk_op == constants.DDM_ADD:
10064
        disk_addremove += 1
10065
      else:
10066
        if not isinstance(disk_op, int):
10067
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
10068
        if not isinstance(disk_dict, dict):
10069
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
10070
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10071

    
10072
      if disk_op == constants.DDM_ADD:
10073
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
10074
        if mode not in constants.DISK_ACCESS_SET:
10075
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
10076
                                     errors.ECODE_INVAL)
10077
        size = disk_dict.get(constants.IDISK_SIZE, None)
10078
        if size is None:
10079
          raise errors.OpPrereqError("Required disk parameter size missing",
10080
                                     errors.ECODE_INVAL)
10081
        try:
10082
          size = int(size)
10083
        except (TypeError, ValueError), err:
10084
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10085
                                     str(err), errors.ECODE_INVAL)
10086
        disk_dict[constants.IDISK_SIZE] = size
10087
      else:
10088
        # modification of disk
10089
        if constants.IDISK_SIZE in disk_dict:
10090
          raise errors.OpPrereqError("Disk size change not possible, use"
10091
                                     " grow-disk", errors.ECODE_INVAL)
10092

    
10093
    if disk_addremove > 1:
10094
      raise errors.OpPrereqError("Only one disk add or remove operation"
10095
                                 " supported at a time", errors.ECODE_INVAL)
10096

    
10097
    if self.op.disks and self.op.disk_template is not None:
10098
      raise errors.OpPrereqError("Disk template conversion and other disk"
10099
                                 " changes not supported at the same time",
10100
                                 errors.ECODE_INVAL)
10101

    
10102
    if (self.op.disk_template and
10103
        self.op.disk_template in constants.DTS_INT_MIRROR and
10104
        self.op.remote_node is None):
10105
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
10106
                                 " one requires specifying a secondary node",
10107
                                 errors.ECODE_INVAL)
10108

    
10109
    # NIC validation
10110
    nic_addremove = 0
10111
    for nic_op, nic_dict in self.op.nics:
10112
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10113
      if nic_op == constants.DDM_REMOVE:
10114
        nic_addremove += 1
10115
        continue
10116
      elif nic_op == constants.DDM_ADD:
10117
        nic_addremove += 1
10118
      else:
10119
        if not isinstance(nic_op, int):
10120
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10121
        if not isinstance(nic_dict, dict):
10122
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10123
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10124

    
10125
      # nic_dict should be a dict
10126
      nic_ip = nic_dict.get(constants.INIC_IP, None)
10127
      if nic_ip is not None:
10128
        if nic_ip.lower() == constants.VALUE_NONE:
10129
          nic_dict[constants.INIC_IP] = None
10130
        else:
10131
          if not netutils.IPAddress.IsValid(nic_ip):
10132
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10133
                                       errors.ECODE_INVAL)
10134

    
10135
      nic_bridge = nic_dict.get('bridge', None)
10136
      nic_link = nic_dict.get(constants.INIC_LINK, None)
10137
      if nic_bridge and nic_link:
10138
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10139
                                   " at the same time", errors.ECODE_INVAL)
10140
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10141
        nic_dict['bridge'] = None
10142
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10143
        nic_dict[constants.INIC_LINK] = None
10144

    
10145
      if nic_op == constants.DDM_ADD:
10146
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
10147
        if nic_mac is None:
10148
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10149

    
10150
      if constants.INIC_MAC in nic_dict:
10151
        nic_mac = nic_dict[constants.INIC_MAC]
10152
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10153
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10154

    
10155
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10156
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10157
                                     " modifying an existing nic",
10158
                                     errors.ECODE_INVAL)
10159

    
10160
    if nic_addremove > 1:
10161
      raise errors.OpPrereqError("Only one NIC add or remove operation"
10162
                                 " supported at a time", errors.ECODE_INVAL)
10163

    
10164
  def ExpandNames(self):
10165
    self._ExpandAndLockInstance()
10166
    self.needed_locks[locking.LEVEL_NODE] = []
10167
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10168

    
10169
  def DeclareLocks(self, level):
10170
    if level == locking.LEVEL_NODE:
10171
      self._LockInstancesNodes()
10172
      if self.op.disk_template and self.op.remote_node:
10173
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10174
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10175

    
10176
  def BuildHooksEnv(self):
10177
    """Build hooks env.
10178

10179
    This runs on the master, primary and secondaries.
10180

10181
    """
10182
    args = dict()
10183
    if constants.BE_MEMORY in self.be_new:
10184
      args['memory'] = self.be_new[constants.BE_MEMORY]
10185
    if constants.BE_VCPUS in self.be_new:
10186
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
10187
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10188
    # information at all.
10189
    if self.op.nics:
10190
      args['nics'] = []
10191
      nic_override = dict(self.op.nics)
10192
      for idx, nic in enumerate(self.instance.nics):
10193
        if idx in nic_override:
10194
          this_nic_override = nic_override[idx]
10195
        else:
10196
          this_nic_override = {}
10197
        if constants.INIC_IP in this_nic_override:
10198
          ip = this_nic_override[constants.INIC_IP]
10199
        else:
10200
          ip = nic.ip
10201
        if constants.INIC_MAC in this_nic_override:
10202
          mac = this_nic_override[constants.INIC_MAC]
10203
        else:
10204
          mac = nic.mac
10205
        if idx in self.nic_pnew:
10206
          nicparams = self.nic_pnew[idx]
10207
        else:
10208
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10209
        mode = nicparams[constants.NIC_MODE]
10210
        link = nicparams[constants.NIC_LINK]
10211
        args['nics'].append((ip, mac, mode, link))
10212
      if constants.DDM_ADD in nic_override:
10213
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10214
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10215
        nicparams = self.nic_pnew[constants.DDM_ADD]
10216
        mode = nicparams[constants.NIC_MODE]
10217
        link = nicparams[constants.NIC_LINK]
10218
        args['nics'].append((ip, mac, mode, link))
10219
      elif constants.DDM_REMOVE in nic_override:
10220
        del args['nics'][-1]
10221

    
10222
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10223
    if self.op.disk_template:
10224
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10225

    
10226
    return env
10227

    
10228
  def BuildHooksNodes(self):
10229
    """Build hooks nodes.
10230

10231
    """
10232
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10233
    return (nl, nl)
10234

    
10235
  def CheckPrereq(self):
10236
    """Check prerequisites.
10237

10238
    This only checks the instance list against the existing names.
10239

10240
    """
10241
    # checking the new params on the primary/secondary nodes
10242

    
10243
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10244
    cluster = self.cluster = self.cfg.GetClusterInfo()
10245
    assert self.instance is not None, \
10246
      "Cannot retrieve locked instance %s" % self.op.instance_name
10247
    pnode = instance.primary_node
10248
    nodelist = list(instance.all_nodes)
10249

    
10250
    # OS change
10251
    if self.op.os_name and not self.op.force:
10252
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10253
                      self.op.force_variant)
10254
      instance_os = self.op.os_name
10255
    else:
10256
      instance_os = instance.os
10257

    
10258
    if self.op.disk_template:
10259
      if instance.disk_template == self.op.disk_template:
10260
        raise errors.OpPrereqError("Instance already has disk template %s" %
10261
                                   instance.disk_template, errors.ECODE_INVAL)
10262

    
10263
      if (instance.disk_template,
10264
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10265
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10266
                                   " %s to %s" % (instance.disk_template,
10267
                                                  self.op.disk_template),
10268
                                   errors.ECODE_INVAL)
10269
      _CheckInstanceDown(self, instance, "cannot change disk template")
10270
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10271
        if self.op.remote_node == pnode:
10272
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10273
                                     " as the primary node of the instance" %
10274
                                     self.op.remote_node, errors.ECODE_STATE)
10275
        _CheckNodeOnline(self, self.op.remote_node)
10276
        _CheckNodeNotDrained(self, self.op.remote_node)
10277
        # FIXME: here we assume that the old instance type is DT_PLAIN
10278
        assert instance.disk_template == constants.DT_PLAIN
10279
        disks = [{constants.IDISK_SIZE: d.size,
10280
                  constants.IDISK_VG: d.logical_id[0]}
10281
                 for d in instance.disks]
10282
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10283
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10284

    
10285
    # hvparams processing
10286
    if self.op.hvparams:
10287
      hv_type = instance.hypervisor
10288
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10289
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10290
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10291

    
10292
      # local check
10293
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10294
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10295
      self.hv_new = hv_new # the new actual values
10296
      self.hv_inst = i_hvdict # the new dict (without defaults)
10297
    else:
10298
      self.hv_new = self.hv_inst = {}
10299

    
10300
    # beparams processing
10301
    if self.op.beparams:
10302
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10303
                                   use_none=True)
10304
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10305
      be_new = cluster.SimpleFillBE(i_bedict)
10306
      self.be_new = be_new # the new actual values
10307
      self.be_inst = i_bedict # the new dict (without defaults)
10308
    else:
10309
      self.be_new = self.be_inst = {}
10310
    be_old = cluster.FillBE(instance)
10311

    
10312
    # osparams processing
10313
    if self.op.osparams:
10314
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10315
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10316
      self.os_inst = i_osdict # the new dict (without defaults)
10317
    else:
10318
      self.os_inst = {}
10319

    
10320
    self.warn = []
10321

    
10322
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10323
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10324
      mem_check_list = [pnode]
10325
      if be_new[constants.BE_AUTO_BALANCE]:
10326
        # either we changed auto_balance to yes or it was from before
10327
        mem_check_list.extend(instance.secondary_nodes)
10328
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10329
                                                  instance.hypervisor)
10330
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10331
                                         instance.hypervisor)
10332
      pninfo = nodeinfo[pnode]
10333
      msg = pninfo.fail_msg
10334
      if msg:
10335
        # Assume the primary node is unreachable and go ahead
10336
        self.warn.append("Can't get info from primary node %s: %s" %
10337
                         (pnode,  msg))
10338
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10339
        self.warn.append("Node data from primary node %s doesn't contain"
10340
                         " free memory information" % pnode)
10341
      elif instance_info.fail_msg:
10342
        self.warn.append("Can't get instance runtime information: %s" %
10343
                        instance_info.fail_msg)
10344
      else:
10345
        if instance_info.payload:
10346
          current_mem = int(instance_info.payload['memory'])
10347
        else:
10348
          # Assume instance not running
10349
          # (there is a slight race condition here, but it's not very probable,
10350
          # and we have no other way to check)
10351
          current_mem = 0
10352
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10353
                    pninfo.payload['memory_free'])
10354
        if miss_mem > 0:
10355
          raise errors.OpPrereqError("This change will prevent the instance"
10356
                                     " from starting, due to %d MB of memory"
10357
                                     " missing on its primary node" % miss_mem,
10358
                                     errors.ECODE_NORES)
10359

    
10360
      if be_new[constants.BE_AUTO_BALANCE]:
10361
        for node, nres in nodeinfo.items():
10362
          if node not in instance.secondary_nodes:
10363
            continue
10364
          nres.Raise("Can't get info from secondary node %s" % node,
10365
                     prereq=True, ecode=errors.ECODE_STATE)
10366
          if not isinstance(nres.payload.get('memory_free', None), int):
10367
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10368
                                       " memory information" % node,
10369
                                       errors.ECODE_STATE)
10370
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10371
            raise errors.OpPrereqError("This change will prevent the instance"
10372
                                       " from failover to its secondary node"
10373
                                       " %s, due to not enough memory" % node,
10374
                                       errors.ECODE_STATE)
10375

    
10376
    # NIC processing
10377
    self.nic_pnew = {}
10378
    self.nic_pinst = {}
10379
    for nic_op, nic_dict in self.op.nics:
10380
      if nic_op == constants.DDM_REMOVE:
10381
        if not instance.nics:
10382
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10383
                                     errors.ECODE_INVAL)
10384
        continue
10385
      if nic_op != constants.DDM_ADD:
10386
        # an existing nic
10387
        if not instance.nics:
10388
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10389
                                     " no NICs" % nic_op,
10390
                                     errors.ECODE_INVAL)
10391
        if nic_op < 0 or nic_op >= len(instance.nics):
10392
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10393
                                     " are 0 to %d" %
10394
                                     (nic_op, len(instance.nics) - 1),
10395
                                     errors.ECODE_INVAL)
10396
        old_nic_params = instance.nics[nic_op].nicparams
10397
        old_nic_ip = instance.nics[nic_op].ip
10398
      else:
10399
        old_nic_params = {}
10400
        old_nic_ip = None
10401

    
10402
      update_params_dict = dict([(key, nic_dict[key])
10403
                                 for key in constants.NICS_PARAMETERS
10404
                                 if key in nic_dict])
10405

    
10406
      if 'bridge' in nic_dict:
10407
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10408

    
10409
      new_nic_params = _GetUpdatedParams(old_nic_params,
10410
                                         update_params_dict)
10411
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10412
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10413
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10414
      self.nic_pinst[nic_op] = new_nic_params
10415
      self.nic_pnew[nic_op] = new_filled_nic_params
10416
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10417

    
10418
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10419
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10420
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10421
        if msg:
10422
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10423
          if self.op.force:
10424
            self.warn.append(msg)
10425
          else:
10426
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10427
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10428
        if constants.INIC_IP in nic_dict:
10429
          nic_ip = nic_dict[constants.INIC_IP]
10430
        else:
10431
          nic_ip = old_nic_ip
10432
        if nic_ip is None:
10433
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10434
                                     ' on a routed nic', errors.ECODE_INVAL)
10435
      if constants.INIC_MAC in nic_dict:
10436
        nic_mac = nic_dict[constants.INIC_MAC]
10437
        if nic_mac is None:
10438
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10439
                                     errors.ECODE_INVAL)
10440
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10441
          # otherwise generate the mac
10442
          nic_dict[constants.INIC_MAC] = \
10443
            self.cfg.GenerateMAC(self.proc.GetECId())
10444
        else:
10445
          # or validate/reserve the current one
10446
          try:
10447
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10448
          except errors.ReservationError:
10449
            raise errors.OpPrereqError("MAC address %s already in use"
10450
                                       " in cluster" % nic_mac,
10451
                                       errors.ECODE_NOTUNIQUE)
10452

    
10453
    # DISK processing
10454
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10455
      raise errors.OpPrereqError("Disk operations not supported for"
10456
                                 " diskless instances",
10457
                                 errors.ECODE_INVAL)
10458
    for disk_op, _ in self.op.disks:
10459
      if disk_op == constants.DDM_REMOVE:
10460
        if len(instance.disks) == 1:
10461
          raise errors.OpPrereqError("Cannot remove the last disk of"
10462
                                     " an instance", errors.ECODE_INVAL)
10463
        _CheckInstanceDown(self, instance, "cannot remove disks")
10464

    
10465
      if (disk_op == constants.DDM_ADD and
10466
          len(instance.disks) >= constants.MAX_DISKS):
10467
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10468
                                   " add more" % constants.MAX_DISKS,
10469
                                   errors.ECODE_STATE)
10470
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10471
        # an existing disk
10472
        if disk_op < 0 or disk_op >= len(instance.disks):
10473
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10474
                                     " are 0 to %d" %
10475
                                     (disk_op, len(instance.disks)),
10476
                                     errors.ECODE_INVAL)
10477

    
10478
    return
10479

    
10480
  def _ConvertPlainToDrbd(self, feedback_fn):
10481
    """Converts an instance from plain to drbd.
10482

10483
    """
10484
    feedback_fn("Converting template to drbd")
10485
    instance = self.instance
10486
    pnode = instance.primary_node
10487
    snode = self.op.remote_node
10488

    
10489
    # create a fake disk info for _GenerateDiskTemplate
10490
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10491
                  constants.IDISK_VG: d.logical_id[0]}
10492
                 for d in instance.disks]
10493
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10494
                                      instance.name, pnode, [snode],
10495
                                      disk_info, None, None, 0, feedback_fn)
10496
    info = _GetInstanceInfoText(instance)
10497
    feedback_fn("Creating aditional volumes...")
10498
    # first, create the missing data and meta devices
10499
    for disk in new_disks:
10500
      # unfortunately this is... not too nice
10501
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10502
                            info, True)
10503
      for child in disk.children:
10504
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10505
    # at this stage, all new LVs have been created, we can rename the
10506
    # old ones
10507
    feedback_fn("Renaming original volumes...")
10508
    rename_list = [(o, n.children[0].logical_id)
10509
                   for (o, n) in zip(instance.disks, new_disks)]
10510
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10511
    result.Raise("Failed to rename original LVs")
10512

    
10513
    feedback_fn("Initializing DRBD devices...")
10514
    # all child devices are in place, we can now create the DRBD devices
10515
    for disk in new_disks:
10516
      for node in [pnode, snode]:
10517
        f_create = node == pnode
10518
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10519

    
10520
    # at this point, the instance has been modified
10521
    instance.disk_template = constants.DT_DRBD8
10522
    instance.disks = new_disks
10523
    self.cfg.Update(instance, feedback_fn)
10524

    
10525
    # disks are created, waiting for sync
10526
    disk_abort = not _WaitForSync(self, instance,
10527
                                  oneshot=not self.op.wait_for_sync)
10528
    if disk_abort:
10529
      raise errors.OpExecError("There are some degraded disks for"
10530
                               " this instance, please cleanup manually")
10531

    
10532
  def _ConvertDrbdToPlain(self, feedback_fn):
10533
    """Converts an instance from drbd to plain.
10534

10535
    """
10536
    instance = self.instance
10537
    assert len(instance.secondary_nodes) == 1
10538
    pnode = instance.primary_node
10539
    snode = instance.secondary_nodes[0]
10540
    feedback_fn("Converting template to plain")
10541

    
10542
    old_disks = instance.disks
10543
    new_disks = [d.children[0] for d in old_disks]
10544

    
10545
    # copy over size and mode
10546
    for parent, child in zip(old_disks, new_disks):
10547
      child.size = parent.size
10548
      child.mode = parent.mode
10549

    
10550
    # update instance structure
10551
    instance.disks = new_disks
10552
    instance.disk_template = constants.DT_PLAIN
10553
    self.cfg.Update(instance, feedback_fn)
10554

    
10555
    feedback_fn("Removing volumes on the secondary node...")
10556
    for disk in old_disks:
10557
      self.cfg.SetDiskID(disk, snode)
10558
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10559
      if msg:
10560
        self.LogWarning("Could not remove block device %s on node %s,"
10561
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10562

    
10563
    feedback_fn("Removing unneeded volumes on the primary node...")
10564
    for idx, disk in enumerate(old_disks):
10565
      meta = disk.children[1]
10566
      self.cfg.SetDiskID(meta, pnode)
10567
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10568
      if msg:
10569
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10570
                        " continuing anyway: %s", idx, pnode, msg)
10571

    
10572
  def Exec(self, feedback_fn):
10573
    """Modifies an instance.
10574

10575
    All parameters take effect only at the next restart of the instance.
10576

10577
    """
10578
    # Process here the warnings from CheckPrereq, as we don't have a
10579
    # feedback_fn there.
10580
    for warn in self.warn:
10581
      feedback_fn("WARNING: %s" % warn)
10582

    
10583
    result = []
10584
    instance = self.instance
10585
    # disk changes
10586
    for disk_op, disk_dict in self.op.disks:
10587
      if disk_op == constants.DDM_REMOVE:
10588
        # remove the last disk
10589
        device = instance.disks.pop()
10590
        device_idx = len(instance.disks)
10591
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10592
          self.cfg.SetDiskID(disk, node)
10593
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10594
          if msg:
10595
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10596
                            " continuing anyway", device_idx, node, msg)
10597
        result.append(("disk/%d" % device_idx, "remove"))
10598
      elif disk_op == constants.DDM_ADD:
10599
        # add a new disk
10600
        if instance.disk_template in (constants.DT_FILE,
10601
                                        constants.DT_SHARED_FILE):
10602
          file_driver, file_path = instance.disks[0].logical_id
10603
          file_path = os.path.dirname(file_path)
10604
        else:
10605
          file_driver = file_path = None
10606
        disk_idx_base = len(instance.disks)
10607
        new_disk = _GenerateDiskTemplate(self,
10608
                                         instance.disk_template,
10609
                                         instance.name, instance.primary_node,
10610
                                         instance.secondary_nodes,
10611
                                         [disk_dict],
10612
                                         file_path,
10613
                                         file_driver,
10614
                                         disk_idx_base, feedback_fn)[0]
10615
        instance.disks.append(new_disk)
10616
        info = _GetInstanceInfoText(instance)
10617

    
10618
        logging.info("Creating volume %s for instance %s",
10619
                     new_disk.iv_name, instance.name)
10620
        # Note: this needs to be kept in sync with _CreateDisks
10621
        #HARDCODE
10622
        for node in instance.all_nodes:
10623
          f_create = node == instance.primary_node
10624
          try:
10625
            _CreateBlockDev(self, node, instance, new_disk,
10626
                            f_create, info, f_create)
10627
          except errors.OpExecError, err:
10628
            self.LogWarning("Failed to create volume %s (%s) on"
10629
                            " node %s: %s",
10630
                            new_disk.iv_name, new_disk, node, err)
10631
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10632
                       (new_disk.size, new_disk.mode)))
10633
      else:
10634
        # change a given disk
10635
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10636
        result.append(("disk.mode/%d" % disk_op,
10637
                       disk_dict[constants.IDISK_MODE]))
10638

    
10639
    if self.op.disk_template:
10640
      r_shut = _ShutdownInstanceDisks(self, instance)
10641
      if not r_shut:
10642
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10643
                                 " proceed with disk template conversion")
10644
      mode = (instance.disk_template, self.op.disk_template)
10645
      try:
10646
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10647
      except:
10648
        self.cfg.ReleaseDRBDMinors(instance.name)
10649
        raise
10650
      result.append(("disk_template", self.op.disk_template))
10651

    
10652
    # NIC changes
10653
    for nic_op, nic_dict in self.op.nics:
10654
      if nic_op == constants.DDM_REMOVE:
10655
        # remove the last nic
10656
        del instance.nics[-1]
10657
        result.append(("nic.%d" % len(instance.nics), "remove"))
10658
      elif nic_op == constants.DDM_ADD:
10659
        # mac and bridge should be set, by now
10660
        mac = nic_dict[constants.INIC_MAC]
10661
        ip = nic_dict.get(constants.INIC_IP, None)
10662
        nicparams = self.nic_pinst[constants.DDM_ADD]
10663
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10664
        instance.nics.append(new_nic)
10665
        result.append(("nic.%d" % (len(instance.nics) - 1),
10666
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10667
                       (new_nic.mac, new_nic.ip,
10668
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10669
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10670
                       )))
10671
      else:
10672
        for key in (constants.INIC_MAC, constants.INIC_IP):
10673
          if key in nic_dict:
10674
            setattr(instance.nics[nic_op], key, nic_dict[key])
10675
        if nic_op in self.nic_pinst:
10676
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10677
        for key, val in nic_dict.iteritems():
10678
          result.append(("nic.%s/%d" % (key, nic_op), val))
10679

    
10680
    # hvparams changes
10681
    if self.op.hvparams:
10682
      instance.hvparams = self.hv_inst
10683
      for key, val in self.op.hvparams.iteritems():
10684
        result.append(("hv/%s" % key, val))
10685

    
10686
    # beparams changes
10687
    if self.op.beparams:
10688
      instance.beparams = self.be_inst
10689
      for key, val in self.op.beparams.iteritems():
10690
        result.append(("be/%s" % key, val))
10691

    
10692
    # OS change
10693
    if self.op.os_name:
10694
      instance.os = self.op.os_name
10695

    
10696
    # osparams changes
10697
    if self.op.osparams:
10698
      instance.osparams = self.os_inst
10699
      for key, val in self.op.osparams.iteritems():
10700
        result.append(("os/%s" % key, val))
10701

    
10702
    self.cfg.Update(instance, feedback_fn)
10703

    
10704
    return result
10705

    
10706
  _DISK_CONVERSIONS = {
10707
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10708
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10709
    }
10710

    
10711

    
10712
class LUBackupQuery(NoHooksLU):
10713
  """Query the exports list
10714

10715
  """
10716
  REQ_BGL = False
10717

    
10718
  def ExpandNames(self):
10719
    self.needed_locks = {}
10720
    self.share_locks[locking.LEVEL_NODE] = 1
10721
    if not self.op.nodes:
10722
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10723
    else:
10724
      self.needed_locks[locking.LEVEL_NODE] = \
10725
        _GetWantedNodes(self, self.op.nodes)
10726

    
10727
  def Exec(self, feedback_fn):
10728
    """Compute the list of all the exported system images.
10729

10730
    @rtype: dict
10731
    @return: a dictionary with the structure node->(export-list)
10732
        where export-list is a list of the instances exported on
10733
        that node.
10734

10735
    """
10736
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10737
    rpcresult = self.rpc.call_export_list(self.nodes)
10738
    result = {}
10739
    for node in rpcresult:
10740
      if rpcresult[node].fail_msg:
10741
        result[node] = False
10742
      else:
10743
        result[node] = rpcresult[node].payload
10744

    
10745
    return result
10746

    
10747

    
10748
class LUBackupPrepare(NoHooksLU):
10749
  """Prepares an instance for an export and returns useful information.
10750

10751
  """
10752
  REQ_BGL = False
10753

    
10754
  def ExpandNames(self):
10755
    self._ExpandAndLockInstance()
10756

    
10757
  def CheckPrereq(self):
10758
    """Check prerequisites.
10759

10760
    """
10761
    instance_name = self.op.instance_name
10762

    
10763
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10764
    assert self.instance is not None, \
10765
          "Cannot retrieve locked instance %s" % self.op.instance_name
10766
    _CheckNodeOnline(self, self.instance.primary_node)
10767

    
10768
    self._cds = _GetClusterDomainSecret()
10769

    
10770
  def Exec(self, feedback_fn):
10771
    """Prepares an instance for an export.
10772

10773
    """
10774
    instance = self.instance
10775

    
10776
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10777
      salt = utils.GenerateSecret(8)
10778

    
10779
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10780
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10781
                                              constants.RIE_CERT_VALIDITY)
10782
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10783

    
10784
      (name, cert_pem) = result.payload
10785

    
10786
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10787
                                             cert_pem)
10788

    
10789
      return {
10790
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10791
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10792
                          salt),
10793
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10794
        }
10795

    
10796
    return None
10797

    
10798

    
10799
class LUBackupExport(LogicalUnit):
10800
  """Export an instance to an image in the cluster.
10801

10802
  """
10803
  HPATH = "instance-export"
10804
  HTYPE = constants.HTYPE_INSTANCE
10805
  REQ_BGL = False
10806

    
10807
  def CheckArguments(self):
10808
    """Check the arguments.
10809

10810
    """
10811
    self.x509_key_name = self.op.x509_key_name
10812
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10813

    
10814
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10815
      if not self.x509_key_name:
10816
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10817
                                   errors.ECODE_INVAL)
10818

    
10819
      if not self.dest_x509_ca_pem:
10820
        raise errors.OpPrereqError("Missing destination X509 CA",
10821
                                   errors.ECODE_INVAL)
10822

    
10823
  def ExpandNames(self):
10824
    self._ExpandAndLockInstance()
10825

    
10826
    # Lock all nodes for local exports
10827
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10828
      # FIXME: lock only instance primary and destination node
10829
      #
10830
      # Sad but true, for now we have do lock all nodes, as we don't know where
10831
      # the previous export might be, and in this LU we search for it and
10832
      # remove it from its current node. In the future we could fix this by:
10833
      #  - making a tasklet to search (share-lock all), then create the
10834
      #    new one, then one to remove, after
10835
      #  - removing the removal operation altogether
10836
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10837

    
10838
  def DeclareLocks(self, level):
10839
    """Last minute lock declaration."""
10840
    # All nodes are locked anyway, so nothing to do here.
10841

    
10842
  def BuildHooksEnv(self):
10843
    """Build hooks env.
10844

10845
    This will run on the master, primary node and target node.
10846

10847
    """
10848
    env = {
10849
      "EXPORT_MODE": self.op.mode,
10850
      "EXPORT_NODE": self.op.target_node,
10851
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10852
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10853
      # TODO: Generic function for boolean env variables
10854
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10855
      }
10856

    
10857
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10858

    
10859
    return env
10860

    
10861
  def BuildHooksNodes(self):
10862
    """Build hooks nodes.
10863

10864
    """
10865
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10866

    
10867
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10868
      nl.append(self.op.target_node)
10869

    
10870
    return (nl, nl)
10871

    
10872
  def CheckPrereq(self):
10873
    """Check prerequisites.
10874

10875
    This checks that the instance and node names are valid.
10876

10877
    """
10878
    instance_name = self.op.instance_name
10879

    
10880
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10881
    assert self.instance is not None, \
10882
          "Cannot retrieve locked instance %s" % self.op.instance_name
10883
    _CheckNodeOnline(self, self.instance.primary_node)
10884

    
10885
    if (self.op.remove_instance and self.instance.admin_up and
10886
        not self.op.shutdown):
10887
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10888
                                 " down before")
10889

    
10890
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10891
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10892
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10893
      assert self.dst_node is not None
10894

    
10895
      _CheckNodeOnline(self, self.dst_node.name)
10896
      _CheckNodeNotDrained(self, self.dst_node.name)
10897

    
10898
      self._cds = None
10899
      self.dest_disk_info = None
10900
      self.dest_x509_ca = None
10901

    
10902
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10903
      self.dst_node = None
10904

    
10905
      if len(self.op.target_node) != len(self.instance.disks):
10906
        raise errors.OpPrereqError(("Received destination information for %s"
10907
                                    " disks, but instance %s has %s disks") %
10908
                                   (len(self.op.target_node), instance_name,
10909
                                    len(self.instance.disks)),
10910
                                   errors.ECODE_INVAL)
10911

    
10912
      cds = _GetClusterDomainSecret()
10913

    
10914
      # Check X509 key name
10915
      try:
10916
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10917
      except (TypeError, ValueError), err:
10918
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10919

    
10920
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10921
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10922
                                   errors.ECODE_INVAL)
10923

    
10924
      # Load and verify CA
10925
      try:
10926
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10927
      except OpenSSL.crypto.Error, err:
10928
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10929
                                   (err, ), errors.ECODE_INVAL)
10930

    
10931
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10932
      if errcode is not None:
10933
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10934
                                   (msg, ), errors.ECODE_INVAL)
10935

    
10936
      self.dest_x509_ca = cert
10937

    
10938
      # Verify target information
10939
      disk_info = []
10940
      for idx, disk_data in enumerate(self.op.target_node):
10941
        try:
10942
          (host, port, magic) = \
10943
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10944
        except errors.GenericError, err:
10945
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10946
                                     (idx, err), errors.ECODE_INVAL)
10947

    
10948
        disk_info.append((host, port, magic))
10949

    
10950
      assert len(disk_info) == len(self.op.target_node)
10951
      self.dest_disk_info = disk_info
10952

    
10953
    else:
10954
      raise errors.ProgrammerError("Unhandled export mode %r" %
10955
                                   self.op.mode)
10956

    
10957
    # instance disk type verification
10958
    # TODO: Implement export support for file-based disks
10959
    for disk in self.instance.disks:
10960
      if disk.dev_type == constants.LD_FILE:
10961
        raise errors.OpPrereqError("Export not supported for instances with"
10962
                                   " file-based disks", errors.ECODE_INVAL)
10963

    
10964
  def _CleanupExports(self, feedback_fn):
10965
    """Removes exports of current instance from all other nodes.
10966

10967
    If an instance in a cluster with nodes A..D was exported to node C, its
10968
    exports will be removed from the nodes A, B and D.
10969

10970
    """
10971
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10972

    
10973
    nodelist = self.cfg.GetNodeList()
10974
    nodelist.remove(self.dst_node.name)
10975

    
10976
    # on one-node clusters nodelist will be empty after the removal
10977
    # if we proceed the backup would be removed because OpBackupQuery
10978
    # substitutes an empty list with the full cluster node list.
10979
    iname = self.instance.name
10980
    if nodelist:
10981
      feedback_fn("Removing old exports for instance %s" % iname)
10982
      exportlist = self.rpc.call_export_list(nodelist)
10983
      for node in exportlist:
10984
        if exportlist[node].fail_msg:
10985
          continue
10986
        if iname in exportlist[node].payload:
10987
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10988
          if msg:
10989
            self.LogWarning("Could not remove older export for instance %s"
10990
                            " on node %s: %s", iname, node, msg)
10991

    
10992
  def Exec(self, feedback_fn):
10993
    """Export an instance to an image in the cluster.
10994

10995
    """
10996
    assert self.op.mode in constants.EXPORT_MODES
10997

    
10998
    instance = self.instance
10999
    src_node = instance.primary_node
11000

    
11001
    if self.op.shutdown:
11002
      # shutdown the instance, but not the disks
11003
      feedback_fn("Shutting down instance %s" % instance.name)
11004
      result = self.rpc.call_instance_shutdown(src_node, instance,
11005
                                               self.op.shutdown_timeout)
11006
      # TODO: Maybe ignore failures if ignore_remove_failures is set
11007
      result.Raise("Could not shutdown instance %s on"
11008
                   " node %s" % (instance.name, src_node))
11009

    
11010
    # set the disks ID correctly since call_instance_start needs the
11011
    # correct drbd minor to create the symlinks
11012
    for disk in instance.disks:
11013
      self.cfg.SetDiskID(disk, src_node)
11014

    
11015
    activate_disks = (not instance.admin_up)
11016

    
11017
    if activate_disks:
11018
      # Activate the instance disks if we'exporting a stopped instance
11019
      feedback_fn("Activating disks for %s" % instance.name)
11020
      _StartInstanceDisks(self, instance, None)
11021

    
11022
    try:
11023
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
11024
                                                     instance)
11025

    
11026
      helper.CreateSnapshots()
11027
      try:
11028
        if (self.op.shutdown and instance.admin_up and
11029
            not self.op.remove_instance):
11030
          assert not activate_disks
11031
          feedback_fn("Starting instance %s" % instance.name)
11032
          result = self.rpc.call_instance_start(src_node, instance, None, None)
11033
          msg = result.fail_msg
11034
          if msg:
11035
            feedback_fn("Failed to start instance: %s" % msg)
11036
            _ShutdownInstanceDisks(self, instance)
11037
            raise errors.OpExecError("Could not start instance: %s" % msg)
11038

    
11039
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
11040
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
11041
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11042
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
11043
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
11044

    
11045
          (key_name, _, _) = self.x509_key_name
11046

    
11047
          dest_ca_pem = \
11048
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
11049
                                            self.dest_x509_ca)
11050

    
11051
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
11052
                                                     key_name, dest_ca_pem,
11053
                                                     timeouts)
11054
      finally:
11055
        helper.Cleanup()
11056

    
11057
      # Check for backwards compatibility
11058
      assert len(dresults) == len(instance.disks)
11059
      assert compat.all(isinstance(i, bool) for i in dresults), \
11060
             "Not all results are boolean: %r" % dresults
11061

    
11062
    finally:
11063
      if activate_disks:
11064
        feedback_fn("Deactivating disks for %s" % instance.name)
11065
        _ShutdownInstanceDisks(self, instance)
11066

    
11067
    if not (compat.all(dresults) and fin_resu):
11068
      failures = []
11069
      if not fin_resu:
11070
        failures.append("export finalization")
11071
      if not compat.all(dresults):
11072
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
11073
                               if not dsk)
11074
        failures.append("disk export: disk(s) %s" % fdsk)
11075

    
11076
      raise errors.OpExecError("Export failed, errors in %s" %
11077
                               utils.CommaJoin(failures))
11078

    
11079
    # At this point, the export was successful, we can cleanup/finish
11080

    
11081
    # Remove instance if requested
11082
    if self.op.remove_instance:
11083
      feedback_fn("Removing instance %s" % instance.name)
11084
      _RemoveInstance(self, feedback_fn, instance,
11085
                      self.op.ignore_remove_failures)
11086

    
11087
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11088
      self._CleanupExports(feedback_fn)
11089

    
11090
    return fin_resu, dresults
11091

    
11092

    
11093
class LUBackupRemove(NoHooksLU):
11094
  """Remove exports related to the named instance.
11095

11096
  """
11097
  REQ_BGL = False
11098

    
11099
  def ExpandNames(self):
11100
    self.needed_locks = {}
11101
    # We need all nodes to be locked in order for RemoveExport to work, but we
11102
    # don't need to lock the instance itself, as nothing will happen to it (and
11103
    # we can remove exports also for a removed instance)
11104
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11105

    
11106
  def Exec(self, feedback_fn):
11107
    """Remove any export.
11108

11109
    """
11110
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11111
    # If the instance was not found we'll try with the name that was passed in.
11112
    # This will only work if it was an FQDN, though.
11113
    fqdn_warn = False
11114
    if not instance_name:
11115
      fqdn_warn = True
11116
      instance_name = self.op.instance_name
11117

    
11118
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
11119
    exportlist = self.rpc.call_export_list(locked_nodes)
11120
    found = False
11121
    for node in exportlist:
11122
      msg = exportlist[node].fail_msg
11123
      if msg:
11124
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11125
        continue
11126
      if instance_name in exportlist[node].payload:
11127
        found = True
11128
        result = self.rpc.call_export_remove(node, instance_name)
11129
        msg = result.fail_msg
11130
        if msg:
11131
          logging.error("Could not remove export for instance %s"
11132
                        " on node %s: %s", instance_name, node, msg)
11133

    
11134
    if fqdn_warn and not found:
11135
      feedback_fn("Export not found. If trying to remove an export belonging"
11136
                  " to a deleted instance please use its Fully Qualified"
11137
                  " Domain Name.")
11138

    
11139

    
11140
class LUGroupAdd(LogicalUnit):
11141
  """Logical unit for creating node groups.
11142

11143
  """
11144
  HPATH = "group-add"
11145
  HTYPE = constants.HTYPE_GROUP
11146
  REQ_BGL = False
11147

    
11148
  def ExpandNames(self):
11149
    # We need the new group's UUID here so that we can create and acquire the
11150
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11151
    # that it should not check whether the UUID exists in the configuration.
11152
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11153
    self.needed_locks = {}
11154
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11155

    
11156
  def CheckPrereq(self):
11157
    """Check prerequisites.
11158

11159
    This checks that the given group name is not an existing node group
11160
    already.
11161

11162
    """
11163
    try:
11164
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11165
    except errors.OpPrereqError:
11166
      pass
11167
    else:
11168
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11169
                                 " node group (UUID: %s)" %
11170
                                 (self.op.group_name, existing_uuid),
11171
                                 errors.ECODE_EXISTS)
11172

    
11173
    if self.op.ndparams:
11174
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11175

    
11176
  def BuildHooksEnv(self):
11177
    """Build hooks env.
11178

11179
    """
11180
    return {
11181
      "GROUP_NAME": self.op.group_name,
11182
      }
11183

    
11184
  def BuildHooksNodes(self):
11185
    """Build hooks nodes.
11186

11187
    """
11188
    mn = self.cfg.GetMasterNode()
11189
    return ([mn], [mn])
11190

    
11191
  def Exec(self, feedback_fn):
11192
    """Add the node group to the cluster.
11193

11194
    """
11195
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11196
                                  uuid=self.group_uuid,
11197
                                  alloc_policy=self.op.alloc_policy,
11198
                                  ndparams=self.op.ndparams)
11199

    
11200
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11201
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11202

    
11203

    
11204
class LUGroupAssignNodes(NoHooksLU):
11205
  """Logical unit for assigning nodes to groups.
11206

11207
  """
11208
  REQ_BGL = False
11209

    
11210
  def ExpandNames(self):
11211
    # These raise errors.OpPrereqError on their own:
11212
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11213
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11214

    
11215
    # We want to lock all the affected nodes and groups. We have readily
11216
    # available the list of nodes, and the *destination* group. To gather the
11217
    # list of "source" groups, we need to fetch node information later on.
11218
    self.needed_locks = {
11219
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11220
      locking.LEVEL_NODE: self.op.nodes,
11221
      }
11222

    
11223
  def DeclareLocks(self, level):
11224
    if level == locking.LEVEL_NODEGROUP:
11225
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11226

    
11227
      # Try to get all affected nodes' groups without having the group or node
11228
      # lock yet. Needs verification later in the code flow.
11229
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11230

    
11231
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11232

    
11233
  def CheckPrereq(self):
11234
    """Check prerequisites.
11235

11236
    """
11237
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11238
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11239
            frozenset(self.op.nodes))
11240

    
11241
    expected_locks = (set([self.group_uuid]) |
11242
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11243
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11244
    if actual_locks != expected_locks:
11245
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11246
                               " current groups are '%s', used to be '%s'" %
11247
                               (utils.CommaJoin(expected_locks),
11248
                                utils.CommaJoin(actual_locks)))
11249

    
11250
    self.node_data = self.cfg.GetAllNodesInfo()
11251
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11252
    instance_data = self.cfg.GetAllInstancesInfo()
11253

    
11254
    if self.group is None:
11255
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11256
                               (self.op.group_name, self.group_uuid))
11257

    
11258
    (new_splits, previous_splits) = \
11259
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11260
                                             for node in self.op.nodes],
11261
                                            self.node_data, instance_data)
11262

    
11263
    if new_splits:
11264
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11265

    
11266
      if not self.op.force:
11267
        raise errors.OpExecError("The following instances get split by this"
11268
                                 " change and --force was not given: %s" %
11269
                                 fmt_new_splits)
11270
      else:
11271
        self.LogWarning("This operation will split the following instances: %s",
11272
                        fmt_new_splits)
11273

    
11274
        if previous_splits:
11275
          self.LogWarning("In addition, these already-split instances continue"
11276
                          " to be split across groups: %s",
11277
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11278

    
11279
  def Exec(self, feedback_fn):
11280
    """Assign nodes to a new group.
11281

11282
    """
11283
    for node in self.op.nodes:
11284
      self.node_data[node].group = self.group_uuid
11285

    
11286
    # FIXME: Depends on side-effects of modifying the result of
11287
    # C{cfg.GetAllNodesInfo}
11288

    
11289
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11290

    
11291
  @staticmethod
11292
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11293
    """Check for split instances after a node assignment.
11294

11295
    This method considers a series of node assignments as an atomic operation,
11296
    and returns information about split instances after applying the set of
11297
    changes.
11298

11299
    In particular, it returns information about newly split instances, and
11300
    instances that were already split, and remain so after the change.
11301

11302
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11303
    considered.
11304

11305
    @type changes: list of (node_name, new_group_uuid) pairs.
11306
    @param changes: list of node assignments to consider.
11307
    @param node_data: a dict with data for all nodes
11308
    @param instance_data: a dict with all instances to consider
11309
    @rtype: a two-tuple
11310
    @return: a list of instances that were previously okay and result split as a
11311
      consequence of this change, and a list of instances that were previously
11312
      split and this change does not fix.
11313

11314
    """
11315
    changed_nodes = dict((node, group) for node, group in changes
11316
                         if node_data[node].group != group)
11317

    
11318
    all_split_instances = set()
11319
    previously_split_instances = set()
11320

    
11321
    def InstanceNodes(instance):
11322
      return [instance.primary_node] + list(instance.secondary_nodes)
11323

    
11324
    for inst in instance_data.values():
11325
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11326
        continue
11327

    
11328
      instance_nodes = InstanceNodes(inst)
11329

    
11330
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11331
        previously_split_instances.add(inst.name)
11332

    
11333
      if len(set(changed_nodes.get(node, node_data[node].group)
11334
                 for node in instance_nodes)) > 1:
11335
        all_split_instances.add(inst.name)
11336

    
11337
    return (list(all_split_instances - previously_split_instances),
11338
            list(previously_split_instances & all_split_instances))
11339

    
11340

    
11341
class _GroupQuery(_QueryBase):
11342
  FIELDS = query.GROUP_FIELDS
11343

    
11344
  def ExpandNames(self, lu):
11345
    lu.needed_locks = {}
11346

    
11347
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11348
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11349

    
11350
    if not self.names:
11351
      self.wanted = [name_to_uuid[name]
11352
                     for name in utils.NiceSort(name_to_uuid.keys())]
11353
    else:
11354
      # Accept names to be either names or UUIDs.
11355
      missing = []
11356
      self.wanted = []
11357
      all_uuid = frozenset(self._all_groups.keys())
11358

    
11359
      for name in self.names:
11360
        if name in all_uuid:
11361
          self.wanted.append(name)
11362
        elif name in name_to_uuid:
11363
          self.wanted.append(name_to_uuid[name])
11364
        else:
11365
          missing.append(name)
11366

    
11367
      if missing:
11368
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11369
                                   utils.CommaJoin(missing),
11370
                                   errors.ECODE_NOENT)
11371

    
11372
  def DeclareLocks(self, lu, level):
11373
    pass
11374

    
11375
  def _GetQueryData(self, lu):
11376
    """Computes the list of node groups and their attributes.
11377

11378
    """
11379
    do_nodes = query.GQ_NODE in self.requested_data
11380
    do_instances = query.GQ_INST in self.requested_data
11381

    
11382
    group_to_nodes = None
11383
    group_to_instances = None
11384

    
11385
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11386
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11387
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11388
    # instance->node. Hence, we will need to process nodes even if we only need
11389
    # instance information.
11390
    if do_nodes or do_instances:
11391
      all_nodes = lu.cfg.GetAllNodesInfo()
11392
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11393
      node_to_group = {}
11394

    
11395
      for node in all_nodes.values():
11396
        if node.group in group_to_nodes:
11397
          group_to_nodes[node.group].append(node.name)
11398
          node_to_group[node.name] = node.group
11399

    
11400
      if do_instances:
11401
        all_instances = lu.cfg.GetAllInstancesInfo()
11402
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11403

    
11404
        for instance in all_instances.values():
11405
          node = instance.primary_node
11406
          if node in node_to_group:
11407
            group_to_instances[node_to_group[node]].append(instance.name)
11408

    
11409
        if not do_nodes:
11410
          # Do not pass on node information if it was not requested.
11411
          group_to_nodes = None
11412

    
11413
    return query.GroupQueryData([self._all_groups[uuid]
11414
                                 for uuid in self.wanted],
11415
                                group_to_nodes, group_to_instances)
11416

    
11417

    
11418
class LUGroupQuery(NoHooksLU):
11419
  """Logical unit for querying node groups.
11420

11421
  """
11422
  REQ_BGL = False
11423

    
11424
  def CheckArguments(self):
11425
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11426
                          self.op.output_fields, False)
11427

    
11428
  def ExpandNames(self):
11429
    self.gq.ExpandNames(self)
11430

    
11431
  def Exec(self, feedback_fn):
11432
    return self.gq.OldStyleQuery(self)
11433

    
11434

    
11435
class LUGroupSetParams(LogicalUnit):
11436
  """Modifies the parameters of a node group.
11437

11438
  """
11439
  HPATH = "group-modify"
11440
  HTYPE = constants.HTYPE_GROUP
11441
  REQ_BGL = False
11442

    
11443
  def CheckArguments(self):
11444
    all_changes = [
11445
      self.op.ndparams,
11446
      self.op.alloc_policy,
11447
      ]
11448

    
11449
    if all_changes.count(None) == len(all_changes):
11450
      raise errors.OpPrereqError("Please pass at least one modification",
11451
                                 errors.ECODE_INVAL)
11452

    
11453
  def ExpandNames(self):
11454
    # This raises errors.OpPrereqError on its own:
11455
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11456

    
11457
    self.needed_locks = {
11458
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11459
      }
11460

    
11461
  def CheckPrereq(self):
11462
    """Check prerequisites.
11463

11464
    """
11465
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11466

    
11467
    if self.group is None:
11468
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11469
                               (self.op.group_name, self.group_uuid))
11470

    
11471
    if self.op.ndparams:
11472
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11473
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11474
      self.new_ndparams = new_ndparams
11475

    
11476
  def BuildHooksEnv(self):
11477
    """Build hooks env.
11478

11479
    """
11480
    return {
11481
      "GROUP_NAME": self.op.group_name,
11482
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11483
      }
11484

    
11485
  def BuildHooksNodes(self):
11486
    """Build hooks nodes.
11487

11488
    """
11489
    mn = self.cfg.GetMasterNode()
11490
    return ([mn], [mn])
11491

    
11492
  def Exec(self, feedback_fn):
11493
    """Modifies the node group.
11494

11495
    """
11496
    result = []
11497

    
11498
    if self.op.ndparams:
11499
      self.group.ndparams = self.new_ndparams
11500
      result.append(("ndparams", str(self.group.ndparams)))
11501

    
11502
    if self.op.alloc_policy:
11503
      self.group.alloc_policy = self.op.alloc_policy
11504

    
11505
    self.cfg.Update(self.group, feedback_fn)
11506
    return result
11507

    
11508

    
11509

    
11510
class LUGroupRemove(LogicalUnit):
11511
  HPATH = "group-remove"
11512
  HTYPE = constants.HTYPE_GROUP
11513
  REQ_BGL = False
11514

    
11515
  def ExpandNames(self):
11516
    # This will raises errors.OpPrereqError on its own:
11517
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11518
    self.needed_locks = {
11519
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11520
      }
11521

    
11522
  def CheckPrereq(self):
11523
    """Check prerequisites.
11524

11525
    This checks that the given group name exists as a node group, that is
11526
    empty (i.e., contains no nodes), and that is not the last group of the
11527
    cluster.
11528

11529
    """
11530
    # Verify that the group is empty.
11531
    group_nodes = [node.name
11532
                   for node in self.cfg.GetAllNodesInfo().values()
11533
                   if node.group == self.group_uuid]
11534

    
11535
    if group_nodes:
11536
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11537
                                 " nodes: %s" %
11538
                                 (self.op.group_name,
11539
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11540
                                 errors.ECODE_STATE)
11541

    
11542
    # Verify the cluster would not be left group-less.
11543
    if len(self.cfg.GetNodeGroupList()) == 1:
11544
      raise errors.OpPrereqError("Group '%s' is the only group,"
11545
                                 " cannot be removed" %
11546
                                 self.op.group_name,
11547
                                 errors.ECODE_STATE)
11548

    
11549
  def BuildHooksEnv(self):
11550
    """Build hooks env.
11551

11552
    """
11553
    return {
11554
      "GROUP_NAME": self.op.group_name,
11555
      }
11556

    
11557
  def BuildHooksNodes(self):
11558
    """Build hooks nodes.
11559

11560
    """
11561
    mn = self.cfg.GetMasterNode()
11562
    return ([mn], [mn])
11563

    
11564
  def Exec(self, feedback_fn):
11565
    """Remove the node group.
11566

11567
    """
11568
    try:
11569
      self.cfg.RemoveNodeGroup(self.group_uuid)
11570
    except errors.ConfigurationError:
11571
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11572
                               (self.op.group_name, self.group_uuid))
11573

    
11574
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11575

    
11576

    
11577
class LUGroupRename(LogicalUnit):
11578
  HPATH = "group-rename"
11579
  HTYPE = constants.HTYPE_GROUP
11580
  REQ_BGL = False
11581

    
11582
  def ExpandNames(self):
11583
    # This raises errors.OpPrereqError on its own:
11584
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11585

    
11586
    self.needed_locks = {
11587
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11588
      }
11589

    
11590
  def CheckPrereq(self):
11591
    """Check prerequisites.
11592

11593
    Ensures requested new name is not yet used.
11594

11595
    """
11596
    try:
11597
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11598
    except errors.OpPrereqError:
11599
      pass
11600
    else:
11601
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11602
                                 " node group (UUID: %s)" %
11603
                                 (self.op.new_name, new_name_uuid),
11604
                                 errors.ECODE_EXISTS)
11605

    
11606
  def BuildHooksEnv(self):
11607
    """Build hooks env.
11608

11609
    """
11610
    return {
11611
      "OLD_NAME": self.op.group_name,
11612
      "NEW_NAME": self.op.new_name,
11613
      }
11614

    
11615
  def BuildHooksNodes(self):
11616
    """Build hooks nodes.
11617

11618
    """
11619
    mn = self.cfg.GetMasterNode()
11620

    
11621
    all_nodes = self.cfg.GetAllNodesInfo()
11622
    all_nodes.pop(mn, None)
11623

    
11624
    run_nodes = [mn]
11625
    run_nodes.extend(node.name for node in all_nodes.values()
11626
                     if node.group == self.group_uuid)
11627

    
11628
    return (run_nodes, run_nodes)
11629

    
11630
  def Exec(self, feedback_fn):
11631
    """Rename the node group.
11632

11633
    """
11634
    group = self.cfg.GetNodeGroup(self.group_uuid)
11635

    
11636
    if group is None:
11637
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11638
                               (self.op.group_name, self.group_uuid))
11639

    
11640
    group.name = self.op.new_name
11641
    self.cfg.Update(group, feedback_fn)
11642

    
11643
    return self.op.new_name
11644

    
11645

    
11646
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11647
  """Generic tags LU.
11648

11649
  This is an abstract class which is the parent of all the other tags LUs.
11650

11651
  """
11652
  def ExpandNames(self):
11653
    self.group_uuid = None
11654
    self.needed_locks = {}
11655
    if self.op.kind == constants.TAG_NODE:
11656
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11657
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11658
    elif self.op.kind == constants.TAG_INSTANCE:
11659
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11660
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11661
    elif self.op.kind == constants.TAG_NODEGROUP:
11662
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
11663

    
11664
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11665
    # not possible to acquire the BGL based on opcode parameters)
11666

    
11667
  def CheckPrereq(self):
11668
    """Check prerequisites.
11669

11670
    """
11671
    if self.op.kind == constants.TAG_CLUSTER:
11672
      self.target = self.cfg.GetClusterInfo()
11673
    elif self.op.kind == constants.TAG_NODE:
11674
      self.target = self.cfg.GetNodeInfo(self.op.name)
11675
    elif self.op.kind == constants.TAG_INSTANCE:
11676
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11677
    elif self.op.kind == constants.TAG_NODEGROUP:
11678
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
11679
    else:
11680
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11681
                                 str(self.op.kind), errors.ECODE_INVAL)
11682

    
11683

    
11684
class LUTagsGet(TagsLU):
11685
  """Returns the tags of a given object.
11686

11687
  """
11688
  REQ_BGL = False
11689

    
11690
  def ExpandNames(self):
11691
    TagsLU.ExpandNames(self)
11692

    
11693
    # Share locks as this is only a read operation
11694
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11695

    
11696
  def Exec(self, feedback_fn):
11697
    """Returns the tag list.
11698

11699
    """
11700
    return list(self.target.GetTags())
11701

    
11702

    
11703
class LUTagsSearch(NoHooksLU):
11704
  """Searches the tags for a given pattern.
11705

11706
  """
11707
  REQ_BGL = False
11708

    
11709
  def ExpandNames(self):
11710
    self.needed_locks = {}
11711

    
11712
  def CheckPrereq(self):
11713
    """Check prerequisites.
11714

11715
    This checks the pattern passed for validity by compiling it.
11716

11717
    """
11718
    try:
11719
      self.re = re.compile(self.op.pattern)
11720
    except re.error, err:
11721
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11722
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11723

    
11724
  def Exec(self, feedback_fn):
11725
    """Returns the tag list.
11726

11727
    """
11728
    cfg = self.cfg
11729
    tgts = [("/cluster", cfg.GetClusterInfo())]
11730
    ilist = cfg.GetAllInstancesInfo().values()
11731
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11732
    nlist = cfg.GetAllNodesInfo().values()
11733
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11734
    tgts.extend(("/nodegroup/%s" % n.name, n)
11735
                for n in cfg.GetAllNodeGroupsInfo().values())
11736
    results = []
11737
    for path, target in tgts:
11738
      for tag in target.GetTags():
11739
        if self.re.search(tag):
11740
          results.append((path, tag))
11741
    return results
11742

    
11743

    
11744
class LUTagsSet(TagsLU):
11745
  """Sets a tag on a given object.
11746

11747
  """
11748
  REQ_BGL = False
11749

    
11750
  def CheckPrereq(self):
11751
    """Check prerequisites.
11752

11753
    This checks the type and length of the tag name and value.
11754

11755
    """
11756
    TagsLU.CheckPrereq(self)
11757
    for tag in self.op.tags:
11758
      objects.TaggableObject.ValidateTag(tag)
11759

    
11760
  def Exec(self, feedback_fn):
11761
    """Sets the tag.
11762

11763
    """
11764
    try:
11765
      for tag in self.op.tags:
11766
        self.target.AddTag(tag)
11767
    except errors.TagError, err:
11768
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11769
    self.cfg.Update(self.target, feedback_fn)
11770

    
11771

    
11772
class LUTagsDel(TagsLU):
11773
  """Delete a list of tags from a given object.
11774

11775
  """
11776
  REQ_BGL = False
11777

    
11778
  def CheckPrereq(self):
11779
    """Check prerequisites.
11780

11781
    This checks that we have the given tag.
11782

11783
    """
11784
    TagsLU.CheckPrereq(self)
11785
    for tag in self.op.tags:
11786
      objects.TaggableObject.ValidateTag(tag)
11787
    del_tags = frozenset(self.op.tags)
11788
    cur_tags = self.target.GetTags()
11789

    
11790
    diff_tags = del_tags - cur_tags
11791
    if diff_tags:
11792
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11793
      raise errors.OpPrereqError("Tag(s) %s not found" %
11794
                                 (utils.CommaJoin(diff_names), ),
11795
                                 errors.ECODE_NOENT)
11796

    
11797
  def Exec(self, feedback_fn):
11798
    """Remove the tag from the object.
11799

11800
    """
11801
    for tag in self.op.tags:
11802
      self.target.RemoveTag(tag)
11803
    self.cfg.Update(self.target, feedback_fn)
11804

    
11805

    
11806
class LUTestDelay(NoHooksLU):
11807
  """Sleep for a specified amount of time.
11808

11809
  This LU sleeps on the master and/or nodes for a specified amount of
11810
  time.
11811

11812
  """
11813
  REQ_BGL = False
11814

    
11815
  def ExpandNames(self):
11816
    """Expand names and set required locks.
11817

11818
    This expands the node list, if any.
11819

11820
    """
11821
    self.needed_locks = {}
11822
    if self.op.on_nodes:
11823
      # _GetWantedNodes can be used here, but is not always appropriate to use
11824
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11825
      # more information.
11826
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11827
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11828

    
11829
  def _TestDelay(self):
11830
    """Do the actual sleep.
11831

11832
    """
11833
    if self.op.on_master:
11834
      if not utils.TestDelay(self.op.duration):
11835
        raise errors.OpExecError("Error during master delay test")
11836
    if self.op.on_nodes:
11837
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11838
      for node, node_result in result.items():
11839
        node_result.Raise("Failure during rpc call to node %s" % node)
11840

    
11841
  def Exec(self, feedback_fn):
11842
    """Execute the test delay opcode, with the wanted repetitions.
11843

11844
    """
11845
    if self.op.repeat == 0:
11846
      self._TestDelay()
11847
    else:
11848
      top_value = self.op.repeat - 1
11849
      for i in range(self.op.repeat):
11850
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11851
        self._TestDelay()
11852

    
11853

    
11854
class LUTestJqueue(NoHooksLU):
11855
  """Utility LU to test some aspects of the job queue.
11856

11857
  """
11858
  REQ_BGL = False
11859

    
11860
  # Must be lower than default timeout for WaitForJobChange to see whether it
11861
  # notices changed jobs
11862
  _CLIENT_CONNECT_TIMEOUT = 20.0
11863
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11864

    
11865
  @classmethod
11866
  def _NotifyUsingSocket(cls, cb, errcls):
11867
    """Opens a Unix socket and waits for another program to connect.
11868

11869
    @type cb: callable
11870
    @param cb: Callback to send socket name to client
11871
    @type errcls: class
11872
    @param errcls: Exception class to use for errors
11873

11874
    """
11875
    # Using a temporary directory as there's no easy way to create temporary
11876
    # sockets without writing a custom loop around tempfile.mktemp and
11877
    # socket.bind
11878
    tmpdir = tempfile.mkdtemp()
11879
    try:
11880
      tmpsock = utils.PathJoin(tmpdir, "sock")
11881

    
11882
      logging.debug("Creating temporary socket at %s", tmpsock)
11883
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11884
      try:
11885
        sock.bind(tmpsock)
11886
        sock.listen(1)
11887

    
11888
        # Send details to client
11889
        cb(tmpsock)
11890

    
11891
        # Wait for client to connect before continuing
11892
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11893
        try:
11894
          (conn, _) = sock.accept()
11895
        except socket.error, err:
11896
          raise errcls("Client didn't connect in time (%s)" % err)
11897
      finally:
11898
        sock.close()
11899
    finally:
11900
      # Remove as soon as client is connected
11901
      shutil.rmtree(tmpdir)
11902

    
11903
    # Wait for client to close
11904
    try:
11905
      try:
11906
        # pylint: disable-msg=E1101
11907
        # Instance of '_socketobject' has no ... member
11908
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11909
        conn.recv(1)
11910
      except socket.error, err:
11911
        raise errcls("Client failed to confirm notification (%s)" % err)
11912
    finally:
11913
      conn.close()
11914

    
11915
  def _SendNotification(self, test, arg, sockname):
11916
    """Sends a notification to the client.
11917

11918
    @type test: string
11919
    @param test: Test name
11920
    @param arg: Test argument (depends on test)
11921
    @type sockname: string
11922
    @param sockname: Socket path
11923

11924
    """
11925
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11926

    
11927
  def _Notify(self, prereq, test, arg):
11928
    """Notifies the client of a test.
11929

11930
    @type prereq: bool
11931
    @param prereq: Whether this is a prereq-phase test
11932
    @type test: string
11933
    @param test: Test name
11934
    @param arg: Test argument (depends on test)
11935

11936
    """
11937
    if prereq:
11938
      errcls = errors.OpPrereqError
11939
    else:
11940
      errcls = errors.OpExecError
11941

    
11942
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11943
                                                  test, arg),
11944
                                   errcls)
11945

    
11946
  def CheckArguments(self):
11947
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11948
    self.expandnames_calls = 0
11949

    
11950
  def ExpandNames(self):
11951
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11952
    if checkargs_calls < 1:
11953
      raise errors.ProgrammerError("CheckArguments was not called")
11954

    
11955
    self.expandnames_calls += 1
11956

    
11957
    if self.op.notify_waitlock:
11958
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11959

    
11960
    self.LogInfo("Expanding names")
11961

    
11962
    # Get lock on master node (just to get a lock, not for a particular reason)
11963
    self.needed_locks = {
11964
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11965
      }
11966

    
11967
  def Exec(self, feedback_fn):
11968
    if self.expandnames_calls < 1:
11969
      raise errors.ProgrammerError("ExpandNames was not called")
11970

    
11971
    if self.op.notify_exec:
11972
      self._Notify(False, constants.JQT_EXEC, None)
11973

    
11974
    self.LogInfo("Executing")
11975

    
11976
    if self.op.log_messages:
11977
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11978
      for idx, msg in enumerate(self.op.log_messages):
11979
        self.LogInfo("Sending log message %s", idx + 1)
11980
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11981
        # Report how many test messages have been sent
11982
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11983

    
11984
    if self.op.fail:
11985
      raise errors.OpExecError("Opcode failure was requested")
11986

    
11987
    return True
11988

    
11989

    
11990
class IAllocator(object):
11991
  """IAllocator framework.
11992

11993
  An IAllocator instance has three sets of attributes:
11994
    - cfg that is needed to query the cluster
11995
    - input data (all members of the _KEYS class attribute are required)
11996
    - four buffer attributes (in|out_data|text), that represent the
11997
      input (to the external script) in text and data structure format,
11998
      and the output from it, again in two formats
11999
    - the result variables from the script (success, info, nodes) for
12000
      easy usage
12001

12002
  """
12003
  # pylint: disable-msg=R0902
12004
  # lots of instance attributes
12005

    
12006
  def __init__(self, cfg, rpc, mode, **kwargs):
12007
    self.cfg = cfg
12008
    self.rpc = rpc
12009
    # init buffer variables
12010
    self.in_text = self.out_text = self.in_data = self.out_data = None
12011
    # init all input fields so that pylint is happy
12012
    self.mode = mode
12013
    self.mem_size = self.disks = self.disk_template = None
12014
    self.os = self.tags = self.nics = self.vcpus = None
12015
    self.hypervisor = None
12016
    self.relocate_from = None
12017
    self.name = None
12018
    self.evac_nodes = None
12019
    self.instances = None
12020
    self.reloc_mode = None
12021
    self.target_groups = None
12022
    # computed fields
12023
    self.required_nodes = None
12024
    # init result fields
12025
    self.success = self.info = self.result = None
12026

    
12027
    try:
12028
      (fn, keyset, self._result_check) = self._MODE_DATA[self.mode]
12029
    except KeyError:
12030
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
12031
                                   " IAllocator" % self.mode)
12032

    
12033
    for key in kwargs:
12034
      if key not in keyset:
12035
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
12036
                                     " IAllocator" % key)
12037
      setattr(self, key, kwargs[key])
12038

    
12039
    for key in keyset:
12040
      if key not in kwargs:
12041
        raise errors.ProgrammerError("Missing input parameter '%s' to"
12042
                                     " IAllocator" % key)
12043
    self._BuildInputData(compat.partial(fn, self))
12044

    
12045
  def _ComputeClusterData(self):
12046
    """Compute the generic allocator input data.
12047

12048
    This is the data that is independent of the actual operation.
12049

12050
    """
12051
    cfg = self.cfg
12052
    cluster_info = cfg.GetClusterInfo()
12053
    # cluster data
12054
    data = {
12055
      "version": constants.IALLOCATOR_VERSION,
12056
      "cluster_name": cfg.GetClusterName(),
12057
      "cluster_tags": list(cluster_info.GetTags()),
12058
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
12059
      # we don't have job IDs
12060
      }
12061
    ninfo = cfg.GetAllNodesInfo()
12062
    iinfo = cfg.GetAllInstancesInfo().values()
12063
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
12064

    
12065
    # node data
12066
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
12067

    
12068
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
12069
      hypervisor_name = self.hypervisor
12070
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
12071
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
12072
    elif self.mode in (constants.IALLOCATOR_MODE_MEVAC,
12073
                       constants.IALLOCATOR_MODE_MRELOC):
12074
      hypervisor_name = cluster_info.enabled_hypervisors[0]
12075

    
12076
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
12077
                                        hypervisor_name)
12078
    node_iinfo = \
12079
      self.rpc.call_all_instances_info(node_list,
12080
                                       cluster_info.enabled_hypervisors)
12081

    
12082
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
12083

    
12084
    config_ndata = self._ComputeBasicNodeData(ninfo)
12085
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12086
                                                 i_list, config_ndata)
12087
    assert len(data["nodes"]) == len(ninfo), \
12088
        "Incomplete node data computed"
12089

    
12090
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12091

    
12092
    self.in_data = data
12093

    
12094
  @staticmethod
12095
  def _ComputeNodeGroupData(cfg):
12096
    """Compute node groups data.
12097

12098
    """
12099
    ng = dict((guuid, {
12100
      "name": gdata.name,
12101
      "alloc_policy": gdata.alloc_policy,
12102
      })
12103
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12104

    
12105
    return ng
12106

    
12107
  @staticmethod
12108
  def _ComputeBasicNodeData(node_cfg):
12109
    """Compute global node data.
12110

12111
    @rtype: dict
12112
    @returns: a dict of name: (node dict, node config)
12113

12114
    """
12115
    # fill in static (config-based) values
12116
    node_results = dict((ninfo.name, {
12117
      "tags": list(ninfo.GetTags()),
12118
      "primary_ip": ninfo.primary_ip,
12119
      "secondary_ip": ninfo.secondary_ip,
12120
      "offline": ninfo.offline,
12121
      "drained": ninfo.drained,
12122
      "master_candidate": ninfo.master_candidate,
12123
      "group": ninfo.group,
12124
      "master_capable": ninfo.master_capable,
12125
      "vm_capable": ninfo.vm_capable,
12126
      })
12127
      for ninfo in node_cfg.values())
12128

    
12129
    return node_results
12130

    
12131
  @staticmethod
12132
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
12133
                              node_results):
12134
    """Compute global node data.
12135

12136
    @param node_results: the basic node structures as filled from the config
12137

12138
    """
12139
    # make a copy of the current dict
12140
    node_results = dict(node_results)
12141
    for nname, nresult in node_data.items():
12142
      assert nname in node_results, "Missing basic data for node %s" % nname
12143
      ninfo = node_cfg[nname]
12144

    
12145
      if not (ninfo.offline or ninfo.drained):
12146
        nresult.Raise("Can't get data for node %s" % nname)
12147
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
12148
                                nname)
12149
        remote_info = nresult.payload
12150

    
12151
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
12152
                     'vg_size', 'vg_free', 'cpu_total']:
12153
          if attr not in remote_info:
12154
            raise errors.OpExecError("Node '%s' didn't return attribute"
12155
                                     " '%s'" % (nname, attr))
12156
          if not isinstance(remote_info[attr], int):
12157
            raise errors.OpExecError("Node '%s' returned invalid value"
12158
                                     " for '%s': %s" %
12159
                                     (nname, attr, remote_info[attr]))
12160
        # compute memory used by primary instances
12161
        i_p_mem = i_p_up_mem = 0
12162
        for iinfo, beinfo in i_list:
12163
          if iinfo.primary_node == nname:
12164
            i_p_mem += beinfo[constants.BE_MEMORY]
12165
            if iinfo.name not in node_iinfo[nname].payload:
12166
              i_used_mem = 0
12167
            else:
12168
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
12169
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
12170
            remote_info['memory_free'] -= max(0, i_mem_diff)
12171

    
12172
            if iinfo.admin_up:
12173
              i_p_up_mem += beinfo[constants.BE_MEMORY]
12174

    
12175
        # compute memory used by instances
12176
        pnr_dyn = {
12177
          "total_memory": remote_info['memory_total'],
12178
          "reserved_memory": remote_info['memory_dom0'],
12179
          "free_memory": remote_info['memory_free'],
12180
          "total_disk": remote_info['vg_size'],
12181
          "free_disk": remote_info['vg_free'],
12182
          "total_cpus": remote_info['cpu_total'],
12183
          "i_pri_memory": i_p_mem,
12184
          "i_pri_up_memory": i_p_up_mem,
12185
          }
12186
        pnr_dyn.update(node_results[nname])
12187
        node_results[nname] = pnr_dyn
12188

    
12189
    return node_results
12190

    
12191
  @staticmethod
12192
  def _ComputeInstanceData(cluster_info, i_list):
12193
    """Compute global instance data.
12194

12195
    """
12196
    instance_data = {}
12197
    for iinfo, beinfo in i_list:
12198
      nic_data = []
12199
      for nic in iinfo.nics:
12200
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
12201
        nic_dict = {
12202
          "mac": nic.mac,
12203
          "ip": nic.ip,
12204
          "mode": filled_params[constants.NIC_MODE],
12205
          "link": filled_params[constants.NIC_LINK],
12206
          }
12207
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
12208
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
12209
        nic_data.append(nic_dict)
12210
      pir = {
12211
        "tags": list(iinfo.GetTags()),
12212
        "admin_up": iinfo.admin_up,
12213
        "vcpus": beinfo[constants.BE_VCPUS],
12214
        "memory": beinfo[constants.BE_MEMORY],
12215
        "os": iinfo.os,
12216
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12217
        "nics": nic_data,
12218
        "disks": [{constants.IDISK_SIZE: dsk.size,
12219
                   constants.IDISK_MODE: dsk.mode}
12220
                  for dsk in iinfo.disks],
12221
        "disk_template": iinfo.disk_template,
12222
        "hypervisor": iinfo.hypervisor,
12223
        }
12224
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12225
                                                 pir["disks"])
12226
      instance_data[iinfo.name] = pir
12227

    
12228
    return instance_data
12229

    
12230
  def _AddNewInstance(self):
12231
    """Add new instance data to allocator structure.
12232

12233
    This in combination with _AllocatorGetClusterData will create the
12234
    correct structure needed as input for the allocator.
12235

12236
    The checks for the completeness of the opcode must have already been
12237
    done.
12238

12239
    """
12240
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12241

    
12242
    if self.disk_template in constants.DTS_INT_MIRROR:
12243
      self.required_nodes = 2
12244
    else:
12245
      self.required_nodes = 1
12246

    
12247
    request = {
12248
      "name": self.name,
12249
      "disk_template": self.disk_template,
12250
      "tags": self.tags,
12251
      "os": self.os,
12252
      "vcpus": self.vcpus,
12253
      "memory": self.mem_size,
12254
      "disks": self.disks,
12255
      "disk_space_total": disk_space,
12256
      "nics": self.nics,
12257
      "required_nodes": self.required_nodes,
12258
      }
12259

    
12260
    return request
12261

    
12262
  def _AddRelocateInstance(self):
12263
    """Add relocate instance data to allocator structure.
12264

12265
    This in combination with _IAllocatorGetClusterData will create the
12266
    correct structure needed as input for the allocator.
12267

12268
    The checks for the completeness of the opcode must have already been
12269
    done.
12270

12271
    """
12272
    instance = self.cfg.GetInstanceInfo(self.name)
12273
    if instance is None:
12274
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12275
                                   " IAllocator" % self.name)
12276

    
12277
    if instance.disk_template not in constants.DTS_MIRRORED:
12278
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12279
                                 errors.ECODE_INVAL)
12280

    
12281
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12282
        len(instance.secondary_nodes) != 1:
12283
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12284
                                 errors.ECODE_STATE)
12285

    
12286
    self.required_nodes = 1
12287
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12288
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12289

    
12290
    request = {
12291
      "name": self.name,
12292
      "disk_space_total": disk_space,
12293
      "required_nodes": self.required_nodes,
12294
      "relocate_from": self.relocate_from,
12295
      }
12296
    return request
12297

    
12298
  def _AddEvacuateNodes(self):
12299
    """Add evacuate nodes data to allocator structure.
12300

12301
    """
12302
    request = {
12303
      "evac_nodes": self.evac_nodes
12304
      }
12305
    return request
12306

    
12307
  def _AddMultiRelocate(self):
12308
    """Get data for multi-relocate requests.
12309

12310
    """
12311
    return {
12312
      "instances": self.instances,
12313
      "reloc_mode": self.reloc_mode,
12314
      "target_groups": self.target_groups,
12315
      }
12316

    
12317
  def _BuildInputData(self, fn):
12318
    """Build input data structures.
12319

12320
    """
12321
    self._ComputeClusterData()
12322

    
12323
    request = fn()
12324
    request["type"] = self.mode
12325
    self.in_data["request"] = request
12326

    
12327
    self.in_text = serializer.Dump(self.in_data)
12328

    
12329
  _MODE_DATA = {
12330
    constants.IALLOCATOR_MODE_ALLOC:
12331
      (_AddNewInstance,
12332
       ["name", "mem_size", "disks", "disk_template", "os", "tags", "nics",
12333
        "vcpus", "hypervisor"], ht.TList),
12334
    constants.IALLOCATOR_MODE_RELOC:
12335
      (_AddRelocateInstance, ["name", "relocate_from"], ht.TList),
12336
    constants.IALLOCATOR_MODE_MEVAC:
12337
      (_AddEvacuateNodes, ["evac_nodes"],
12338
       ht.TListOf(ht.TAnd(ht.TIsLength(2),
12339
                          ht.TListOf(ht.TString)))),
12340
    constants.IALLOCATOR_MODE_MRELOC:
12341
      (_AddMultiRelocate, ["instances", "reloc_mode", "target_groups"],
12342
       ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12343
         # pylint: disable-msg=E1101
12344
         # Class '...' has no 'OP_ID' member
12345
         "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12346
                              opcodes.OpInstanceMigrate.OP_ID,
12347
                              opcodes.OpInstanceReplaceDisks.OP_ID])
12348
         })))),
12349
    }
12350

    
12351
  def Run(self, name, validate=True, call_fn=None):
12352
    """Run an instance allocator and return the results.
12353

12354
    """
12355
    if call_fn is None:
12356
      call_fn = self.rpc.call_iallocator_runner
12357

    
12358
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12359
    result.Raise("Failure while running the iallocator script")
12360

    
12361
    self.out_text = result.payload
12362
    if validate:
12363
      self._ValidateResult()
12364

    
12365
  def _ValidateResult(self):
12366
    """Process the allocator results.
12367

12368
    This will process and if successful save the result in
12369
    self.out_data and the other parameters.
12370

12371
    """
12372
    try:
12373
      rdict = serializer.Load(self.out_text)
12374
    except Exception, err:
12375
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12376

    
12377
    if not isinstance(rdict, dict):
12378
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12379

    
12380
    # TODO: remove backwards compatiblity in later versions
12381
    if "nodes" in rdict and "result" not in rdict:
12382
      rdict["result"] = rdict["nodes"]
12383
      del rdict["nodes"]
12384

    
12385
    for key in "success", "info", "result":
12386
      if key not in rdict:
12387
        raise errors.OpExecError("Can't parse iallocator results:"
12388
                                 " missing key '%s'" % key)
12389
      setattr(self, key, rdict[key])
12390

    
12391
    if not self._result_check(self.result):
12392
      raise errors.OpExecError("Iallocator returned invalid result,"
12393
                               " expected %s, got %s" %
12394
                               (self._result_check, self.result),
12395
                               errors.ECODE_INVAL)
12396

    
12397
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12398
                     constants.IALLOCATOR_MODE_MEVAC):
12399
      node2group = dict((name, ndata["group"])
12400
                        for (name, ndata) in self.in_data["nodes"].items())
12401

    
12402
      fn = compat.partial(self._NodesToGroups, node2group,
12403
                          self.in_data["nodegroups"])
12404

    
12405
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12406
        assert self.relocate_from is not None
12407
        assert self.required_nodes == 1
12408

    
12409
        request_groups = fn(self.relocate_from)
12410
        result_groups = fn(rdict["result"])
12411

    
12412
        if result_groups != request_groups:
12413
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12414
                                   " differ from original groups (%s)" %
12415
                                   (utils.CommaJoin(result_groups),
12416
                                    utils.CommaJoin(request_groups)))
12417
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12418
        request_groups = fn(self.evac_nodes)
12419
        for (instance_name, secnode) in self.result:
12420
          result_groups = fn([secnode])
12421
          if result_groups != request_groups:
12422
            raise errors.OpExecError("Iallocator returned new secondary node"
12423
                                     " '%s' (group '%s') for instance '%s'"
12424
                                     " which is not in original group '%s'" %
12425
                                     (secnode, utils.CommaJoin(result_groups),
12426
                                      instance_name,
12427
                                      utils.CommaJoin(request_groups)))
12428
      else:
12429
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12430

    
12431
    self.out_data = rdict
12432

    
12433
  @staticmethod
12434
  def _NodesToGroups(node2group, groups, nodes):
12435
    """Returns a list of unique group names for a list of nodes.
12436

12437
    @type node2group: dict
12438
    @param node2group: Map from node name to group UUID
12439
    @type groups: dict
12440
    @param groups: Group information
12441
    @type nodes: list
12442
    @param nodes: Node names
12443

12444
    """
12445
    result = set()
12446

    
12447
    for node in nodes:
12448
      try:
12449
        group_uuid = node2group[node]
12450
      except KeyError:
12451
        # Ignore unknown node
12452
        pass
12453
      else:
12454
        try:
12455
          group = groups[group_uuid]
12456
        except KeyError:
12457
          # Can't find group, let's use UUID
12458
          group_name = group_uuid
12459
        else:
12460
          group_name = group["name"]
12461

    
12462
        result.add(group_name)
12463

    
12464
    return sorted(result)
12465

    
12466

    
12467
class LUTestAllocator(NoHooksLU):
12468
  """Run allocator tests.
12469

12470
  This LU runs the allocator tests
12471

12472
  """
12473
  def CheckPrereq(self):
12474
    """Check prerequisites.
12475

12476
    This checks the opcode parameters depending on the director and mode test.
12477

12478
    """
12479
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12480
      for attr in ["mem_size", "disks", "disk_template",
12481
                   "os", "tags", "nics", "vcpus"]:
12482
        if not hasattr(self.op, attr):
12483
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12484
                                     attr, errors.ECODE_INVAL)
12485
      iname = self.cfg.ExpandInstanceName(self.op.name)
12486
      if iname is not None:
12487
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12488
                                   iname, errors.ECODE_EXISTS)
12489
      if not isinstance(self.op.nics, list):
12490
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12491
                                   errors.ECODE_INVAL)
12492
      if not isinstance(self.op.disks, list):
12493
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12494
                                   errors.ECODE_INVAL)
12495
      for row in self.op.disks:
12496
        if (not isinstance(row, dict) or
12497
            "size" not in row or
12498
            not isinstance(row["size"], int) or
12499
            "mode" not in row or
12500
            row["mode"] not in ['r', 'w']):
12501
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12502
                                     " parameter", errors.ECODE_INVAL)
12503
      if self.op.hypervisor is None:
12504
        self.op.hypervisor = self.cfg.GetHypervisorType()
12505
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12506
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12507
      self.op.name = fname
12508
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12509
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12510
      if not hasattr(self.op, "evac_nodes"):
12511
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12512
                                   " opcode input", errors.ECODE_INVAL)
12513
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12514
      if self.op.instances:
12515
        self.op.instances = _GetWantedInstances(self, self.op.instances)
12516
      else:
12517
        raise errors.OpPrereqError("Missing instances to relocate",
12518
                                   errors.ECODE_INVAL)
12519
    else:
12520
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12521
                                 self.op.mode, errors.ECODE_INVAL)
12522

    
12523
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12524
      if self.op.allocator is None:
12525
        raise errors.OpPrereqError("Missing allocator name",
12526
                                   errors.ECODE_INVAL)
12527
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12528
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12529
                                 self.op.direction, errors.ECODE_INVAL)
12530

    
12531
  def Exec(self, feedback_fn):
12532
    """Run the allocator test.
12533

12534
    """
12535
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12536
      ial = IAllocator(self.cfg, self.rpc,
12537
                       mode=self.op.mode,
12538
                       name=self.op.name,
12539
                       mem_size=self.op.mem_size,
12540
                       disks=self.op.disks,
12541
                       disk_template=self.op.disk_template,
12542
                       os=self.op.os,
12543
                       tags=self.op.tags,
12544
                       nics=self.op.nics,
12545
                       vcpus=self.op.vcpus,
12546
                       hypervisor=self.op.hypervisor,
12547
                       )
12548
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12549
      ial = IAllocator(self.cfg, self.rpc,
12550
                       mode=self.op.mode,
12551
                       name=self.op.name,
12552
                       relocate_from=list(self.relocate_from),
12553
                       )
12554
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12555
      ial = IAllocator(self.cfg, self.rpc,
12556
                       mode=self.op.mode,
12557
                       evac_nodes=self.op.evac_nodes)
12558
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12559
      ial = IAllocator(self.cfg, self.rpc,
12560
                       mode=self.op.mode,
12561
                       instances=self.op.instances,
12562
                       reloc_mode=self.op.reloc_mode,
12563
                       target_groups=self.op.target_groups)
12564
    else:
12565
      raise errors.ProgrammerError("Uncatched mode %s in"
12566
                                   " LUTestAllocator.Exec", self.op.mode)
12567

    
12568
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
12569
      result = ial.in_text
12570
    else:
12571
      ial.Run(self.op.allocator, validate=False)
12572
      result = ial.out_text
12573
    return result
12574

    
12575

    
12576
#: Query type implementations
12577
_QUERY_IMPL = {
12578
  constants.QR_INSTANCE: _InstanceQuery,
12579
  constants.QR_NODE: _NodeQuery,
12580
  constants.QR_GROUP: _GroupQuery,
12581
  constants.QR_OS: _OsQuery,
12582
  }
12583

    
12584
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
12585

    
12586

    
12587
def _GetQueryImplementation(name):
12588
  """Returns the implemtnation for a query type.
12589

12590
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
12591

12592
  """
12593
  try:
12594
    return _QUERY_IMPL[name]
12595
  except KeyError:
12596
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
12597
                               errors.ECODE_INVAL)