Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ d748d9a7

History | View | Annotate | Download (445.1 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, tags):
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
  @type tags: list
897
  @param tags: list of instance tags as strings
898
  @rtype: dict
899
  @return: the hook environment for this instance
900

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

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

    
933
  env["INSTANCE_NIC_COUNT"] = nic_count
934

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

    
943
  env["INSTANCE_DISK_COUNT"] = disk_count
944

    
945
  if not tags:
946
    tags = []
947

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

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

    
954
  return env
955

    
956

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

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

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

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

    
980

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

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

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

    
1019

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

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

    
1035

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

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

    
1046

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

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

    
1060

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

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

    
1069

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

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

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

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

    
1089

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

    
1093

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

1097
  """
1098

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

    
1101

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

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

    
1109

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

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

    
1117

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

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

    
1127
  return []
1128

    
1129

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

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

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

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

    
1144
  return faulty
1145

    
1146

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

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

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

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

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

    
1178

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

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

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

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

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

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

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

1203
    """
1204
    return True
1205

    
1206

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

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

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

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

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

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

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

1231
    This checks whether the cluster is empty.
1232

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

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

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

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

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

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

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

    
1261
    return master
1262

    
1263

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

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

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

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

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

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

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

    
1296

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

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

1308
  """
1309
  hvp_data = []
1310

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

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

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

    
1326
  return hvp_data
1327

    
1328

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

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

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

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

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

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

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

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

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

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

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

    
1412

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

1416
  """
1417
  REQ_BGL = True
1418

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

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

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

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

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

    
1448
    feedback_fn("* Verifying cluster config")
1449

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

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

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

    
1459
    feedback_fn("* Verifying hypervisor parameters")
1460

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

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

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

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

    
1473
    dangling_instances = {}
1474
    no_node_instances = []
1475

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

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

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

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

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

    
1499

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

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

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

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

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

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

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

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

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

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

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

    
1580
      all_inst_info = self.cfg.GetAllInstancesInfo()
1581

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1714
    return True
1715

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2124
    nimg.os_fail = test
2125

    
2126
    if test:
2127
      return
2128

    
2129
    os_dict = {}
2130

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

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

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

    
2143
    nimg.oslist = os_dict
2144

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2340
      node_disks[nname] = disks
2341

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

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

    
2349
      node_disks_devonly[nname] = devonly
2350

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

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

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

    
2359
    instdisk = {}
2360

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

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

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

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

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

    
2400
    return instdisk
2401

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

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

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

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

    
2416
    return env
2417

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

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

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

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

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

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

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

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

    
2453
    # FIXME: verify OS list
2454

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2548
      inst_config.MapLVsByNode(node_vol_should)
2549

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

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

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

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

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

    
2581
    all_drbd_map = self.cfg.ComputeDRBDMap()
2582

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

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

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

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

    
2617
    feedback_fn("* Verifying node status")
2618

    
2619
    refos_img = None
2620

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

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

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

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

    
2649
      nresult = all_nvinfo[node].payload
2650

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2798
    return not self.bad
2799

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

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

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

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

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

    
2846
    return lu_result
2847

    
2848

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

2852
  """
2853
  REQ_BGL = False
2854

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

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

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

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

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

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

    
2887
    if not nv_dict:
2888
      return result
2889

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

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

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

    
2914
    return result
2915

    
2916

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

2920
  """
2921
  REQ_BGL = False
2922

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3030

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

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

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

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

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

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

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

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

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

    
3074
    self.op.name = new_name
3075

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

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

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

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

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

    
3109
    return clustername
3110

    
3111

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3454

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

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

    
3468

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

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

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

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

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

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

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

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

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

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

    
3512

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

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

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

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

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

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

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

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

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

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

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

    
3563

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

3567
  This is a very simple LU.
3568

3569
  """
3570
  REQ_BGL = False
3571

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

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

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

    
3585

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

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

    
3593
  disks = _ExpandCheckDisks(instance, disks)
3594

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

    
3598
  node = instance.primary_node
3599

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

    
3603
  # TODO: Convert to utils.Retry
3604

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

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

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

    
3651
    if done or oneshot:
3652
      break
3653

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

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

    
3660

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

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

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

    
3671
  result = True
3672

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

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

    
3692
  return result
3693

    
3694

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

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

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

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

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

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

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

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

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

    
3729
    assert self.op.power_delay >= 0.0
3730

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3838
    return ret
3839

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

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

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

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

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

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

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

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

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

    
3893
    self.do_locking = self.use_locking
3894

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

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

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

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

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

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

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

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

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

    
3954
    data = {}
3955

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

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

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

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

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

    
3986
      data[os_name] = info
3987

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

    
3992

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

3996
  """
3997
  REQ_BGL = False
3998

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

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

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

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

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

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

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

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

    
4036

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

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

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

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

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

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

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

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

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

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

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

    
4083
    instance_list = self.cfg.GetInstanceList()
4084

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

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

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

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

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

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

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

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

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

    
4131

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

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

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

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

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

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

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

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

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

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

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

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

    
4179
      inst_data = lu.cfg.GetAllInstancesInfo()
4180

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

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

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

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

    
4207

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

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

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

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

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

    
4225

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

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

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

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

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

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

    
4255
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
4256
             in self.cfg.GetInstanceList()]
4257

    
4258
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
4259

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

    
4270
      node_vols = nresult.payload[:]
4271
      node_vols.sort(key=lambda vol: vol['dev'])
4272

    
4273
      for vol in node_vols:
4274
        node_output = []
4275
        for field in self.op.output_fields:
4276
          if field == "node":
4277
            val = node
4278
          elif field == "phys":
4279
            val = vol['dev']
4280
          elif field == "vg":
4281
            val = vol['vg']
4282
          elif field == "name":
4283
            val = vol['name']
4284
          elif field == "size":
4285
            val = int(float(vol['size']))
4286
          elif field == "instance":
4287
            for inst in ilist:
4288
              if node not in lv_by_node[inst]:
4289
                continue
4290
              if vol['name'] in lv_by_node[inst][node]:
4291
                val = inst.name
4292
                break
4293
            else:
4294
              val = '-'
4295
          else:
4296
            raise errors.ParameterError(field)
4297
          node_output.append(str(val))
4298

    
4299
        output.append(node_output)
4300

    
4301
    return output
4302

    
4303

    
4304
class LUNodeQueryStorage(NoHooksLU):
4305
  """Logical unit for getting information on storage units on node(s).
4306

4307
  """
4308
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4309
  REQ_BGL = False
4310

    
4311
  def CheckArguments(self):
4312
    _CheckOutputFields(static=self._FIELDS_STATIC,
4313
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4314
                       selected=self.op.output_fields)
4315

    
4316
  def ExpandNames(self):
4317
    self.needed_locks = {}
4318
    self.share_locks[locking.LEVEL_NODE] = 1
4319

    
4320
    if self.op.nodes:
4321
      self.needed_locks[locking.LEVEL_NODE] = \
4322
        _GetWantedNodes(self, self.op.nodes)
4323
    else:
4324
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4325

    
4326
  def Exec(self, feedback_fn):
4327
    """Computes the list of nodes and their attributes.
4328

4329
    """
4330
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
4331

    
4332
    # Always get name to sort by
4333
    if constants.SF_NAME in self.op.output_fields:
4334
      fields = self.op.output_fields[:]
4335
    else:
4336
      fields = [constants.SF_NAME] + self.op.output_fields
4337

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

    
4343
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4344
    name_idx = field_idx[constants.SF_NAME]
4345

    
4346
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4347
    data = self.rpc.call_storage_list(self.nodes,
4348
                                      self.op.storage_type, st_args,
4349
                                      self.op.name, fields)
4350

    
4351
    result = []
4352

    
4353
    for node in utils.NiceSort(self.nodes):
4354
      nresult = data[node]
4355
      if nresult.offline:
4356
        continue
4357

    
4358
      msg = nresult.fail_msg
4359
      if msg:
4360
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4361
        continue
4362

    
4363
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4364

    
4365
      for name in utils.NiceSort(rows.keys()):
4366
        row = rows[name]
4367

    
4368
        out = []
4369

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

    
4380
          out.append(val)
4381

    
4382
        result.append(out)
4383

    
4384
    return result
4385

    
4386

    
4387
class _InstanceQuery(_QueryBase):
4388
  FIELDS = query.INSTANCE_FIELDS
4389

    
4390
  def ExpandNames(self, lu):
4391
    lu.needed_locks = {}
4392
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
4393
    lu.share_locks[locking.LEVEL_NODE] = 1
4394

    
4395
    if self.names:
4396
      self.wanted = _GetWantedInstances(lu, self.names)
4397
    else:
4398
      self.wanted = locking.ALL_SET
4399

    
4400
    self.do_locking = (self.use_locking and
4401
                       query.IQ_LIVE in self.requested_data)
4402
    if self.do_locking:
4403
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4404
      lu.needed_locks[locking.LEVEL_NODE] = []
4405
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4406

    
4407
  def DeclareLocks(self, lu, level):
4408
    if level == locking.LEVEL_NODE and self.do_locking:
4409
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
4410

    
4411
  def _GetQueryData(self, lu):
4412
    """Computes the list of instances and their attributes.
4413

4414
    """
4415
    cluster = lu.cfg.GetClusterInfo()
4416
    all_info = lu.cfg.GetAllInstancesInfo()
4417

    
4418
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4419

    
4420
    instance_list = [all_info[name] for name in instance_names]
4421
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4422
                                        for inst in instance_list)))
4423
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4424
    bad_nodes = []
4425
    offline_nodes = []
4426
    wrongnode_inst = set()
4427

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

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

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

    
4477
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4478
                                   disk_usage, offline_nodes, bad_nodes,
4479
                                   live_data, wrongnode_inst, consinfo)
4480

    
4481

    
4482
class LUQuery(NoHooksLU):
4483
  """Query for resources/items of a certain kind.
4484

4485
  """
4486
  # pylint: disable-msg=W0142
4487
  REQ_BGL = False
4488

    
4489
  def CheckArguments(self):
4490
    qcls = _GetQueryImplementation(self.op.what)
4491

    
4492
    self.impl = qcls(self.op.filter, self.op.fields, False)
4493

    
4494
  def ExpandNames(self):
4495
    self.impl.ExpandNames(self)
4496

    
4497
  def DeclareLocks(self, level):
4498
    self.impl.DeclareLocks(self, level)
4499

    
4500
  def Exec(self, feedback_fn):
4501
    return self.impl.NewStyleQuery(self)
4502

    
4503

    
4504
class LUQueryFields(NoHooksLU):
4505
  """Query for resources/items of a certain kind.
4506

4507
  """
4508
  # pylint: disable-msg=W0142
4509
  REQ_BGL = False
4510

    
4511
  def CheckArguments(self):
4512
    self.qcls = _GetQueryImplementation(self.op.what)
4513

    
4514
  def ExpandNames(self):
4515
    self.needed_locks = {}
4516

    
4517
  def Exec(self, feedback_fn):
4518
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4519

    
4520

    
4521
class LUNodeModifyStorage(NoHooksLU):
4522
  """Logical unit for modifying a storage volume on a node.
4523

4524
  """
4525
  REQ_BGL = False
4526

    
4527
  def CheckArguments(self):
4528
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4529

    
4530
    storage_type = self.op.storage_type
4531

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

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

    
4546
  def ExpandNames(self):
4547
    self.needed_locks = {
4548
      locking.LEVEL_NODE: self.op.node_name,
4549
      }
4550

    
4551
  def Exec(self, feedback_fn):
4552
    """Computes the list of nodes and their attributes.
4553

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

    
4562

    
4563
class LUNodeAdd(LogicalUnit):
4564
  """Logical unit for adding node to the cluster.
4565

4566
  """
4567
  HPATH = "node-add"
4568
  HTYPE = constants.HTYPE_NODE
4569
  _NFLAGS = ["master_capable", "vm_capable"]
4570

    
4571
  def CheckArguments(self):
4572
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4573
    # validate/normalize the node name
4574
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4575
                                         family=self.primary_ip_family)
4576
    self.op.node_name = self.hostname.name
4577

    
4578
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4579
      raise errors.OpPrereqError("Cannot readd the master node",
4580
                                 errors.ECODE_STATE)
4581

    
4582
    if self.op.readd and self.op.group:
4583
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4584
                                 " being readded", errors.ECODE_INVAL)
4585

    
4586
  def BuildHooksEnv(self):
4587
    """Build hooks env.
4588

4589
    This will run on all nodes before, and on all nodes + the new node after.
4590

4591
    """
4592
    return {
4593
      "OP_TARGET": self.op.node_name,
4594
      "NODE_NAME": self.op.node_name,
4595
      "NODE_PIP": self.op.primary_ip,
4596
      "NODE_SIP": self.op.secondary_ip,
4597
      "MASTER_CAPABLE": str(self.op.master_capable),
4598
      "VM_CAPABLE": str(self.op.vm_capable),
4599
      }
4600

    
4601
  def BuildHooksNodes(self):
4602
    """Build hooks nodes.
4603

4604
    """
4605
    # Exclude added node
4606
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4607
    post_nodes = pre_nodes + [self.op.node_name, ]
4608

    
4609
    return (pre_nodes, post_nodes)
4610

    
4611
  def CheckPrereq(self):
4612
    """Check prerequisites.
4613

4614
    This checks:
4615
     - the new node is not already in the config
4616
     - it is resolvable
4617
     - its parameters (single/dual homed) matches the cluster
4618

4619
    Any errors are signaled by raising errors.OpPrereqError.
4620

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

    
4633
    secondary_ip = self.op.secondary_ip
4634
    if not netutils.IP4Address.IsValid(secondary_ip):
4635
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4636
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4637

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

    
4646
    self.changed_primary_ip = False
4647

    
4648
    for existing_node_name in node_list:
4649
      existing_node = cfg.GetNodeInfo(existing_node_name)
4650

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

    
4659
        continue
4660

    
4661
      if (existing_node.primary_ip == primary_ip or
4662
          existing_node.secondary_ip == primary_ip or
4663
          existing_node.primary_ip == secondary_ip or
4664
          existing_node.secondary_ip == secondary_ip):
4665
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4666
                                   " existing node %s" % existing_node.name,
4667
                                   errors.ECODE_NOTUNIQUE)
4668

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

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

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

    
4705
    # checks reachability
4706
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4707
      raise errors.OpPrereqError("Node not reachable by ping",
4708
                                 errors.ECODE_ENVIRON)
4709

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

    
4718
    if self.op.readd:
4719
      exceptions = [node]
4720
    else:
4721
      exceptions = []
4722

    
4723
    if self.op.master_capable:
4724
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4725
    else:
4726
      self.master_candidate = False
4727

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

    
4739
    if self.op.ndparams:
4740
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4741

    
4742
  def Exec(self, feedback_fn):
4743
    """Adds the new node to the cluster.
4744

4745
    """
4746
    new_node = self.new_node
4747
    node = new_node.name
4748

    
4749
    # We adding a new node so we assume it's powered
4750
    new_node.powered = True
4751

    
4752
    # for re-adds, reset the offline/drained/master-candidate flags;
4753
    # we need to reset here, otherwise offline would prevent RPC calls
4754
    # later in the procedure; this also means that if the re-add
4755
    # fails, we are left with a non-offlined, broken node
4756
    if self.op.readd:
4757
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4758
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4759
      # if we demote the node, we do cleanup later in the procedure
4760
      new_node.master_candidate = self.master_candidate
4761
      if self.changed_primary_ip:
4762
        new_node.primary_ip = self.op.primary_ip
4763

    
4764
    # copy the master/vm_capable flags
4765
    for attr in self._NFLAGS:
4766
      setattr(new_node, attr, getattr(self.op, attr))
4767

    
4768
    # notify the user about any possible mc promotion
4769
    if new_node.master_candidate:
4770
      self.LogInfo("Node will be a master candidate")
4771

    
4772
    if self.op.ndparams:
4773
      new_node.ndparams = self.op.ndparams
4774
    else:
4775
      new_node.ndparams = {}
4776

    
4777
    # check connectivity
4778
    result = self.rpc.call_version([node])[node]
4779
    result.Raise("Can't get version information from node %s" % node)
4780
    if constants.PROTOCOL_VERSION == result.payload:
4781
      logging.info("Communication to node %s fine, sw version %s match",
4782
                   node, result.payload)
4783
    else:
4784
      raise errors.OpExecError("Version mismatch master version %s,"
4785
                               " node version %s" %
4786
                               (constants.PROTOCOL_VERSION, result.payload))
4787

    
4788
    # Add node to our /etc/hosts, and add key to known_hosts
4789
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4790
      master_node = self.cfg.GetMasterNode()
4791
      result = self.rpc.call_etc_hosts_modify(master_node,
4792
                                              constants.ETC_HOSTS_ADD,
4793
                                              self.hostname.name,
4794
                                              self.hostname.ip)
4795
      result.Raise("Can't update hosts file with new host data")
4796

    
4797
    if new_node.secondary_ip != new_node.primary_ip:
4798
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4799
                               False)
4800

    
4801
    node_verify_list = [self.cfg.GetMasterNode()]
4802
    node_verify_param = {
4803
      constants.NV_NODELIST: [node],
4804
      # TODO: do a node-net-test as well?
4805
    }
4806

    
4807
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4808
                                       self.cfg.GetClusterName())
4809
    for verifier in node_verify_list:
4810
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4811
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4812
      if nl_payload:
4813
        for failed in nl_payload:
4814
          feedback_fn("ssh/hostname verification failed"
4815
                      " (checking from %s): %s" %
4816
                      (verifier, nl_payload[failed]))
4817
        raise errors.OpExecError("ssh/hostname verification failed")
4818

    
4819
    if self.op.readd:
4820
      _RedistributeAncillaryFiles(self)
4821
      self.context.ReaddNode(new_node)
4822
      # make sure we redistribute the config
4823
      self.cfg.Update(new_node, feedback_fn)
4824
      # and make sure the new node will not have old files around
4825
      if not new_node.master_candidate:
4826
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4827
        msg = result.fail_msg
4828
        if msg:
4829
          self.LogWarning("Node failed to demote itself from master"
4830
                          " candidate status: %s" % msg)
4831
    else:
4832
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4833
                                  additional_vm=self.op.vm_capable)
4834
      self.context.AddNode(new_node, self.proc.GetECId())
4835

    
4836

    
4837
class LUNodeSetParams(LogicalUnit):
4838
  """Modifies the parameters of a node.
4839

4840
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4841
      to the node role (as _ROLE_*)
4842
  @cvar _R2F: a dictionary from node role to tuples of flags
4843
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4844

4845
  """
4846
  HPATH = "node-modify"
4847
  HTYPE = constants.HTYPE_NODE
4848
  REQ_BGL = False
4849
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4850
  _F2R = {
4851
    (True, False, False): _ROLE_CANDIDATE,
4852
    (False, True, False): _ROLE_DRAINED,
4853
    (False, False, True): _ROLE_OFFLINE,
4854
    (False, False, False): _ROLE_REGULAR,
4855
    }
4856
  _R2F = dict((v, k) for k, v in _F2R.items())
4857
  _FLAGS = ["master_candidate", "drained", "offline"]
4858

    
4859
  def CheckArguments(self):
4860
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4861
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4862
                self.op.master_capable, self.op.vm_capable,
4863
                self.op.secondary_ip, self.op.ndparams]
4864
    if all_mods.count(None) == len(all_mods):
4865
      raise errors.OpPrereqError("Please pass at least one modification",
4866
                                 errors.ECODE_INVAL)
4867
    if all_mods.count(True) > 1:
4868
      raise errors.OpPrereqError("Can't set the node into more than one"
4869
                                 " state at the same time",
4870
                                 errors.ECODE_INVAL)
4871

    
4872
    # Boolean value that tells us whether we might be demoting from MC
4873
    self.might_demote = (self.op.master_candidate == False or
4874
                         self.op.offline == True or
4875
                         self.op.drained == True or
4876
                         self.op.master_capable == False)
4877

    
4878
    if self.op.secondary_ip:
4879
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4880
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4881
                                   " address" % self.op.secondary_ip,
4882
                                   errors.ECODE_INVAL)
4883

    
4884
    self.lock_all = self.op.auto_promote and self.might_demote
4885
    self.lock_instances = self.op.secondary_ip is not None
4886

    
4887
  def ExpandNames(self):
4888
    if self.lock_all:
4889
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4890
    else:
4891
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4892

    
4893
    if self.lock_instances:
4894
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4895

    
4896
  def DeclareLocks(self, level):
4897
    # If we have locked all instances, before waiting to lock nodes, release
4898
    # all the ones living on nodes unrelated to the current operation.
4899
    if level == locking.LEVEL_NODE and self.lock_instances:
4900
      self.affected_instances = []
4901
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4902
        instances_keep = []
4903

    
4904
        # Build list of instances to release
4905
        for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
4906
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4907
          if (instance.disk_template in constants.DTS_INT_MIRROR and
4908
              self.op.node_name in instance.all_nodes):
4909
            instances_keep.append(instance_name)
4910
            self.affected_instances.append(instance)
4911

    
4912
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
4913

    
4914
        assert (set(self.glm.list_owned(locking.LEVEL_INSTANCE)) ==
4915
                set(instances_keep))
4916

    
4917
  def BuildHooksEnv(self):
4918
    """Build hooks env.
4919

4920
    This runs on the master node.
4921

4922
    """
4923
    return {
4924
      "OP_TARGET": self.op.node_name,
4925
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4926
      "OFFLINE": str(self.op.offline),
4927
      "DRAINED": str(self.op.drained),
4928
      "MASTER_CAPABLE": str(self.op.master_capable),
4929
      "VM_CAPABLE": str(self.op.vm_capable),
4930
      }
4931

    
4932
  def BuildHooksNodes(self):
4933
    """Build hooks nodes.
4934

4935
    """
4936
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
4937
    return (nl, nl)
4938

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

4942
    This only checks the instance list against the existing names.
4943

4944
    """
4945
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4946

    
4947
    if (self.op.master_candidate is not None or
4948
        self.op.drained is not None or
4949
        self.op.offline is not None):
4950
      # we can't change the master's node flags
4951
      if self.op.node_name == self.cfg.GetMasterNode():
4952
        raise errors.OpPrereqError("The master role can be changed"
4953
                                   " only via master-failover",
4954
                                   errors.ECODE_INVAL)
4955

    
4956
    if self.op.master_candidate and not node.master_capable:
4957
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4958
                                 " it a master candidate" % node.name,
4959
                                 errors.ECODE_STATE)
4960

    
4961
    if self.op.vm_capable == False:
4962
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4963
      if ipri or isec:
4964
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4965
                                   " the vm_capable flag" % node.name,
4966
                                   errors.ECODE_STATE)
4967

    
4968
    if node.master_candidate and self.might_demote and not self.lock_all:
4969
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4970
      # check if after removing the current node, we're missing master
4971
      # candidates
4972
      (mc_remaining, mc_should, _) = \
4973
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4974
      if mc_remaining < mc_should:
4975
        raise errors.OpPrereqError("Not enough master candidates, please"
4976
                                   " pass auto promote option to allow"
4977
                                   " promotion", errors.ECODE_STATE)
4978

    
4979
    self.old_flags = old_flags = (node.master_candidate,
4980
                                  node.drained, node.offline)
4981
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
4982
    self.old_role = old_role = self._F2R[old_flags]
4983

    
4984
    # Check for ineffective changes
4985
    for attr in self._FLAGS:
4986
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4987
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4988
        setattr(self.op, attr, None)
4989

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

    
4993
    # TODO: We might query the real power state if it supports OOB
4994
    if _SupportsOob(self.cfg, node):
4995
      if self.op.offline is False and not (node.powered or
4996
                                           self.op.powered == True):
4997
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
4998
                                    " offline status can be reset") %
4999
                                   self.op.node_name)
5000
    elif self.op.powered is not None:
5001
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
5002
                                  " as it does not support out-of-band"
5003
                                  " handling") % self.op.node_name)
5004

    
5005
    # If we're being deofflined/drained, we'll MC ourself if needed
5006
    if (self.op.drained == False or self.op.offline == False or
5007
        (self.op.master_capable and not node.master_capable)):
5008
      if _DecideSelfPromotion(self):
5009
        self.op.master_candidate = True
5010
        self.LogInfo("Auto-promoting node to master candidate")
5011

    
5012
    # If we're no longer master capable, we'll demote ourselves from MC
5013
    if self.op.master_capable == False and node.master_candidate:
5014
      self.LogInfo("Demoting from master candidate")
5015
      self.op.master_candidate = False
5016

    
5017
    # Compute new role
5018
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
5019
    if self.op.master_candidate:
5020
      new_role = self._ROLE_CANDIDATE
5021
    elif self.op.drained:
5022
      new_role = self._ROLE_DRAINED
5023
    elif self.op.offline:
5024
      new_role = self._ROLE_OFFLINE
5025
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
5026
      # False is still in new flags, which means we're un-setting (the
5027
      # only) True flag
5028
      new_role = self._ROLE_REGULAR
5029
    else: # no new flags, nothing, keep old role
5030
      new_role = old_role
5031

    
5032
    self.new_role = new_role
5033

    
5034
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
5035
      # Trying to transition out of offline status
5036
      result = self.rpc.call_version([node.name])[node.name]
5037
      if result.fail_msg:
5038
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
5039
                                   " to report its version: %s" %
5040
                                   (node.name, result.fail_msg),
5041
                                   errors.ECODE_STATE)
5042
      else:
5043
        self.LogWarning("Transitioning node from offline to online state"
5044
                        " without using re-add. Please make sure the node"
5045
                        " is healthy!")
5046

    
5047
    if self.op.secondary_ip:
5048
      # Ok even without locking, because this can't be changed by any LU
5049
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
5050
      master_singlehomed = master.secondary_ip == master.primary_ip
5051
      if master_singlehomed and self.op.secondary_ip:
5052
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
5053
                                   " homed cluster", errors.ECODE_INVAL)
5054

    
5055
      if node.offline:
5056
        if self.affected_instances:
5057
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
5058
                                     " node has instances (%s) configured"
5059
                                     " to use it" % self.affected_instances)
5060
      else:
5061
        # On online nodes, check that no instances are running, and that
5062
        # the node has the new ip and we can reach it.
5063
        for instance in self.affected_instances:
5064
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
5065

    
5066
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
5067
        if master.name != node.name:
5068
          # check reachability from master secondary ip to new secondary ip
5069
          if not netutils.TcpPing(self.op.secondary_ip,
5070
                                  constants.DEFAULT_NODED_PORT,
5071
                                  source=master.secondary_ip):
5072
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5073
                                       " based ping to node daemon port",
5074
                                       errors.ECODE_ENVIRON)
5075

    
5076
    if self.op.ndparams:
5077
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
5078
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
5079
      self.new_ndparams = new_ndparams
5080

    
5081
  def Exec(self, feedback_fn):
5082
    """Modifies a node.
5083

5084
    """
5085
    node = self.node
5086
    old_role = self.old_role
5087
    new_role = self.new_role
5088

    
5089
    result = []
5090

    
5091
    if self.op.ndparams:
5092
      node.ndparams = self.new_ndparams
5093

    
5094
    if self.op.powered is not None:
5095
      node.powered = self.op.powered
5096

    
5097
    for attr in ["master_capable", "vm_capable"]:
5098
      val = getattr(self.op, attr)
5099
      if val is not None:
5100
        setattr(node, attr, val)
5101
        result.append((attr, str(val)))
5102

    
5103
    if new_role != old_role:
5104
      # Tell the node to demote itself, if no longer MC and not offline
5105
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5106
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5107
        if msg:
5108
          self.LogWarning("Node failed to demote itself: %s", msg)
5109

    
5110
      new_flags = self._R2F[new_role]
5111
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5112
        if of != nf:
5113
          result.append((desc, str(nf)))
5114
      (node.master_candidate, node.drained, node.offline) = new_flags
5115

    
5116
      # we locked all nodes, we adjust the CP before updating this node
5117
      if self.lock_all:
5118
        _AdjustCandidatePool(self, [node.name])
5119

    
5120
    if self.op.secondary_ip:
5121
      node.secondary_ip = self.op.secondary_ip
5122
      result.append(("secondary_ip", self.op.secondary_ip))
5123

    
5124
    # this will trigger configuration file update, if needed
5125
    self.cfg.Update(node, feedback_fn)
5126

    
5127
    # this will trigger job queue propagation or cleanup if the mc
5128
    # flag changed
5129
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5130
      self.context.ReaddNode(node)
5131

    
5132
    return result
5133

    
5134

    
5135
class LUNodePowercycle(NoHooksLU):
5136
  """Powercycles a node.
5137

5138
  """
5139
  REQ_BGL = False
5140

    
5141
  def CheckArguments(self):
5142
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5143
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5144
      raise errors.OpPrereqError("The node is the master and the force"
5145
                                 " parameter was not set",
5146
                                 errors.ECODE_INVAL)
5147

    
5148
  def ExpandNames(self):
5149
    """Locking for PowercycleNode.
5150

5151
    This is a last-resort option and shouldn't block on other
5152
    jobs. Therefore, we grab no locks.
5153

5154
    """
5155
    self.needed_locks = {}
5156

    
5157
  def Exec(self, feedback_fn):
5158
    """Reboots a node.
5159

5160
    """
5161
    result = self.rpc.call_node_powercycle(self.op.node_name,
5162
                                           self.cfg.GetHypervisorType())
5163
    result.Raise("Failed to schedule the reboot")
5164
    return result.payload
5165

    
5166

    
5167
class LUClusterQuery(NoHooksLU):
5168
  """Query cluster configuration.
5169

5170
  """
5171
  REQ_BGL = False
5172

    
5173
  def ExpandNames(self):
5174
    self.needed_locks = {}
5175

    
5176
  def Exec(self, feedback_fn):
5177
    """Return cluster config.
5178

5179
    """
5180
    cluster = self.cfg.GetClusterInfo()
5181
    os_hvp = {}
5182

    
5183
    # Filter just for enabled hypervisors
5184
    for os_name, hv_dict in cluster.os_hvp.items():
5185
      os_hvp[os_name] = {}
5186
      for hv_name, hv_params in hv_dict.items():
5187
        if hv_name in cluster.enabled_hypervisors:
5188
          os_hvp[os_name][hv_name] = hv_params
5189

    
5190
    # Convert ip_family to ip_version
5191
    primary_ip_version = constants.IP4_VERSION
5192
    if cluster.primary_ip_family == netutils.IP6Address.family:
5193
      primary_ip_version = constants.IP6_VERSION
5194

    
5195
    result = {
5196
      "software_version": constants.RELEASE_VERSION,
5197
      "protocol_version": constants.PROTOCOL_VERSION,
5198
      "config_version": constants.CONFIG_VERSION,
5199
      "os_api_version": max(constants.OS_API_VERSIONS),
5200
      "export_version": constants.EXPORT_VERSION,
5201
      "architecture": (platform.architecture()[0], platform.machine()),
5202
      "name": cluster.cluster_name,
5203
      "master": cluster.master_node,
5204
      "default_hypervisor": cluster.enabled_hypervisors[0],
5205
      "enabled_hypervisors": cluster.enabled_hypervisors,
5206
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5207
                        for hypervisor_name in cluster.enabled_hypervisors]),
5208
      "os_hvp": os_hvp,
5209
      "beparams": cluster.beparams,
5210
      "osparams": cluster.osparams,
5211
      "nicparams": cluster.nicparams,
5212
      "ndparams": cluster.ndparams,
5213
      "candidate_pool_size": cluster.candidate_pool_size,
5214
      "master_netdev": cluster.master_netdev,
5215
      "volume_group_name": cluster.volume_group_name,
5216
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5217
      "file_storage_dir": cluster.file_storage_dir,
5218
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5219
      "maintain_node_health": cluster.maintain_node_health,
5220
      "ctime": cluster.ctime,
5221
      "mtime": cluster.mtime,
5222
      "uuid": cluster.uuid,
5223
      "tags": list(cluster.GetTags()),
5224
      "uid_pool": cluster.uid_pool,
5225
      "default_iallocator": cluster.default_iallocator,
5226
      "reserved_lvs": cluster.reserved_lvs,
5227
      "primary_ip_version": primary_ip_version,
5228
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5229
      "hidden_os": cluster.hidden_os,
5230
      "blacklisted_os": cluster.blacklisted_os,
5231
      }
5232

    
5233
    return result
5234

    
5235

    
5236
class LUClusterConfigQuery(NoHooksLU):
5237
  """Return configuration values.
5238

5239
  """
5240
  REQ_BGL = False
5241
  _FIELDS_DYNAMIC = utils.FieldSet()
5242
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5243
                                  "watcher_pause", "volume_group_name")
5244

    
5245
  def CheckArguments(self):
5246
    _CheckOutputFields(static=self._FIELDS_STATIC,
5247
                       dynamic=self._FIELDS_DYNAMIC,
5248
                       selected=self.op.output_fields)
5249

    
5250
  def ExpandNames(self):
5251
    self.needed_locks = {}
5252

    
5253
  def Exec(self, feedback_fn):
5254
    """Dump a representation of the cluster config to the standard output.
5255

5256
    """
5257
    values = []
5258
    for field in self.op.output_fields:
5259
      if field == "cluster_name":
5260
        entry = self.cfg.GetClusterName()
5261
      elif field == "master_node":
5262
        entry = self.cfg.GetMasterNode()
5263
      elif field == "drain_flag":
5264
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5265
      elif field == "watcher_pause":
5266
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5267
      elif field == "volume_group_name":
5268
        entry = self.cfg.GetVGName()
5269
      else:
5270
        raise errors.ParameterError(field)
5271
      values.append(entry)
5272
    return values
5273

    
5274

    
5275
class LUInstanceActivateDisks(NoHooksLU):
5276
  """Bring up an instance's disks.
5277

5278
  """
5279
  REQ_BGL = False
5280

    
5281
  def ExpandNames(self):
5282
    self._ExpandAndLockInstance()
5283
    self.needed_locks[locking.LEVEL_NODE] = []
5284
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5285

    
5286
  def DeclareLocks(self, level):
5287
    if level == locking.LEVEL_NODE:
5288
      self._LockInstancesNodes()
5289

    
5290
  def CheckPrereq(self):
5291
    """Check prerequisites.
5292

5293
    This checks that the instance is in the cluster.
5294

5295
    """
5296
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5297
    assert self.instance is not None, \
5298
      "Cannot retrieve locked instance %s" % self.op.instance_name
5299
    _CheckNodeOnline(self, self.instance.primary_node)
5300

    
5301
  def Exec(self, feedback_fn):
5302
    """Activate the disks.
5303

5304
    """
5305
    disks_ok, disks_info = \
5306
              _AssembleInstanceDisks(self, self.instance,
5307
                                     ignore_size=self.op.ignore_size)
5308
    if not disks_ok:
5309
      raise errors.OpExecError("Cannot activate block devices")
5310

    
5311
    return disks_info
5312

    
5313

    
5314
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5315
                           ignore_size=False):
5316
  """Prepare the block devices for an instance.
5317

5318
  This sets up the block devices on all nodes.
5319

5320
  @type lu: L{LogicalUnit}
5321
  @param lu: the logical unit on whose behalf we execute
5322
  @type instance: L{objects.Instance}
5323
  @param instance: the instance for whose disks we assemble
5324
  @type disks: list of L{objects.Disk} or None
5325
  @param disks: which disks to assemble (or all, if None)
5326
  @type ignore_secondaries: boolean
5327
  @param ignore_secondaries: if true, errors on secondary nodes
5328
      won't result in an error return from the function
5329
  @type ignore_size: boolean
5330
  @param ignore_size: if true, the current known size of the disk
5331
      will not be used during the disk activation, useful for cases
5332
      when the size is wrong
5333
  @return: False if the operation failed, otherwise a list of
5334
      (host, instance_visible_name, node_visible_name)
5335
      with the mapping from node devices to instance devices
5336

5337
  """
5338
  device_info = []
5339
  disks_ok = True
5340
  iname = instance.name
5341
  disks = _ExpandCheckDisks(instance, disks)
5342

    
5343
  # With the two passes mechanism we try to reduce the window of
5344
  # opportunity for the race condition of switching DRBD to primary
5345
  # before handshaking occured, but we do not eliminate it
5346

    
5347
  # The proper fix would be to wait (with some limits) until the
5348
  # connection has been made and drbd transitions from WFConnection
5349
  # into any other network-connected state (Connected, SyncTarget,
5350
  # SyncSource, etc.)
5351

    
5352
  # 1st pass, assemble on all nodes in secondary mode
5353
  for idx, inst_disk in enumerate(disks):
5354
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5355
      if ignore_size:
5356
        node_disk = node_disk.Copy()
5357
        node_disk.UnsetSize()
5358
      lu.cfg.SetDiskID(node_disk, node)
5359
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5360
      msg = result.fail_msg
5361
      if msg:
5362
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5363
                           " (is_primary=False, pass=1): %s",
5364
                           inst_disk.iv_name, node, msg)
5365
        if not ignore_secondaries:
5366
          disks_ok = False
5367

    
5368
  # FIXME: race condition on drbd migration to primary
5369

    
5370
  # 2nd pass, do only the primary node
5371
  for idx, inst_disk in enumerate(disks):
5372
    dev_path = None
5373

    
5374
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5375
      if node != instance.primary_node:
5376
        continue
5377
      if ignore_size:
5378
        node_disk = node_disk.Copy()
5379
        node_disk.UnsetSize()
5380
      lu.cfg.SetDiskID(node_disk, node)
5381
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5382
      msg = result.fail_msg
5383
      if msg:
5384
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5385
                           " (is_primary=True, pass=2): %s",
5386
                           inst_disk.iv_name, node, msg)
5387
        disks_ok = False
5388
      else:
5389
        dev_path = result.payload
5390

    
5391
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5392

    
5393
  # leave the disks configured for the primary node
5394
  # this is a workaround that would be fixed better by
5395
  # improving the logical/physical id handling
5396
  for disk in disks:
5397
    lu.cfg.SetDiskID(disk, instance.primary_node)
5398

    
5399
  return disks_ok, device_info
5400

    
5401

    
5402
def _StartInstanceDisks(lu, instance, force):
5403
  """Start the disks of an instance.
5404

5405
  """
5406
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5407
                                           ignore_secondaries=force)
5408
  if not disks_ok:
5409
    _ShutdownInstanceDisks(lu, instance)
5410
    if force is not None and not force:
5411
      lu.proc.LogWarning("", hint="If the message above refers to a"
5412
                         " secondary node,"
5413
                         " you can retry the operation using '--force'.")
5414
    raise errors.OpExecError("Disk consistency error")
5415

    
5416

    
5417
class LUInstanceDeactivateDisks(NoHooksLU):
5418
  """Shutdown an instance's disks.
5419

5420
  """
5421
  REQ_BGL = False
5422

    
5423
  def ExpandNames(self):
5424
    self._ExpandAndLockInstance()
5425
    self.needed_locks[locking.LEVEL_NODE] = []
5426
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5427

    
5428
  def DeclareLocks(self, level):
5429
    if level == locking.LEVEL_NODE:
5430
      self._LockInstancesNodes()
5431

    
5432
  def CheckPrereq(self):
5433
    """Check prerequisites.
5434

5435
    This checks that the instance is in the cluster.
5436

5437
    """
5438
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5439
    assert self.instance is not None, \
5440
      "Cannot retrieve locked instance %s" % self.op.instance_name
5441

    
5442
  def Exec(self, feedback_fn):
5443
    """Deactivate the disks
5444

5445
    """
5446
    instance = self.instance
5447
    if self.op.force:
5448
      _ShutdownInstanceDisks(self, instance)
5449
    else:
5450
      _SafeShutdownInstanceDisks(self, instance)
5451

    
5452

    
5453
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5454
  """Shutdown block devices of an instance.
5455

5456
  This function checks if an instance is running, before calling
5457
  _ShutdownInstanceDisks.
5458

5459
  """
5460
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5461
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5462

    
5463

    
5464
def _ExpandCheckDisks(instance, disks):
5465
  """Return the instance disks selected by the disks list
5466

5467
  @type disks: list of L{objects.Disk} or None
5468
  @param disks: selected disks
5469
  @rtype: list of L{objects.Disk}
5470
  @return: selected instance disks to act on
5471

5472
  """
5473
  if disks is None:
5474
    return instance.disks
5475
  else:
5476
    if not set(disks).issubset(instance.disks):
5477
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5478
                                   " target instance")
5479
    return disks
5480

    
5481

    
5482
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5483
  """Shutdown block devices of an instance.
5484

5485
  This does the shutdown on all nodes of the instance.
5486

5487
  If the ignore_primary is false, errors on the primary node are
5488
  ignored.
5489

5490
  """
5491
  all_result = True
5492
  disks = _ExpandCheckDisks(instance, disks)
5493

    
5494
  for disk in disks:
5495
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5496
      lu.cfg.SetDiskID(top_disk, node)
5497
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5498
      msg = result.fail_msg
5499
      if msg:
5500
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5501
                      disk.iv_name, node, msg)
5502
        if ((node == instance.primary_node and not ignore_primary) or
5503
            (node != instance.primary_node and not result.offline)):
5504
          all_result = False
5505
  return all_result
5506

    
5507

    
5508
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5509
  """Checks if a node has enough free memory.
5510

5511
  This function check if a given node has the needed amount of free
5512
  memory. In case the node has less memory or we cannot get the
5513
  information from the node, this function raise an OpPrereqError
5514
  exception.
5515

5516
  @type lu: C{LogicalUnit}
5517
  @param lu: a logical unit from which we get configuration data
5518
  @type node: C{str}
5519
  @param node: the node to check
5520
  @type reason: C{str}
5521
  @param reason: string to use in the error message
5522
  @type requested: C{int}
5523
  @param requested: the amount of memory in MiB to check for
5524
  @type hypervisor_name: C{str}
5525
  @param hypervisor_name: the hypervisor to ask for memory stats
5526
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5527
      we cannot check the node
5528

5529
  """
5530
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5531
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5532
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5533
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5534
  if not isinstance(free_mem, int):
5535
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5536
                               " was '%s'" % (node, free_mem),
5537
                               errors.ECODE_ENVIRON)
5538
  if requested > free_mem:
5539
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5540
                               " needed %s MiB, available %s MiB" %
5541
                               (node, reason, requested, free_mem),
5542
                               errors.ECODE_NORES)
5543

    
5544

    
5545
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5546
  """Checks if nodes have enough free disk space in the all VGs.
5547

5548
  This function check if all given nodes have the needed amount of
5549
  free disk. In case any node has less disk or we cannot get the
5550
  information from the node, this function raise an OpPrereqError
5551
  exception.
5552

5553
  @type lu: C{LogicalUnit}
5554
  @param lu: a logical unit from which we get configuration data
5555
  @type nodenames: C{list}
5556
  @param nodenames: the list of node names to check
5557
  @type req_sizes: C{dict}
5558
  @param req_sizes: the hash of vg and corresponding amount of disk in
5559
      MiB to check for
5560
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5561
      or we cannot check the node
5562

5563
  """
5564
  for vg, req_size in req_sizes.items():
5565
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5566

    
5567

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

5571
  This function check if all given nodes have the needed amount of
5572
  free disk. In case any node has less disk or we cannot get the
5573
  information from the node, this function raise an OpPrereqError
5574
  exception.
5575

5576
  @type lu: C{LogicalUnit}
5577
  @param lu: a logical unit from which we get configuration data
5578
  @type nodenames: C{list}
5579
  @param nodenames: the list of node names to check
5580
  @type vg: C{str}
5581
  @param vg: the volume group to check
5582
  @type requested: C{int}
5583
  @param requested: the amount of disk in MiB to check for
5584
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5585
      or we cannot check the node
5586

5587
  """
5588
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5589
  for node in nodenames:
5590
    info = nodeinfo[node]
5591
    info.Raise("Cannot get current information from node %s" % node,
5592
               prereq=True, ecode=errors.ECODE_ENVIRON)
5593
    vg_free = info.payload.get("vg_free", None)
5594
    if not isinstance(vg_free, int):
5595
      raise errors.OpPrereqError("Can't compute free disk space on node"
5596
                                 " %s for vg %s, result was '%s'" %
5597
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5598
    if requested > vg_free:
5599
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5600
                                 " vg %s: required %d MiB, available %d MiB" %
5601
                                 (node, vg, requested, vg_free),
5602
                                 errors.ECODE_NORES)
5603

    
5604

    
5605
class LUInstanceStartup(LogicalUnit):
5606
  """Starts an instance.
5607

5608
  """
5609
  HPATH = "instance-start"
5610
  HTYPE = constants.HTYPE_INSTANCE
5611
  REQ_BGL = False
5612

    
5613
  def CheckArguments(self):
5614
    # extra beparams
5615
    if self.op.beparams:
5616
      # fill the beparams dict
5617
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5618

    
5619
  def ExpandNames(self):
5620
    self._ExpandAndLockInstance()
5621

    
5622
  def BuildHooksEnv(self):
5623
    """Build hooks env.
5624

5625
    This runs on master, primary and secondary nodes of the instance.
5626

5627
    """
5628
    env = {
5629
      "FORCE": self.op.force,
5630
      }
5631

    
5632
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5633

    
5634
    return env
5635

    
5636
  def BuildHooksNodes(self):
5637
    """Build hooks nodes.
5638

5639
    """
5640
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5641
    return (nl, nl)
5642

    
5643
  def CheckPrereq(self):
5644
    """Check prerequisites.
5645

5646
    This checks that the instance is in the cluster.
5647

5648
    """
5649
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5650
    assert self.instance is not None, \
5651
      "Cannot retrieve locked instance %s" % self.op.instance_name
5652

    
5653
    # extra hvparams
5654
    if self.op.hvparams:
5655
      # check hypervisor parameter syntax (locally)
5656
      cluster = self.cfg.GetClusterInfo()
5657
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5658
      filled_hvp = cluster.FillHV(instance)
5659
      filled_hvp.update(self.op.hvparams)
5660
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5661
      hv_type.CheckParameterSyntax(filled_hvp)
5662
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5663

    
5664
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5665

    
5666
    if self.primary_offline and self.op.ignore_offline_nodes:
5667
      self.proc.LogWarning("Ignoring offline primary node")
5668

    
5669
      if self.op.hvparams or self.op.beparams:
5670
        self.proc.LogWarning("Overridden parameters are ignored")
5671
    else:
5672
      _CheckNodeOnline(self, instance.primary_node)
5673

    
5674
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5675

    
5676
      # check bridges existence
5677
      _CheckInstanceBridgesExist(self, instance)
5678

    
5679
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5680
                                                instance.name,
5681
                                                instance.hypervisor)
5682
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5683
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5684
      if not remote_info.payload: # not running already
5685
        _CheckNodeFreeMemory(self, instance.primary_node,
5686
                             "starting instance %s" % instance.name,
5687
                             bep[constants.BE_MEMORY], instance.hypervisor)
5688

    
5689
  def Exec(self, feedback_fn):
5690
    """Start the instance.
5691

5692
    """
5693
    instance = self.instance
5694
    force = self.op.force
5695

    
5696
    if not self.op.no_remember:
5697
      self.cfg.MarkInstanceUp(instance.name)
5698

    
5699
    if self.primary_offline:
5700
      assert self.op.ignore_offline_nodes
5701
      self.proc.LogInfo("Primary node offline, marked instance as started")
5702
    else:
5703
      node_current = instance.primary_node
5704

    
5705
      _StartInstanceDisks(self, instance, force)
5706

    
5707
      result = self.rpc.call_instance_start(node_current, instance,
5708
                                            self.op.hvparams, self.op.beparams)
5709
      msg = result.fail_msg
5710
      if msg:
5711
        _ShutdownInstanceDisks(self, instance)
5712
        raise errors.OpExecError("Could not start instance: %s" % msg)
5713

    
5714

    
5715
class LUInstanceReboot(LogicalUnit):
5716
  """Reboot an instance.
5717

5718
  """
5719
  HPATH = "instance-reboot"
5720
  HTYPE = constants.HTYPE_INSTANCE
5721
  REQ_BGL = False
5722

    
5723
  def ExpandNames(self):
5724
    self._ExpandAndLockInstance()
5725

    
5726
  def BuildHooksEnv(self):
5727
    """Build hooks env.
5728

5729
    This runs on master, primary and secondary nodes of the instance.
5730

5731
    """
5732
    env = {
5733
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5734
      "REBOOT_TYPE": self.op.reboot_type,
5735
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5736
      }
5737

    
5738
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5739

    
5740
    return env
5741

    
5742
  def BuildHooksNodes(self):
5743
    """Build hooks nodes.
5744

5745
    """
5746
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5747
    return (nl, nl)
5748

    
5749
  def CheckPrereq(self):
5750
    """Check prerequisites.
5751

5752
    This checks that the instance is in the cluster.
5753

5754
    """
5755
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5756
    assert self.instance is not None, \
5757
      "Cannot retrieve locked instance %s" % self.op.instance_name
5758

    
5759
    _CheckNodeOnline(self, instance.primary_node)
5760

    
5761
    # check bridges existence
5762
    _CheckInstanceBridgesExist(self, instance)
5763

    
5764
  def Exec(self, feedback_fn):
5765
    """Reboot the instance.
5766

5767
    """
5768
    instance = self.instance
5769
    ignore_secondaries = self.op.ignore_secondaries
5770
    reboot_type = self.op.reboot_type
5771

    
5772
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5773
                                              instance.name,
5774
                                              instance.hypervisor)
5775
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5776
    instance_running = bool(remote_info.payload)
5777

    
5778
    node_current = instance.primary_node
5779

    
5780
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5781
                                            constants.INSTANCE_REBOOT_HARD]:
5782
      for disk in instance.disks:
5783
        self.cfg.SetDiskID(disk, node_current)
5784
      result = self.rpc.call_instance_reboot(node_current, instance,
5785
                                             reboot_type,
5786
                                             self.op.shutdown_timeout)
5787
      result.Raise("Could not reboot instance")
5788
    else:
5789
      if instance_running:
5790
        result = self.rpc.call_instance_shutdown(node_current, instance,
5791
                                                 self.op.shutdown_timeout)
5792
        result.Raise("Could not shutdown instance for full reboot")
5793
        _ShutdownInstanceDisks(self, instance)
5794
      else:
5795
        self.LogInfo("Instance %s was already stopped, starting now",
5796
                     instance.name)
5797
      _StartInstanceDisks(self, instance, ignore_secondaries)
5798
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5799
      msg = result.fail_msg
5800
      if msg:
5801
        _ShutdownInstanceDisks(self, instance)
5802
        raise errors.OpExecError("Could not start instance for"
5803
                                 " full reboot: %s" % msg)
5804

    
5805
    self.cfg.MarkInstanceUp(instance.name)
5806

    
5807

    
5808
class LUInstanceShutdown(LogicalUnit):
5809
  """Shutdown an instance.
5810

5811
  """
5812
  HPATH = "instance-stop"
5813
  HTYPE = constants.HTYPE_INSTANCE
5814
  REQ_BGL = False
5815

    
5816
  def ExpandNames(self):
5817
    self._ExpandAndLockInstance()
5818

    
5819
  def BuildHooksEnv(self):
5820
    """Build hooks env.
5821

5822
    This runs on master, primary and secondary nodes of the instance.
5823

5824
    """
5825
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5826
    env["TIMEOUT"] = self.op.timeout
5827
    return env
5828

    
5829
  def BuildHooksNodes(self):
5830
    """Build hooks nodes.
5831

5832
    """
5833
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5834
    return (nl, nl)
5835

    
5836
  def CheckPrereq(self):
5837
    """Check prerequisites.
5838

5839
    This checks that the instance is in the cluster.
5840

5841
    """
5842
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5843
    assert self.instance is not None, \
5844
      "Cannot retrieve locked instance %s" % self.op.instance_name
5845

    
5846
    self.primary_offline = \
5847
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5848

    
5849
    if self.primary_offline and self.op.ignore_offline_nodes:
5850
      self.proc.LogWarning("Ignoring offline primary node")
5851
    else:
5852
      _CheckNodeOnline(self, self.instance.primary_node)
5853

    
5854
  def Exec(self, feedback_fn):
5855
    """Shutdown the instance.
5856

5857
    """
5858
    instance = self.instance
5859
    node_current = instance.primary_node
5860
    timeout = self.op.timeout
5861

    
5862
    if not self.op.no_remember:
5863
      self.cfg.MarkInstanceDown(instance.name)
5864

    
5865
    if self.primary_offline:
5866
      assert self.op.ignore_offline_nodes
5867
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5868
    else:
5869
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5870
      msg = result.fail_msg
5871
      if msg:
5872
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5873

    
5874
      _ShutdownInstanceDisks(self, instance)
5875

    
5876

    
5877
class LUInstanceReinstall(LogicalUnit):
5878
  """Reinstall an instance.
5879

5880
  """
5881
  HPATH = "instance-reinstall"
5882
  HTYPE = constants.HTYPE_INSTANCE
5883
  REQ_BGL = False
5884

    
5885
  def ExpandNames(self):
5886
    self._ExpandAndLockInstance()
5887

    
5888
  def BuildHooksEnv(self):
5889
    """Build hooks env.
5890

5891
    This runs on master, primary and secondary nodes of the instance.
5892

5893
    """
5894
    return _BuildInstanceHookEnvByObject(self, self.instance)
5895

    
5896
  def BuildHooksNodes(self):
5897
    """Build hooks nodes.
5898

5899
    """
5900
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5901
    return (nl, nl)
5902

    
5903
  def CheckPrereq(self):
5904
    """Check prerequisites.
5905

5906
    This checks that the instance is in the cluster and is not running.
5907

5908
    """
5909
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5910
    assert instance is not None, \
5911
      "Cannot retrieve locked instance %s" % self.op.instance_name
5912
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5913
                     " offline, cannot reinstall")
5914
    for node in instance.secondary_nodes:
5915
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5916
                       " cannot reinstall")
5917

    
5918
    if instance.disk_template == constants.DT_DISKLESS:
5919
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5920
                                 self.op.instance_name,
5921
                                 errors.ECODE_INVAL)
5922
    _CheckInstanceDown(self, instance, "cannot reinstall")
5923

    
5924
    if self.op.os_type is not None:
5925
      # OS verification
5926
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5927
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5928
      instance_os = self.op.os_type
5929
    else:
5930
      instance_os = instance.os
5931

    
5932
    nodelist = list(instance.all_nodes)
5933

    
5934
    if self.op.osparams:
5935
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5936
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5937
      self.os_inst = i_osdict # the new dict (without defaults)
5938
    else:
5939
      self.os_inst = None
5940

    
5941
    self.instance = instance
5942

    
5943
  def Exec(self, feedback_fn):
5944
    """Reinstall the instance.
5945

5946
    """
5947
    inst = self.instance
5948

    
5949
    if self.op.os_type is not None:
5950
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5951
      inst.os = self.op.os_type
5952
      # Write to configuration
5953
      self.cfg.Update(inst, feedback_fn)
5954

    
5955
    _StartInstanceDisks(self, inst, None)
5956
    try:
5957
      feedback_fn("Running the instance OS create scripts...")
5958
      # FIXME: pass debug option from opcode to backend
5959
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5960
                                             self.op.debug_level,
5961
                                             osparams=self.os_inst)
5962
      result.Raise("Could not install OS for instance %s on node %s" %
5963
                   (inst.name, inst.primary_node))
5964
    finally:
5965
      _ShutdownInstanceDisks(self, inst)
5966

    
5967

    
5968
class LUInstanceRecreateDisks(LogicalUnit):
5969
  """Recreate an instance's missing disks.
5970

5971
  """
5972
  HPATH = "instance-recreate-disks"
5973
  HTYPE = constants.HTYPE_INSTANCE
5974
  REQ_BGL = False
5975

    
5976
  def CheckArguments(self):
5977
    # normalise the disk list
5978
    self.op.disks = sorted(frozenset(self.op.disks))
5979

    
5980
  def ExpandNames(self):
5981
    self._ExpandAndLockInstance()
5982
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5983
    if self.op.nodes:
5984
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5985
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5986
    else:
5987
      self.needed_locks[locking.LEVEL_NODE] = []
5988

    
5989
  def DeclareLocks(self, level):
5990
    if level == locking.LEVEL_NODE:
5991
      # if we replace the nodes, we only need to lock the old primary,
5992
      # otherwise we need to lock all nodes for disk re-creation
5993
      primary_only = bool(self.op.nodes)
5994
      self._LockInstancesNodes(primary_only=primary_only)
5995

    
5996
  def BuildHooksEnv(self):
5997
    """Build hooks env.
5998

5999
    This runs on master, primary and secondary nodes of the instance.
6000

6001
    """
6002
    return _BuildInstanceHookEnvByObject(self, self.instance)
6003

    
6004
  def BuildHooksNodes(self):
6005
    """Build hooks nodes.
6006

6007
    """
6008
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6009
    return (nl, nl)
6010

    
6011
  def CheckPrereq(self):
6012
    """Check prerequisites.
6013

6014
    This checks that the instance is in the cluster and is not running.
6015

6016
    """
6017
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6018
    assert instance is not None, \
6019
      "Cannot retrieve locked instance %s" % self.op.instance_name
6020
    if self.op.nodes:
6021
      if len(self.op.nodes) != len(instance.all_nodes):
6022
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6023
                                   " %d replacement nodes were specified" %
6024
                                   (instance.name, len(instance.all_nodes),
6025
                                    len(self.op.nodes)),
6026
                                   errors.ECODE_INVAL)
6027
      assert instance.disk_template != constants.DT_DRBD8 or \
6028
          len(self.op.nodes) == 2
6029
      assert instance.disk_template != constants.DT_PLAIN or \
6030
          len(self.op.nodes) == 1
6031
      primary_node = self.op.nodes[0]
6032
    else:
6033
      primary_node = instance.primary_node
6034
    _CheckNodeOnline(self, primary_node)
6035

    
6036
    if instance.disk_template == constants.DT_DISKLESS:
6037
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6038
                                 self.op.instance_name, errors.ECODE_INVAL)
6039
    # if we replace nodes *and* the old primary is offline, we don't
6040
    # check
6041
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
6042
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6043
    if not (self.op.nodes and old_pnode.offline):
6044
      _CheckInstanceDown(self, instance, "cannot recreate disks")
6045

    
6046
    if not self.op.disks:
6047
      self.op.disks = range(len(instance.disks))
6048
    else:
6049
      for idx in self.op.disks:
6050
        if idx >= len(instance.disks):
6051
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6052
                                     errors.ECODE_INVAL)
6053
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6054
      raise errors.OpPrereqError("Can't recreate disks partially and"
6055
                                 " change the nodes at the same time",
6056
                                 errors.ECODE_INVAL)
6057
    self.instance = instance
6058

    
6059
  def Exec(self, feedback_fn):
6060
    """Recreate the disks.
6061

6062
    """
6063
    # change primary node, if needed
6064
    if self.op.nodes:
6065
      self.instance.primary_node = self.op.nodes[0]
6066
      self.LogWarning("Changing the instance's nodes, you will have to"
6067
                      " remove any disks left on the older nodes manually")
6068

    
6069
    to_skip = []
6070
    for idx, disk in enumerate(self.instance.disks):
6071
      if idx not in self.op.disks: # disk idx has not been passed in
6072
        to_skip.append(idx)
6073
        continue
6074
      # update secondaries for disks, if needed
6075
      if self.op.nodes:
6076
        if disk.dev_type == constants.LD_DRBD8:
6077
          # need to update the nodes
6078
          assert len(self.op.nodes) == 2
6079
          logical_id = list(disk.logical_id)
6080
          logical_id[0] = self.op.nodes[0]
6081
          logical_id[1] = self.op.nodes[1]
6082
          disk.logical_id = tuple(logical_id)
6083

    
6084
    if self.op.nodes:
6085
      self.cfg.Update(self.instance, feedback_fn)
6086

    
6087
    _CreateDisks(self, self.instance, to_skip=to_skip)
6088

    
6089

    
6090
class LUInstanceRename(LogicalUnit):
6091
  """Rename an instance.
6092

6093
  """
6094
  HPATH = "instance-rename"
6095
  HTYPE = constants.HTYPE_INSTANCE
6096

    
6097
  def CheckArguments(self):
6098
    """Check arguments.
6099

6100
    """
6101
    if self.op.ip_check and not self.op.name_check:
6102
      # TODO: make the ip check more flexible and not depend on the name check
6103
      raise errors.OpPrereqError("IP address check requires a name check",
6104
                                 errors.ECODE_INVAL)
6105

    
6106
  def BuildHooksEnv(self):
6107
    """Build hooks env.
6108

6109
    This runs on master, primary and secondary nodes of the instance.
6110

6111
    """
6112
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6113
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6114
    return env
6115

    
6116
  def BuildHooksNodes(self):
6117
    """Build hooks nodes.
6118

6119
    """
6120
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6121
    return (nl, nl)
6122

    
6123
  def CheckPrereq(self):
6124
    """Check prerequisites.
6125

6126
    This checks that the instance is in the cluster and is not running.
6127

6128
    """
6129
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6130
                                                self.op.instance_name)
6131
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6132
    assert instance is not None
6133
    _CheckNodeOnline(self, instance.primary_node)
6134
    _CheckInstanceDown(self, instance, "cannot rename")
6135
    self.instance = instance
6136

    
6137
    new_name = self.op.new_name
6138
    if self.op.name_check:
6139
      hostname = netutils.GetHostname(name=new_name)
6140
      if hostname != new_name:
6141
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6142
                     hostname.name)
6143
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6144
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6145
                                    " same as given hostname '%s'") %
6146
                                    (hostname.name, self.op.new_name),
6147
                                    errors.ECODE_INVAL)
6148
      new_name = self.op.new_name = hostname.name
6149
      if (self.op.ip_check and
6150
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6151
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6152
                                   (hostname.ip, new_name),
6153
                                   errors.ECODE_NOTUNIQUE)
6154

    
6155
    instance_list = self.cfg.GetInstanceList()
6156
    if new_name in instance_list and new_name != instance.name:
6157
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6158
                                 new_name, errors.ECODE_EXISTS)
6159

    
6160
  def Exec(self, feedback_fn):
6161
    """Rename the instance.
6162

6163
    """
6164
    inst = self.instance
6165
    old_name = inst.name
6166

    
6167
    rename_file_storage = False
6168
    if (inst.disk_template in constants.DTS_FILEBASED and
6169
        self.op.new_name != inst.name):
6170
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6171
      rename_file_storage = True
6172

    
6173
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6174
    # Change the instance lock. This is definitely safe while we hold the BGL.
6175
    # Otherwise the new lock would have to be added in acquired mode.
6176
    assert self.REQ_BGL
6177
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6178
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6179

    
6180
    # re-read the instance from the configuration after rename
6181
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6182

    
6183
    if rename_file_storage:
6184
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6185
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6186
                                                     old_file_storage_dir,
6187
                                                     new_file_storage_dir)
6188
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6189
                   " (but the instance has been renamed in Ganeti)" %
6190
                   (inst.primary_node, old_file_storage_dir,
6191
                    new_file_storage_dir))
6192

    
6193
    _StartInstanceDisks(self, inst, None)
6194
    try:
6195
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6196
                                                 old_name, self.op.debug_level)
6197
      msg = result.fail_msg
6198
      if msg:
6199
        msg = ("Could not run OS rename script for instance %s on node %s"
6200
               " (but the instance has been renamed in Ganeti): %s" %
6201
               (inst.name, inst.primary_node, msg))
6202
        self.proc.LogWarning(msg)
6203
    finally:
6204
      _ShutdownInstanceDisks(self, inst)
6205

    
6206
    return inst.name
6207

    
6208

    
6209
class LUInstanceRemove(LogicalUnit):
6210
  """Remove an instance.
6211

6212
  """
6213
  HPATH = "instance-remove"
6214
  HTYPE = constants.HTYPE_INSTANCE
6215
  REQ_BGL = False
6216

    
6217
  def ExpandNames(self):
6218
    self._ExpandAndLockInstance()
6219
    self.needed_locks[locking.LEVEL_NODE] = []
6220
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6221

    
6222
  def DeclareLocks(self, level):
6223
    if level == locking.LEVEL_NODE:
6224
      self._LockInstancesNodes()
6225

    
6226
  def BuildHooksEnv(self):
6227
    """Build hooks env.
6228

6229
    This runs on master, primary and secondary nodes of the instance.
6230

6231
    """
6232
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6233
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6234
    return env
6235

    
6236
  def BuildHooksNodes(self):
6237
    """Build hooks nodes.
6238

6239
    """
6240
    nl = [self.cfg.GetMasterNode()]
6241
    nl_post = list(self.instance.all_nodes) + nl
6242
    return (nl, nl_post)
6243

    
6244
  def CheckPrereq(self):
6245
    """Check prerequisites.
6246

6247
    This checks that the instance is in the cluster.
6248

6249
    """
6250
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6251
    assert self.instance is not None, \
6252
      "Cannot retrieve locked instance %s" % self.op.instance_name
6253

    
6254
  def Exec(self, feedback_fn):
6255
    """Remove the instance.
6256

6257
    """
6258
    instance = self.instance
6259
    logging.info("Shutting down instance %s on node %s",
6260
                 instance.name, instance.primary_node)
6261

    
6262
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6263
                                             self.op.shutdown_timeout)
6264
    msg = result.fail_msg
6265
    if msg:
6266
      if self.op.ignore_failures:
6267
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6268
      else:
6269
        raise errors.OpExecError("Could not shutdown instance %s on"
6270
                                 " node %s: %s" %
6271
                                 (instance.name, instance.primary_node, msg))
6272

    
6273
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6274

    
6275

    
6276
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6277
  """Utility function to remove an instance.
6278

6279
  """
6280
  logging.info("Removing block devices for instance %s", instance.name)
6281

    
6282
  if not _RemoveDisks(lu, instance):
6283
    if not ignore_failures:
6284
      raise errors.OpExecError("Can't remove instance's disks")
6285
    feedback_fn("Warning: can't remove instance's disks")
6286

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

    
6289
  lu.cfg.RemoveInstance(instance.name)
6290

    
6291
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6292
    "Instance lock removal conflict"
6293

    
6294
  # Remove lock for the instance
6295
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6296

    
6297

    
6298
class LUInstanceQuery(NoHooksLU):
6299
  """Logical unit for querying instances.
6300

6301
  """
6302
  # pylint: disable-msg=W0142
6303
  REQ_BGL = False
6304

    
6305
  def CheckArguments(self):
6306
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6307
                             self.op.output_fields, self.op.use_locking)
6308

    
6309
  def ExpandNames(self):
6310
    self.iq.ExpandNames(self)
6311

    
6312
  def DeclareLocks(self, level):
6313
    self.iq.DeclareLocks(self, level)
6314

    
6315
  def Exec(self, feedback_fn):
6316
    return self.iq.OldStyleQuery(self)
6317

    
6318

    
6319
class LUInstanceFailover(LogicalUnit):
6320
  """Failover an instance.
6321

6322
  """
6323
  HPATH = "instance-failover"
6324
  HTYPE = constants.HTYPE_INSTANCE
6325
  REQ_BGL = False
6326

    
6327
  def CheckArguments(self):
6328
    """Check the arguments.
6329

6330
    """
6331
    self.iallocator = getattr(self.op, "iallocator", None)
6332
    self.target_node = getattr(self.op, "target_node", None)
6333

    
6334
  def ExpandNames(self):
6335
    self._ExpandAndLockInstance()
6336

    
6337
    if self.op.target_node is not None:
6338
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6339

    
6340
    self.needed_locks[locking.LEVEL_NODE] = []
6341
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6342

    
6343
    ignore_consistency = self.op.ignore_consistency
6344
    shutdown_timeout = self.op.shutdown_timeout
6345
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6346
                                       cleanup=False,
6347
                                       failover=True,
6348
                                       ignore_consistency=ignore_consistency,
6349
                                       shutdown_timeout=shutdown_timeout)
6350
    self.tasklets = [self._migrater]
6351

    
6352
  def DeclareLocks(self, level):
6353
    if level == locking.LEVEL_NODE:
6354
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6355
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6356
        if self.op.target_node is None:
6357
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6358
        else:
6359
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6360
                                                   self.op.target_node]
6361
        del self.recalculate_locks[locking.LEVEL_NODE]
6362
      else:
6363
        self._LockInstancesNodes()
6364

    
6365
  def BuildHooksEnv(self):
6366
    """Build hooks env.
6367

6368
    This runs on master, primary and secondary nodes of the instance.
6369

6370
    """
6371
    instance = self._migrater.instance
6372
    source_node = instance.primary_node
6373
    target_node = self.op.target_node
6374
    env = {
6375
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6376
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6377
      "OLD_PRIMARY": source_node,
6378
      "NEW_PRIMARY": target_node,
6379
      }
6380

    
6381
    if instance.disk_template in constants.DTS_INT_MIRROR:
6382
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6383
      env["NEW_SECONDARY"] = source_node
6384
    else:
6385
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6386

    
6387
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6388

    
6389
    return env
6390

    
6391
  def BuildHooksNodes(self):
6392
    """Build hooks nodes.
6393

6394
    """
6395
    instance = self._migrater.instance
6396
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6397
    return (nl, nl + [instance.primary_node])
6398

    
6399

    
6400
class LUInstanceMigrate(LogicalUnit):
6401
  """Migrate an instance.
6402

6403
  This is migration without shutting down, compared to the failover,
6404
  which is done with shutdown.
6405

6406
  """
6407
  HPATH = "instance-migrate"
6408
  HTYPE = constants.HTYPE_INSTANCE
6409
  REQ_BGL = False
6410

    
6411
  def ExpandNames(self):
6412
    self._ExpandAndLockInstance()
6413

    
6414
    if self.op.target_node is not None:
6415
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6416

    
6417
    self.needed_locks[locking.LEVEL_NODE] = []
6418
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6419

    
6420
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6421
                                       cleanup=self.op.cleanup,
6422
                                       failover=False,
6423
                                       fallback=self.op.allow_failover)
6424
    self.tasklets = [self._migrater]
6425

    
6426
  def DeclareLocks(self, level):
6427
    if level == locking.LEVEL_NODE:
6428
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6429
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6430
        if self.op.target_node is None:
6431
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6432
        else:
6433
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6434
                                                   self.op.target_node]
6435
        del self.recalculate_locks[locking.LEVEL_NODE]
6436
      else:
6437
        self._LockInstancesNodes()
6438

    
6439
  def BuildHooksEnv(self):
6440
    """Build hooks env.
6441

6442
    This runs on master, primary and secondary nodes of the instance.
6443

6444
    """
6445
    instance = self._migrater.instance
6446
    source_node = instance.primary_node
6447
    target_node = self.op.target_node
6448
    env = _BuildInstanceHookEnvByObject(self, instance)
6449
    env.update({
6450
      "MIGRATE_LIVE": self._migrater.live,
6451
      "MIGRATE_CLEANUP": self.op.cleanup,
6452
      "OLD_PRIMARY": source_node,
6453
      "NEW_PRIMARY": target_node,
6454
      })
6455

    
6456
    if instance.disk_template in constants.DTS_INT_MIRROR:
6457
      env["OLD_SECONDARY"] = target_node
6458
      env["NEW_SECONDARY"] = source_node
6459
    else:
6460
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6461

    
6462
    return env
6463

    
6464
  def BuildHooksNodes(self):
6465
    """Build hooks nodes.
6466

6467
    """
6468
    instance = self._migrater.instance
6469
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6470
    return (nl, nl + [instance.primary_node])
6471

    
6472

    
6473
class LUInstanceMove(LogicalUnit):
6474
  """Move an instance by data-copying.
6475

6476
  """
6477
  HPATH = "instance-move"
6478
  HTYPE = constants.HTYPE_INSTANCE
6479
  REQ_BGL = False
6480

    
6481
  def ExpandNames(self):
6482
    self._ExpandAndLockInstance()
6483
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6484
    self.op.target_node = target_node
6485
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6486
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6487

    
6488
  def DeclareLocks(self, level):
6489
    if level == locking.LEVEL_NODE:
6490
      self._LockInstancesNodes(primary_only=True)
6491

    
6492
  def BuildHooksEnv(self):
6493
    """Build hooks env.
6494

6495
    This runs on master, primary and secondary nodes of the instance.
6496

6497
    """
6498
    env = {
6499
      "TARGET_NODE": self.op.target_node,
6500
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6501
      }
6502
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6503
    return env
6504

    
6505
  def BuildHooksNodes(self):
6506
    """Build hooks nodes.
6507

6508
    """
6509
    nl = [
6510
      self.cfg.GetMasterNode(),
6511
      self.instance.primary_node,
6512
      self.op.target_node,
6513
      ]
6514
    return (nl, nl)
6515

    
6516
  def CheckPrereq(self):
6517
    """Check prerequisites.
6518

6519
    This checks that the instance is in the cluster.
6520

6521
    """
6522
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6523
    assert self.instance is not None, \
6524
      "Cannot retrieve locked instance %s" % self.op.instance_name
6525

    
6526
    node = self.cfg.GetNodeInfo(self.op.target_node)
6527
    assert node is not None, \
6528
      "Cannot retrieve locked node %s" % self.op.target_node
6529

    
6530
    self.target_node = target_node = node.name
6531

    
6532
    if target_node == instance.primary_node:
6533
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6534
                                 (instance.name, target_node),
6535
                                 errors.ECODE_STATE)
6536

    
6537
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6538

    
6539
    for idx, dsk in enumerate(instance.disks):
6540
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6541
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6542
                                   " cannot copy" % idx, errors.ECODE_STATE)
6543

    
6544
    _CheckNodeOnline(self, target_node)
6545
    _CheckNodeNotDrained(self, target_node)
6546
    _CheckNodeVmCapable(self, target_node)
6547

    
6548
    if instance.admin_up:
6549
      # check memory requirements on the secondary node
6550
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6551
                           instance.name, bep[constants.BE_MEMORY],
6552
                           instance.hypervisor)
6553
    else:
6554
      self.LogInfo("Not checking memory on the secondary node as"
6555
                   " instance will not be started")
6556

    
6557
    # check bridge existance
6558
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6559

    
6560
  def Exec(self, feedback_fn):
6561
    """Move an instance.
6562

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

6566
    """
6567
    instance = self.instance
6568

    
6569
    source_node = instance.primary_node
6570
    target_node = self.target_node
6571

    
6572
    self.LogInfo("Shutting down instance %s on source node %s",
6573
                 instance.name, source_node)
6574

    
6575
    result = self.rpc.call_instance_shutdown(source_node, instance,
6576
                                             self.op.shutdown_timeout)
6577
    msg = result.fail_msg
6578
    if msg:
6579
      if self.op.ignore_consistency:
6580
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6581
                             " Proceeding anyway. Please make sure node"
6582
                             " %s is down. Error details: %s",
6583
                             instance.name, source_node, source_node, msg)
6584
      else:
6585
        raise errors.OpExecError("Could not shutdown instance %s on"
6586
                                 " node %s: %s" %
6587
                                 (instance.name, source_node, msg))
6588

    
6589
    # create the target disks
6590
    try:
6591
      _CreateDisks(self, instance, target_node=target_node)
6592
    except errors.OpExecError:
6593
      self.LogWarning("Device creation failed, reverting...")
6594
      try:
6595
        _RemoveDisks(self, instance, target_node=target_node)
6596
      finally:
6597
        self.cfg.ReleaseDRBDMinors(instance.name)
6598
        raise
6599

    
6600
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6601

    
6602
    errs = []
6603
    # activate, get path, copy the data over
6604
    for idx, disk in enumerate(instance.disks):
6605
      self.LogInfo("Copying data for disk %d", idx)
6606
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6607
                                               instance.name, True, idx)
6608
      if result.fail_msg:
6609
        self.LogWarning("Can't assemble newly created disk %d: %s",
6610
                        idx, result.fail_msg)
6611
        errs.append(result.fail_msg)
6612
        break
6613
      dev_path = result.payload
6614
      result = self.rpc.call_blockdev_export(source_node, disk,
6615
                                             target_node, dev_path,
6616
                                             cluster_name)
6617
      if result.fail_msg:
6618
        self.LogWarning("Can't copy data over for disk %d: %s",
6619
                        idx, result.fail_msg)
6620
        errs.append(result.fail_msg)
6621
        break
6622

    
6623
    if errs:
6624
      self.LogWarning("Some disks failed to copy, aborting")
6625
      try:
6626
        _RemoveDisks(self, instance, target_node=target_node)
6627
      finally:
6628
        self.cfg.ReleaseDRBDMinors(instance.name)
6629
        raise errors.OpExecError("Errors during disk copy: %s" %
6630
                                 (",".join(errs),))
6631

    
6632
    instance.primary_node = target_node
6633
    self.cfg.Update(instance, feedback_fn)
6634

    
6635
    self.LogInfo("Removing the disks on the original node")
6636
    _RemoveDisks(self, instance, target_node=source_node)
6637

    
6638
    # Only start the instance if it's marked as up
6639
    if instance.admin_up:
6640
      self.LogInfo("Starting instance %s on node %s",
6641
                   instance.name, target_node)
6642

    
6643
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6644
                                           ignore_secondaries=True)
6645
      if not disks_ok:
6646
        _ShutdownInstanceDisks(self, instance)
6647
        raise errors.OpExecError("Can't activate the instance's disks")
6648

    
6649
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6650
      msg = result.fail_msg
6651
      if msg:
6652
        _ShutdownInstanceDisks(self, instance)
6653
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6654
                                 (instance.name, target_node, msg))
6655

    
6656

    
6657
class LUNodeMigrate(LogicalUnit):
6658
  """Migrate all instances from a node.
6659

6660
  """
6661
  HPATH = "node-migrate"
6662
  HTYPE = constants.HTYPE_NODE
6663
  REQ_BGL = False
6664

    
6665
  def CheckArguments(self):
6666
    pass
6667

    
6668
  def ExpandNames(self):
6669
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6670

    
6671
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
6672
    self.needed_locks = {
6673
      locking.LEVEL_NODE: [self.op.node_name],
6674
      }
6675

    
6676
  def BuildHooksEnv(self):
6677
    """Build hooks env.
6678

6679
    This runs on the master, the primary and all the secondaries.
6680

6681
    """
6682
    return {
6683
      "NODE_NAME": self.op.node_name,
6684
      }
6685

    
6686
  def BuildHooksNodes(self):
6687
    """Build hooks nodes.
6688

6689
    """
6690
    nl = [self.cfg.GetMasterNode()]
6691
    return (nl, nl)
6692

    
6693
  def CheckPrereq(self):
6694
    pass
6695

    
6696
  def Exec(self, feedback_fn):
6697
    # Prepare jobs for migration instances
6698
    jobs = [
6699
      [opcodes.OpInstanceMigrate(instance_name=inst.name,
6700
                                 mode=self.op.mode,
6701
                                 live=self.op.live,
6702
                                 iallocator=self.op.iallocator,
6703
                                 target_node=self.op.target_node)]
6704
      for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name)
6705
      ]
6706

    
6707
    # TODO: Run iallocator in this opcode and pass correct placement options to
6708
    # OpInstanceMigrate. Since other jobs can modify the cluster between
6709
    # running the iallocator and the actual migration, a good consistency model
6710
    # will have to be found.
6711

    
6712
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
6713
            frozenset([self.op.node_name]))
6714

    
6715
    return ResultWithJobs(jobs)
6716

    
6717

    
6718
class TLMigrateInstance(Tasklet):
6719
  """Tasklet class for instance migration.
6720

6721
  @type live: boolean
6722
  @ivar live: whether the migration will be done live or non-live;
6723
      this variable is initalized only after CheckPrereq has run
6724
  @type cleanup: boolean
6725
  @ivar cleanup: Wheater we cleanup from a failed migration
6726
  @type iallocator: string
6727
  @ivar iallocator: The iallocator used to determine target_node
6728
  @type target_node: string
6729
  @ivar target_node: If given, the target_node to reallocate the instance to
6730
  @type failover: boolean
6731
  @ivar failover: Whether operation results in failover or migration
6732
  @type fallback: boolean
6733
  @ivar fallback: Whether fallback to failover is allowed if migration not
6734
                  possible
6735
  @type ignore_consistency: boolean
6736
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6737
                            and target node
6738
  @type shutdown_timeout: int
6739
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6740

6741
  """
6742
  def __init__(self, lu, instance_name, cleanup=False,
6743
               failover=False, fallback=False,
6744
               ignore_consistency=False,
6745
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6746
    """Initializes this class.
6747

6748
    """
6749
    Tasklet.__init__(self, lu)
6750

    
6751
    # Parameters
6752
    self.instance_name = instance_name
6753
    self.cleanup = cleanup
6754
    self.live = False # will be overridden later
6755
    self.failover = failover
6756
    self.fallback = fallback
6757
    self.ignore_consistency = ignore_consistency
6758
    self.shutdown_timeout = shutdown_timeout
6759

    
6760
  def CheckPrereq(self):
6761
    """Check prerequisites.
6762

6763
    This checks that the instance is in the cluster.
6764

6765
    """
6766
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6767
    instance = self.cfg.GetInstanceInfo(instance_name)
6768
    assert instance is not None
6769
    self.instance = instance
6770

    
6771
    if (not self.cleanup and not instance.admin_up and not self.failover and
6772
        self.fallback):
6773
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6774
                      " to failover")
6775
      self.failover = True
6776

    
6777
    if instance.disk_template not in constants.DTS_MIRRORED:
6778
      if self.failover:
6779
        text = "failovers"
6780
      else:
6781
        text = "migrations"
6782
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6783
                                 " %s" % (instance.disk_template, text),
6784
                                 errors.ECODE_STATE)
6785

    
6786
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6787
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6788

    
6789
      if self.lu.op.iallocator:
6790
        self._RunAllocator()
6791
      else:
6792
        # We set set self.target_node as it is required by
6793
        # BuildHooksEnv
6794
        self.target_node = self.lu.op.target_node
6795

    
6796
      # self.target_node is already populated, either directly or by the
6797
      # iallocator run
6798
      target_node = self.target_node
6799
      if self.target_node == instance.primary_node:
6800
        raise errors.OpPrereqError("Cannot migrate instance %s"
6801
                                   " to its primary (%s)" %
6802
                                   (instance.name, instance.primary_node))
6803

    
6804
      if len(self.lu.tasklets) == 1:
6805
        # It is safe to release locks only when we're the only tasklet
6806
        # in the LU
6807
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6808
                      keep=[instance.primary_node, self.target_node])
6809

    
6810
    else:
6811
      secondary_nodes = instance.secondary_nodes
6812
      if not secondary_nodes:
6813
        raise errors.ConfigurationError("No secondary node but using"
6814
                                        " %s disk template" %
6815
                                        instance.disk_template)
6816
      target_node = secondary_nodes[0]
6817
      if self.lu.op.iallocator or (self.lu.op.target_node and
6818
                                   self.lu.op.target_node != target_node):
6819
        if self.failover:
6820
          text = "failed over"
6821
        else:
6822
          text = "migrated"
6823
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6824
                                   " be %s to arbitrary nodes"
6825
                                   " (neither an iallocator nor a target"
6826
                                   " node can be passed)" %
6827
                                   (instance.disk_template, text),
6828
                                   errors.ECODE_INVAL)
6829

    
6830
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6831

    
6832
    # check memory requirements on the secondary node
6833
    if not self.failover or instance.admin_up:
6834
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6835
                           instance.name, i_be[constants.BE_MEMORY],
6836
                           instance.hypervisor)
6837
    else:
6838
      self.lu.LogInfo("Not checking memory on the secondary node as"
6839
                      " instance will not be started")
6840

    
6841
    # check bridge existance
6842
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6843

    
6844
    if not self.cleanup:
6845
      _CheckNodeNotDrained(self.lu, target_node)
6846
      if not self.failover:
6847
        result = self.rpc.call_instance_migratable(instance.primary_node,
6848
                                                   instance)
6849
        if result.fail_msg and self.fallback:
6850
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6851
                          " failover")
6852
          self.failover = True
6853
        else:
6854
          result.Raise("Can't migrate, please use failover",
6855
                       prereq=True, ecode=errors.ECODE_STATE)
6856

    
6857
    assert not (self.failover and self.cleanup)
6858

    
6859
    if not self.failover:
6860
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6861
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6862
                                   " parameters are accepted",
6863
                                   errors.ECODE_INVAL)
6864
      if self.lu.op.live is not None:
6865
        if self.lu.op.live:
6866
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6867
        else:
6868
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6869
        # reset the 'live' parameter to None so that repeated
6870
        # invocations of CheckPrereq do not raise an exception
6871
        self.lu.op.live = None
6872
      elif self.lu.op.mode is None:
6873
        # read the default value from the hypervisor
6874
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6875
                                                skip_globals=False)
6876
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6877

    
6878
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6879
    else:
6880
      # Failover is never live
6881
      self.live = False
6882

    
6883
  def _RunAllocator(self):
6884
    """Run the allocator based on input opcode.
6885

6886
    """
6887
    ial = IAllocator(self.cfg, self.rpc,
6888
                     mode=constants.IALLOCATOR_MODE_RELOC,
6889
                     name=self.instance_name,
6890
                     # TODO See why hail breaks with a single node below
6891
                     relocate_from=[self.instance.primary_node,
6892
                                    self.instance.primary_node],
6893
                     )
6894

    
6895
    ial.Run(self.lu.op.iallocator)
6896

    
6897
    if not ial.success:
6898
      raise errors.OpPrereqError("Can't compute nodes using"
6899
                                 " iallocator '%s': %s" %
6900
                                 (self.lu.op.iallocator, ial.info),
6901
                                 errors.ECODE_NORES)
6902
    if len(ial.result) != ial.required_nodes:
6903
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6904
                                 " of nodes (%s), required %s" %
6905
                                 (self.lu.op.iallocator, len(ial.result),
6906
                                  ial.required_nodes), errors.ECODE_FAULT)
6907
    self.target_node = ial.result[0]
6908
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6909
                 self.instance_name, self.lu.op.iallocator,
6910
                 utils.CommaJoin(ial.result))
6911

    
6912
  def _WaitUntilSync(self):
6913
    """Poll with custom rpc for disk sync.
6914

6915
    This uses our own step-based rpc call.
6916

6917
    """
6918
    self.feedback_fn("* wait until resync is done")
6919
    all_done = False
6920
    while not all_done:
6921
      all_done = True
6922
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6923
                                            self.nodes_ip,
6924
                                            self.instance.disks)
6925
      min_percent = 100
6926
      for node, nres in result.items():
6927
        nres.Raise("Cannot resync disks on node %s" % node)
6928
        node_done, node_percent = nres.payload
6929
        all_done = all_done and node_done
6930
        if node_percent is not None:
6931
          min_percent = min(min_percent, node_percent)
6932
      if not all_done:
6933
        if min_percent < 100:
6934
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6935
        time.sleep(2)
6936

    
6937
  def _EnsureSecondary(self, node):
6938
    """Demote a node to secondary.
6939

6940
    """
6941
    self.feedback_fn("* switching node %s to secondary mode" % node)
6942

    
6943
    for dev in self.instance.disks:
6944
      self.cfg.SetDiskID(dev, node)
6945

    
6946
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6947
                                          self.instance.disks)
6948
    result.Raise("Cannot change disk to secondary on node %s" % node)
6949

    
6950
  def _GoStandalone(self):
6951
    """Disconnect from the network.
6952

6953
    """
6954
    self.feedback_fn("* changing into standalone mode")
6955
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6956
                                               self.instance.disks)
6957
    for node, nres in result.items():
6958
      nres.Raise("Cannot disconnect disks node %s" % node)
6959

    
6960
  def _GoReconnect(self, multimaster):
6961
    """Reconnect to the network.
6962

6963
    """
6964
    if multimaster:
6965
      msg = "dual-master"
6966
    else:
6967
      msg = "single-master"
6968
    self.feedback_fn("* changing disks into %s mode" % msg)
6969
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6970
                                           self.instance.disks,
6971
                                           self.instance.name, multimaster)
6972
    for node, nres in result.items():
6973
      nres.Raise("Cannot change disks config on node %s" % node)
6974

    
6975
  def _ExecCleanup(self):
6976
    """Try to cleanup after a failed migration.
6977

6978
    The cleanup is done by:
6979
      - check that the instance is running only on one node
6980
        (and update the config if needed)
6981
      - change disks on its secondary node to secondary
6982
      - wait until disks are fully synchronized
6983
      - disconnect from the network
6984
      - change disks into single-master mode
6985
      - wait again until disks are fully synchronized
6986

6987
    """
6988
    instance = self.instance
6989
    target_node = self.target_node
6990
    source_node = self.source_node
6991

    
6992
    # check running on only one node
6993
    self.feedback_fn("* checking where the instance actually runs"
6994
                     " (if this hangs, the hypervisor might be in"
6995
                     " a bad state)")
6996
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6997
    for node, result in ins_l.items():
6998
      result.Raise("Can't contact node %s" % node)
6999

    
7000
    runningon_source = instance.name in ins_l[source_node].payload
7001
    runningon_target = instance.name in ins_l[target_node].payload
7002

    
7003
    if runningon_source and runningon_target:
7004
      raise errors.OpExecError("Instance seems to be running on two nodes,"
7005
                               " or the hypervisor is confused; you will have"
7006
                               " to ensure manually that it runs only on one"
7007
                               " and restart this operation")
7008

    
7009
    if not (runningon_source or runningon_target):
7010
      raise errors.OpExecError("Instance does not seem to be running at all;"
7011
                               " in this case it's safer to repair by"
7012
                               " running 'gnt-instance stop' to ensure disk"
7013
                               " shutdown, and then restarting it")
7014

    
7015
    if runningon_target:
7016
      # the migration has actually succeeded, we need to update the config
7017
      self.feedback_fn("* instance running on secondary node (%s),"
7018
                       " updating config" % target_node)
7019
      instance.primary_node = target_node
7020
      self.cfg.Update(instance, self.feedback_fn)
7021
      demoted_node = source_node
7022
    else:
7023
      self.feedback_fn("* instance confirmed to be running on its"
7024
                       " primary node (%s)" % source_node)
7025
      demoted_node = target_node
7026

    
7027
    if instance.disk_template in constants.DTS_INT_MIRROR:
7028
      self._EnsureSecondary(demoted_node)
7029
      try:
7030
        self._WaitUntilSync()
7031
      except errors.OpExecError:
7032
        # we ignore here errors, since if the device is standalone, it
7033
        # won't be able to sync
7034
        pass
7035
      self._GoStandalone()
7036
      self._GoReconnect(False)
7037
      self._WaitUntilSync()
7038

    
7039
    self.feedback_fn("* done")
7040

    
7041
  def _RevertDiskStatus(self):
7042
    """Try to revert the disk status after a failed migration.
7043

7044
    """
7045
    target_node = self.target_node
7046
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7047
      return
7048

    
7049
    try:
7050
      self._EnsureSecondary(target_node)
7051
      self._GoStandalone()
7052
      self._GoReconnect(False)
7053
      self._WaitUntilSync()
7054
    except errors.OpExecError, err:
7055
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7056
                         " please try to recover the instance manually;"
7057
                         " error '%s'" % str(err))
7058

    
7059
  def _AbortMigration(self):
7060
    """Call the hypervisor code to abort a started migration.
7061

7062
    """
7063
    instance = self.instance
7064
    target_node = self.target_node
7065
    migration_info = self.migration_info
7066

    
7067
    abort_result = self.rpc.call_finalize_migration(target_node,
7068
                                                    instance,
7069
                                                    migration_info,
7070
                                                    False)
7071
    abort_msg = abort_result.fail_msg
7072
    if abort_msg:
7073
      logging.error("Aborting migration failed on target node %s: %s",
7074
                    target_node, abort_msg)
7075
      # Don't raise an exception here, as we stil have to try to revert the
7076
      # disk status, even if this step failed.
7077

    
7078
  def _ExecMigration(self):
7079
    """Migrate an instance.
7080

7081
    The migrate is done by:
7082
      - change the disks into dual-master mode
7083
      - wait until disks are fully synchronized again
7084
      - migrate the instance
7085
      - change disks on the new secondary node (the old primary) to secondary
7086
      - wait until disks are fully synchronized
7087
      - change disks into single-master mode
7088

7089
    """
7090
    instance = self.instance
7091
    target_node = self.target_node
7092
    source_node = self.source_node
7093

    
7094
    self.feedback_fn("* checking disk consistency between source and target")
7095
    for dev in instance.disks:
7096
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7097
        raise errors.OpExecError("Disk %s is degraded or not fully"
7098
                                 " synchronized on target node,"
7099
                                 " aborting migration" % dev.iv_name)
7100

    
7101
    # First get the migration information from the remote node
7102
    result = self.rpc.call_migration_info(source_node, instance)
7103
    msg = result.fail_msg
7104
    if msg:
7105
      log_err = ("Failed fetching source migration information from %s: %s" %
7106
                 (source_node, msg))
7107
      logging.error(log_err)
7108
      raise errors.OpExecError(log_err)
7109

    
7110
    self.migration_info = migration_info = result.payload
7111

    
7112
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7113
      # Then switch the disks to master/master mode
7114
      self._EnsureSecondary(target_node)
7115
      self._GoStandalone()
7116
      self._GoReconnect(True)
7117
      self._WaitUntilSync()
7118

    
7119
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7120
    result = self.rpc.call_accept_instance(target_node,
7121
                                           instance,
7122
                                           migration_info,
7123
                                           self.nodes_ip[target_node])
7124

    
7125
    msg = result.fail_msg
7126
    if msg:
7127
      logging.error("Instance pre-migration failed, trying to revert"
7128
                    " disk status: %s", msg)
7129
      self.feedback_fn("Pre-migration failed, aborting")
7130
      self._AbortMigration()
7131
      self._RevertDiskStatus()
7132
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7133
                               (instance.name, msg))
7134

    
7135
    self.feedback_fn("* migrating instance to %s" % target_node)
7136
    result = self.rpc.call_instance_migrate(source_node, instance,
7137
                                            self.nodes_ip[target_node],
7138
                                            self.live)
7139
    msg = result.fail_msg
7140
    if msg:
7141
      logging.error("Instance migration failed, trying to revert"
7142
                    " disk status: %s", msg)
7143
      self.feedback_fn("Migration failed, aborting")
7144
      self._AbortMigration()
7145
      self._RevertDiskStatus()
7146
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7147
                               (instance.name, msg))
7148

    
7149
    instance.primary_node = target_node
7150
    # distribute new instance config to the other nodes
7151
    self.cfg.Update(instance, self.feedback_fn)
7152

    
7153
    result = self.rpc.call_finalize_migration(target_node,
7154
                                              instance,
7155
                                              migration_info,
7156
                                              True)
7157
    msg = result.fail_msg
7158
    if msg:
7159
      logging.error("Instance migration succeeded, but finalization failed:"
7160
                    " %s", msg)
7161
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7162
                               msg)
7163

    
7164
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7165
      self._EnsureSecondary(source_node)
7166
      self._WaitUntilSync()
7167
      self._GoStandalone()
7168
      self._GoReconnect(False)
7169
      self._WaitUntilSync()
7170

    
7171
    self.feedback_fn("* done")
7172

    
7173
  def _ExecFailover(self):
7174
    """Failover an instance.
7175

7176
    The failover is done by shutting it down on its present node and
7177
    starting it on the secondary.
7178

7179
    """
7180
    instance = self.instance
7181
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7182

    
7183
    source_node = instance.primary_node
7184
    target_node = self.target_node
7185

    
7186
    if instance.admin_up:
7187
      self.feedback_fn("* checking disk consistency between source and target")
7188
      for dev in instance.disks:
7189
        # for drbd, these are drbd over lvm
7190
        if not _CheckDiskConsistency(self, dev, target_node, False):
7191
          if not self.ignore_consistency:
7192
            raise errors.OpExecError("Disk %s is degraded on target node,"
7193
                                     " aborting failover" % dev.iv_name)
7194
    else:
7195
      self.feedback_fn("* not checking disk consistency as instance is not"
7196
                       " running")
7197

    
7198
    self.feedback_fn("* shutting down instance on source node")
7199
    logging.info("Shutting down instance %s on node %s",
7200
                 instance.name, source_node)
7201

    
7202
    result = self.rpc.call_instance_shutdown(source_node, instance,
7203
                                             self.shutdown_timeout)
7204
    msg = result.fail_msg
7205
    if msg:
7206
      if self.ignore_consistency or primary_node.offline:
7207
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7208
                           " proceeding anyway; please make sure node"
7209
                           " %s is down; error details: %s",
7210
                           instance.name, source_node, source_node, msg)
7211
      else:
7212
        raise errors.OpExecError("Could not shutdown instance %s on"
7213
                                 " node %s: %s" %
7214
                                 (instance.name, source_node, msg))
7215

    
7216
    self.feedback_fn("* deactivating the instance's disks on source node")
7217
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
7218
      raise errors.OpExecError("Can't shut down the instance's disks.")
7219

    
7220
    instance.primary_node = target_node
7221
    # distribute new instance config to the other nodes
7222
    self.cfg.Update(instance, self.feedback_fn)
7223

    
7224
    # Only start the instance if it's marked as up
7225
    if instance.admin_up:
7226
      self.feedback_fn("* activating the instance's disks on target node")
7227
      logging.info("Starting instance %s on node %s",
7228
                   instance.name, target_node)
7229

    
7230
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7231
                                           ignore_secondaries=True)
7232
      if not disks_ok:
7233
        _ShutdownInstanceDisks(self, instance)
7234
        raise errors.OpExecError("Can't activate the instance's disks")
7235

    
7236
      self.feedback_fn("* starting the instance on the target node")
7237
      result = self.rpc.call_instance_start(target_node, instance, None, None)
7238
      msg = result.fail_msg
7239
      if msg:
7240
        _ShutdownInstanceDisks(self, instance)
7241
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7242
                                 (instance.name, target_node, msg))
7243

    
7244
  def Exec(self, feedback_fn):
7245
    """Perform the migration.
7246

7247
    """
7248
    self.feedback_fn = feedback_fn
7249
    self.source_node = self.instance.primary_node
7250

    
7251
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7252
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7253
      self.target_node = self.instance.secondary_nodes[0]
7254
      # Otherwise self.target_node has been populated either
7255
      # directly, or through an iallocator.
7256

    
7257
    self.all_nodes = [self.source_node, self.target_node]
7258
    self.nodes_ip = {
7259
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7260
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7261
      }
7262

    
7263
    if self.failover:
7264
      feedback_fn("Failover instance %s" % self.instance.name)
7265
      self._ExecFailover()
7266
    else:
7267
      feedback_fn("Migrating instance %s" % self.instance.name)
7268

    
7269
      if self.cleanup:
7270
        return self._ExecCleanup()
7271
      else:
7272
        return self._ExecMigration()
7273

    
7274

    
7275
def _CreateBlockDev(lu, node, instance, device, force_create,
7276
                    info, force_open):
7277
  """Create a tree of block devices on a given node.
7278

7279
  If this device type has to be created on secondaries, create it and
7280
  all its children.
7281

7282
  If not, just recurse to children keeping the same 'force' value.
7283

7284
  @param lu: the lu on whose behalf we execute
7285
  @param node: the node on which to create the device
7286
  @type instance: L{objects.Instance}
7287
  @param instance: the instance which owns the device
7288
  @type device: L{objects.Disk}
7289
  @param device: the device to create
7290
  @type force_create: boolean
7291
  @param force_create: whether to force creation of this device; this
7292
      will be change to True whenever we find a device which has
7293
      CreateOnSecondary() attribute
7294
  @param info: the extra 'metadata' we should attach to the device
7295
      (this will be represented as a LVM tag)
7296
  @type force_open: boolean
7297
  @param force_open: this parameter will be passes to the
7298
      L{backend.BlockdevCreate} function where it specifies
7299
      whether we run on primary or not, and it affects both
7300
      the child assembly and the device own Open() execution
7301

7302
  """
7303
  if device.CreateOnSecondary():
7304
    force_create = True
7305

    
7306
  if device.children:
7307
    for child in device.children:
7308
      _CreateBlockDev(lu, node, instance, child, force_create,
7309
                      info, force_open)
7310

    
7311
  if not force_create:
7312
    return
7313

    
7314
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7315

    
7316

    
7317
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7318
  """Create a single block device on a given node.
7319

7320
  This will not recurse over children of the device, so they must be
7321
  created in advance.
7322

7323
  @param lu: the lu on whose behalf we execute
7324
  @param node: the node on which to create the device
7325
  @type instance: L{objects.Instance}
7326
  @param instance: the instance which owns the device
7327
  @type device: L{objects.Disk}
7328
  @param device: the device to create
7329
  @param info: the extra 'metadata' we should attach to the device
7330
      (this will be represented as a LVM tag)
7331
  @type force_open: boolean
7332
  @param force_open: this parameter will be passes to the
7333
      L{backend.BlockdevCreate} function where it specifies
7334
      whether we run on primary or not, and it affects both
7335
      the child assembly and the device own Open() execution
7336

7337
  """
7338
  lu.cfg.SetDiskID(device, node)
7339
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7340
                                       instance.name, force_open, info)
7341
  result.Raise("Can't create block device %s on"
7342
               " node %s for instance %s" % (device, node, instance.name))
7343
  if device.physical_id is None:
7344
    device.physical_id = result.payload
7345

    
7346

    
7347
def _GenerateUniqueNames(lu, exts):
7348
  """Generate a suitable LV name.
7349

7350
  This will generate a logical volume name for the given instance.
7351

7352
  """
7353
  results = []
7354
  for val in exts:
7355
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7356
    results.append("%s%s" % (new_id, val))
7357
  return results
7358

    
7359

    
7360
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7361
                         iv_name, p_minor, s_minor):
7362
  """Generate a drbd8 device complete with its children.
7363

7364
  """
7365
  assert len(vgnames) == len(names) == 2
7366
  port = lu.cfg.AllocatePort()
7367
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7368
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7369
                          logical_id=(vgnames[0], names[0]))
7370
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7371
                          logical_id=(vgnames[1], names[1]))
7372
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7373
                          logical_id=(primary, secondary, port,
7374
                                      p_minor, s_minor,
7375
                                      shared_secret),
7376
                          children=[dev_data, dev_meta],
7377
                          iv_name=iv_name)
7378
  return drbd_dev
7379

    
7380

    
7381
def _GenerateDiskTemplate(lu, template_name,
7382
                          instance_name, primary_node,
7383
                          secondary_nodes, disk_info,
7384
                          file_storage_dir, file_driver,
7385
                          base_index, feedback_fn):
7386
  """Generate the entire disk layout for a given template type.
7387

7388
  """
7389
  #TODO: compute space requirements
7390

    
7391
  vgname = lu.cfg.GetVGName()
7392
  disk_count = len(disk_info)
7393
  disks = []
7394
  if template_name == constants.DT_DISKLESS:
7395
    pass
7396
  elif template_name == constants.DT_PLAIN:
7397
    if len(secondary_nodes) != 0:
7398
      raise errors.ProgrammerError("Wrong template configuration")
7399

    
7400
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7401
                                      for i in range(disk_count)])
7402
    for idx, disk in enumerate(disk_info):
7403
      disk_index = idx + base_index
7404
      vg = disk.get(constants.IDISK_VG, vgname)
7405
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7406
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7407
                              size=disk[constants.IDISK_SIZE],
7408
                              logical_id=(vg, names[idx]),
7409
                              iv_name="disk/%d" % disk_index,
7410
                              mode=disk[constants.IDISK_MODE])
7411
      disks.append(disk_dev)
7412
  elif template_name == constants.DT_DRBD8:
7413
    if len(secondary_nodes) != 1:
7414
      raise errors.ProgrammerError("Wrong template configuration")
7415
    remote_node = secondary_nodes[0]
7416
    minors = lu.cfg.AllocateDRBDMinor(
7417
      [primary_node, remote_node] * len(disk_info), instance_name)
7418

    
7419
    names = []
7420
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7421
                                               for i in range(disk_count)]):
7422
      names.append(lv_prefix + "_data")
7423
      names.append(lv_prefix + "_meta")
7424
    for idx, disk in enumerate(disk_info):
7425
      disk_index = idx + base_index
7426
      data_vg = disk.get(constants.IDISK_VG, vgname)
7427
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7428
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7429
                                      disk[constants.IDISK_SIZE],
7430
                                      [data_vg, meta_vg],
7431
                                      names[idx * 2:idx * 2 + 2],
7432
                                      "disk/%d" % disk_index,
7433
                                      minors[idx * 2], minors[idx * 2 + 1])
7434
      disk_dev.mode = disk[constants.IDISK_MODE]
7435
      disks.append(disk_dev)
7436
  elif template_name == constants.DT_FILE:
7437
    if len(secondary_nodes) != 0:
7438
      raise errors.ProgrammerError("Wrong template configuration")
7439

    
7440
    opcodes.RequireFileStorage()
7441

    
7442
    for idx, disk in enumerate(disk_info):
7443
      disk_index = idx + base_index
7444
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7445
                              size=disk[constants.IDISK_SIZE],
7446
                              iv_name="disk/%d" % disk_index,
7447
                              logical_id=(file_driver,
7448
                                          "%s/disk%d" % (file_storage_dir,
7449
                                                         disk_index)),
7450
                              mode=disk[constants.IDISK_MODE])
7451
      disks.append(disk_dev)
7452
  elif template_name == constants.DT_SHARED_FILE:
7453
    if len(secondary_nodes) != 0:
7454
      raise errors.ProgrammerError("Wrong template configuration")
7455

    
7456
    opcodes.RequireSharedFileStorage()
7457

    
7458
    for idx, disk in enumerate(disk_info):
7459
      disk_index = idx + base_index
7460
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7461
                              size=disk[constants.IDISK_SIZE],
7462
                              iv_name="disk/%d" % disk_index,
7463
                              logical_id=(file_driver,
7464
                                          "%s/disk%d" % (file_storage_dir,
7465
                                                         disk_index)),
7466
                              mode=disk[constants.IDISK_MODE])
7467
      disks.append(disk_dev)
7468
  elif template_name == constants.DT_BLOCK:
7469
    if len(secondary_nodes) != 0:
7470
      raise errors.ProgrammerError("Wrong template configuration")
7471

    
7472
    for idx, disk in enumerate(disk_info):
7473
      disk_index = idx + base_index
7474
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7475
                              size=disk[constants.IDISK_SIZE],
7476
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7477
                                          disk[constants.IDISK_ADOPT]),
7478
                              iv_name="disk/%d" % disk_index,
7479
                              mode=disk[constants.IDISK_MODE])
7480
      disks.append(disk_dev)
7481

    
7482
  else:
7483
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7484
  return disks
7485

    
7486

    
7487
def _GetInstanceInfoText(instance):
7488
  """Compute that text that should be added to the disk's metadata.
7489

7490
  """
7491
  return "originstname+%s" % instance.name
7492

    
7493

    
7494
def _CalcEta(time_taken, written, total_size):
7495
  """Calculates the ETA based on size written and total size.
7496

7497
  @param time_taken: The time taken so far
7498
  @param written: amount written so far
7499
  @param total_size: The total size of data to be written
7500
  @return: The remaining time in seconds
7501

7502
  """
7503
  avg_time = time_taken / float(written)
7504
  return (total_size - written) * avg_time
7505

    
7506

    
7507
def _WipeDisks(lu, instance):
7508
  """Wipes instance disks.
7509

7510
  @type lu: L{LogicalUnit}
7511
  @param lu: the logical unit on whose behalf we execute
7512
  @type instance: L{objects.Instance}
7513
  @param instance: the instance whose disks we should create
7514
  @return: the success of the wipe
7515

7516
  """
7517
  node = instance.primary_node
7518

    
7519
  for device in instance.disks:
7520
    lu.cfg.SetDiskID(device, node)
7521

    
7522
  logging.info("Pause sync of instance %s disks", instance.name)
7523
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7524

    
7525
  for idx, success in enumerate(result.payload):
7526
    if not success:
7527
      logging.warn("pause-sync of instance %s for disks %d failed",
7528
                   instance.name, idx)
7529

    
7530
  try:
7531
    for idx, device in enumerate(instance.disks):
7532
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7533
      # MAX_WIPE_CHUNK at max
7534
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7535
                            constants.MIN_WIPE_CHUNK_PERCENT)
7536
      # we _must_ make this an int, otherwise rounding errors will
7537
      # occur
7538
      wipe_chunk_size = int(wipe_chunk_size)
7539

    
7540
      lu.LogInfo("* Wiping disk %d", idx)
7541
      logging.info("Wiping disk %d for instance %s, node %s using"
7542
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7543

    
7544
      offset = 0
7545
      size = device.size
7546
      last_output = 0
7547
      start_time = time.time()
7548

    
7549
      while offset < size:
7550
        wipe_size = min(wipe_chunk_size, size - offset)
7551
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7552
                      idx, offset, wipe_size)
7553
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7554
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7555
                     (idx, offset, wipe_size))
7556
        now = time.time()
7557
        offset += wipe_size
7558
        if now - last_output >= 60:
7559
          eta = _CalcEta(now - start_time, offset, size)
7560
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7561
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7562
          last_output = now
7563
  finally:
7564
    logging.info("Resume sync of instance %s disks", instance.name)
7565

    
7566
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7567

    
7568
    for idx, success in enumerate(result.payload):
7569
      if not success:
7570
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7571
                      " look at the status and troubleshoot the issue", idx)
7572
        logging.warn("resume-sync of instance %s for disks %d failed",
7573
                     instance.name, idx)
7574

    
7575

    
7576
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7577
  """Create all disks for an instance.
7578

7579
  This abstracts away some work from AddInstance.
7580

7581
  @type lu: L{LogicalUnit}
7582
  @param lu: the logical unit on whose behalf we execute
7583
  @type instance: L{objects.Instance}
7584
  @param instance: the instance whose disks we should create
7585
  @type to_skip: list
7586
  @param to_skip: list of indices to skip
7587
  @type target_node: string
7588
  @param target_node: if passed, overrides the target node for creation
7589
  @rtype: boolean
7590
  @return: the success of the creation
7591

7592
  """
7593
  info = _GetInstanceInfoText(instance)
7594
  if target_node is None:
7595
    pnode = instance.primary_node
7596
    all_nodes = instance.all_nodes
7597
  else:
7598
    pnode = target_node
7599
    all_nodes = [pnode]
7600

    
7601
  if instance.disk_template in constants.DTS_FILEBASED:
7602
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7603
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7604

    
7605
    result.Raise("Failed to create directory '%s' on"
7606
                 " node %s" % (file_storage_dir, pnode))
7607

    
7608
  # Note: this needs to be kept in sync with adding of disks in
7609
  # LUInstanceSetParams
7610
  for idx, device in enumerate(instance.disks):
7611
    if to_skip and idx in to_skip:
7612
      continue
7613
    logging.info("Creating volume %s for instance %s",
7614
                 device.iv_name, instance.name)
7615
    #HARDCODE
7616
    for node in all_nodes:
7617
      f_create = node == pnode
7618
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7619

    
7620

    
7621
def _RemoveDisks(lu, instance, target_node=None):
7622
  """Remove all disks for an instance.
7623

7624
  This abstracts away some work from `AddInstance()` and
7625
  `RemoveInstance()`. Note that in case some of the devices couldn't
7626
  be removed, the removal will continue with the other ones (compare
7627
  with `_CreateDisks()`).
7628

7629
  @type lu: L{LogicalUnit}
7630
  @param lu: the logical unit on whose behalf we execute
7631
  @type instance: L{objects.Instance}
7632
  @param instance: the instance whose disks we should remove
7633
  @type target_node: string
7634
  @param target_node: used to override the node on which to remove the disks
7635
  @rtype: boolean
7636
  @return: the success of the removal
7637

7638
  """
7639
  logging.info("Removing block devices for instance %s", instance.name)
7640

    
7641
  all_result = True
7642
  for device in instance.disks:
7643
    if target_node:
7644
      edata = [(target_node, device)]
7645
    else:
7646
      edata = device.ComputeNodeTree(instance.primary_node)
7647
    for node, disk in edata:
7648
      lu.cfg.SetDiskID(disk, node)
7649
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7650
      if msg:
7651
        lu.LogWarning("Could not remove block device %s on node %s,"
7652
                      " continuing anyway: %s", device.iv_name, node, msg)
7653
        all_result = False
7654

    
7655
  if instance.disk_template == constants.DT_FILE:
7656
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7657
    if target_node:
7658
      tgt = target_node
7659
    else:
7660
      tgt = instance.primary_node
7661
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7662
    if result.fail_msg:
7663
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7664
                    file_storage_dir, instance.primary_node, result.fail_msg)
7665
      all_result = False
7666

    
7667
  return all_result
7668

    
7669

    
7670
def _ComputeDiskSizePerVG(disk_template, disks):
7671
  """Compute disk size requirements in the volume group
7672

7673
  """
7674
  def _compute(disks, payload):
7675
    """Universal algorithm.
7676

7677
    """
7678
    vgs = {}
7679
    for disk in disks:
7680
      vgs[disk[constants.IDISK_VG]] = \
7681
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7682

    
7683
    return vgs
7684

    
7685
  # Required free disk space as a function of disk and swap space
7686
  req_size_dict = {
7687
    constants.DT_DISKLESS: {},
7688
    constants.DT_PLAIN: _compute(disks, 0),
7689
    # 128 MB are added for drbd metadata for each disk
7690
    constants.DT_DRBD8: _compute(disks, 128),
7691
    constants.DT_FILE: {},
7692
    constants.DT_SHARED_FILE: {},
7693
  }
7694

    
7695
  if disk_template not in req_size_dict:
7696
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7697
                                 " is unknown" %  disk_template)
7698

    
7699
  return req_size_dict[disk_template]
7700

    
7701

    
7702
def _ComputeDiskSize(disk_template, disks):
7703
  """Compute disk size requirements in the volume group
7704

7705
  """
7706
  # Required free disk space as a function of disk and swap space
7707
  req_size_dict = {
7708
    constants.DT_DISKLESS: None,
7709
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7710
    # 128 MB are added for drbd metadata for each disk
7711
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7712
    constants.DT_FILE: None,
7713
    constants.DT_SHARED_FILE: 0,
7714
    constants.DT_BLOCK: 0,
7715
  }
7716

    
7717
  if disk_template not in req_size_dict:
7718
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7719
                                 " is unknown" %  disk_template)
7720

    
7721
  return req_size_dict[disk_template]
7722

    
7723

    
7724
def _FilterVmNodes(lu, nodenames):
7725
  """Filters out non-vm_capable nodes from a list.
7726

7727
  @type lu: L{LogicalUnit}
7728
  @param lu: the logical unit for which we check
7729
  @type nodenames: list
7730
  @param nodenames: the list of nodes on which we should check
7731
  @rtype: list
7732
  @return: the list of vm-capable nodes
7733

7734
  """
7735
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7736
  return [name for name in nodenames if name not in vm_nodes]
7737

    
7738

    
7739
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7740
  """Hypervisor parameter validation.
7741

7742
  This function abstract the hypervisor parameter validation to be
7743
  used in both instance create and instance modify.
7744

7745
  @type lu: L{LogicalUnit}
7746
  @param lu: the logical unit for which we check
7747
  @type nodenames: list
7748
  @param nodenames: the list of nodes on which we should check
7749
  @type hvname: string
7750
  @param hvname: the name of the hypervisor we should use
7751
  @type hvparams: dict
7752
  @param hvparams: the parameters which we need to check
7753
  @raise errors.OpPrereqError: if the parameters are not valid
7754

7755
  """
7756
  nodenames = _FilterVmNodes(lu, nodenames)
7757
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7758
                                                  hvname,
7759
                                                  hvparams)
7760
  for node in nodenames:
7761
    info = hvinfo[node]
7762
    if info.offline:
7763
      continue
7764
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7765

    
7766

    
7767
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7768
  """OS parameters validation.
7769

7770
  @type lu: L{LogicalUnit}
7771
  @param lu: the logical unit for which we check
7772
  @type required: boolean
7773
  @param required: whether the validation should fail if the OS is not
7774
      found
7775
  @type nodenames: list
7776
  @param nodenames: the list of nodes on which we should check
7777
  @type osname: string
7778
  @param osname: the name of the hypervisor we should use
7779
  @type osparams: dict
7780
  @param osparams: the parameters which we need to check
7781
  @raise errors.OpPrereqError: if the parameters are not valid
7782

7783
  """
7784
  nodenames = _FilterVmNodes(lu, nodenames)
7785
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7786
                                   [constants.OS_VALIDATE_PARAMETERS],
7787
                                   osparams)
7788
  for node, nres in result.items():
7789
    # we don't check for offline cases since this should be run only
7790
    # against the master node and/or an instance's nodes
7791
    nres.Raise("OS Parameters validation failed on node %s" % node)
7792
    if not nres.payload:
7793
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7794
                 osname, node)
7795

    
7796

    
7797
class LUInstanceCreate(LogicalUnit):
7798
  """Create an instance.
7799

7800
  """
7801
  HPATH = "instance-add"
7802
  HTYPE = constants.HTYPE_INSTANCE
7803
  REQ_BGL = False
7804

    
7805
  def CheckArguments(self):
7806
    """Check arguments.
7807

7808
    """
7809
    # do not require name_check to ease forward/backward compatibility
7810
    # for tools
7811
    if self.op.no_install and self.op.start:
7812
      self.LogInfo("No-installation mode selected, disabling startup")
7813
      self.op.start = False
7814
    # validate/normalize the instance name
7815
    self.op.instance_name = \
7816
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7817

    
7818
    if self.op.ip_check and not self.op.name_check:
7819
      # TODO: make the ip check more flexible and not depend on the name check
7820
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7821
                                 " check", errors.ECODE_INVAL)
7822

    
7823
    # check nics' parameter names
7824
    for nic in self.op.nics:
7825
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7826

    
7827
    # check disks. parameter names and consistent adopt/no-adopt strategy
7828
    has_adopt = has_no_adopt = False
7829
    for disk in self.op.disks:
7830
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7831
      if constants.IDISK_ADOPT in disk:
7832
        has_adopt = True
7833
      else:
7834
        has_no_adopt = True
7835
    if has_adopt and has_no_adopt:
7836
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7837
                                 errors.ECODE_INVAL)
7838
    if has_adopt:
7839
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7840
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7841
                                   " '%s' disk template" %
7842
                                   self.op.disk_template,
7843
                                   errors.ECODE_INVAL)
7844
      if self.op.iallocator is not None:
7845
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7846
                                   " iallocator script", errors.ECODE_INVAL)
7847
      if self.op.mode == constants.INSTANCE_IMPORT:
7848
        raise errors.OpPrereqError("Disk adoption not allowed for"
7849
                                   " instance import", errors.ECODE_INVAL)
7850
    else:
7851
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7852
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7853
                                   " but no 'adopt' parameter given" %
7854
                                   self.op.disk_template,
7855
                                   errors.ECODE_INVAL)
7856

    
7857
    self.adopt_disks = has_adopt
7858

    
7859
    # instance name verification
7860
    if self.op.name_check:
7861
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7862
      self.op.instance_name = self.hostname1.name
7863
      # used in CheckPrereq for ip ping check
7864
      self.check_ip = self.hostname1.ip
7865
    else:
7866
      self.check_ip = None
7867

    
7868
    # file storage checks
7869
    if (self.op.file_driver and
7870
        not self.op.file_driver in constants.FILE_DRIVER):
7871
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7872
                                 self.op.file_driver, errors.ECODE_INVAL)
7873

    
7874
    if self.op.disk_template == constants.DT_FILE:
7875
      opcodes.RequireFileStorage()
7876
    elif self.op.disk_template == constants.DT_SHARED_FILE:
7877
      opcodes.RequireSharedFileStorage()
7878

    
7879
    ### Node/iallocator related checks
7880
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7881

    
7882
    if self.op.pnode is not None:
7883
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7884
        if self.op.snode is None:
7885
          raise errors.OpPrereqError("The networked disk templates need"
7886
                                     " a mirror node", errors.ECODE_INVAL)
7887
      elif self.op.snode:
7888
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7889
                        " template")
7890
        self.op.snode = None
7891

    
7892
    self._cds = _GetClusterDomainSecret()
7893

    
7894
    if self.op.mode == constants.INSTANCE_IMPORT:
7895
      # On import force_variant must be True, because if we forced it at
7896
      # initial install, our only chance when importing it back is that it
7897
      # works again!
7898
      self.op.force_variant = True
7899

    
7900
      if self.op.no_install:
7901
        self.LogInfo("No-installation mode has no effect during import")
7902

    
7903
    elif self.op.mode == constants.INSTANCE_CREATE:
7904
      if self.op.os_type is None:
7905
        raise errors.OpPrereqError("No guest OS specified",
7906
                                   errors.ECODE_INVAL)
7907
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7908
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7909
                                   " installation" % self.op.os_type,
7910
                                   errors.ECODE_STATE)
7911
      if self.op.disk_template is None:
7912
        raise errors.OpPrereqError("No disk template specified",
7913
                                   errors.ECODE_INVAL)
7914

    
7915
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7916
      # Check handshake to ensure both clusters have the same domain secret
7917
      src_handshake = self.op.source_handshake
7918
      if not src_handshake:
7919
        raise errors.OpPrereqError("Missing source handshake",
7920
                                   errors.ECODE_INVAL)
7921

    
7922
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7923
                                                           src_handshake)
7924
      if errmsg:
7925
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7926
                                   errors.ECODE_INVAL)
7927

    
7928
      # Load and check source CA
7929
      self.source_x509_ca_pem = self.op.source_x509_ca
7930
      if not self.source_x509_ca_pem:
7931
        raise errors.OpPrereqError("Missing source X509 CA",
7932
                                   errors.ECODE_INVAL)
7933

    
7934
      try:
7935
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7936
                                                    self._cds)
7937
      except OpenSSL.crypto.Error, err:
7938
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7939
                                   (err, ), errors.ECODE_INVAL)
7940

    
7941
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7942
      if errcode is not None:
7943
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7944
                                   errors.ECODE_INVAL)
7945

    
7946
      self.source_x509_ca = cert
7947

    
7948
      src_instance_name = self.op.source_instance_name
7949
      if not src_instance_name:
7950
        raise errors.OpPrereqError("Missing source instance name",
7951
                                   errors.ECODE_INVAL)
7952

    
7953
      self.source_instance_name = \
7954
          netutils.GetHostname(name=src_instance_name).name
7955

    
7956
    else:
7957
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7958
                                 self.op.mode, errors.ECODE_INVAL)
7959

    
7960
  def ExpandNames(self):
7961
    """ExpandNames for CreateInstance.
7962

7963
    Figure out the right locks for instance creation.
7964

7965
    """
7966
    self.needed_locks = {}
7967

    
7968
    instance_name = self.op.instance_name
7969
    # this is just a preventive check, but someone might still add this
7970
    # instance in the meantime, and creation will fail at lock-add time
7971
    if instance_name in self.cfg.GetInstanceList():
7972
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7973
                                 instance_name, errors.ECODE_EXISTS)
7974

    
7975
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7976

    
7977
    if self.op.iallocator:
7978
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7979
    else:
7980
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7981
      nodelist = [self.op.pnode]
7982
      if self.op.snode is not None:
7983
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7984
        nodelist.append(self.op.snode)
7985
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7986

    
7987
    # in case of import lock the source node too
7988
    if self.op.mode == constants.INSTANCE_IMPORT:
7989
      src_node = self.op.src_node
7990
      src_path = self.op.src_path
7991

    
7992
      if src_path is None:
7993
        self.op.src_path = src_path = self.op.instance_name
7994

    
7995
      if src_node is None:
7996
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7997
        self.op.src_node = None
7998
        if os.path.isabs(src_path):
7999
          raise errors.OpPrereqError("Importing an instance from an absolute"
8000
                                     " path requires a source node option",
8001
                                     errors.ECODE_INVAL)
8002
      else:
8003
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
8004
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
8005
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
8006
        if not os.path.isabs(src_path):
8007
          self.op.src_path = src_path = \
8008
            utils.PathJoin(constants.EXPORT_DIR, src_path)
8009

    
8010
  def _RunAllocator(self):
8011
    """Run the allocator based on input opcode.
8012

8013
    """
8014
    nics = [n.ToDict() for n in self.nics]
8015
    ial = IAllocator(self.cfg, self.rpc,
8016
                     mode=constants.IALLOCATOR_MODE_ALLOC,
8017
                     name=self.op.instance_name,
8018
                     disk_template=self.op.disk_template,
8019
                     tags=self.op.tags,
8020
                     os=self.op.os_type,
8021
                     vcpus=self.be_full[constants.BE_VCPUS],
8022
                     memory=self.be_full[constants.BE_MEMORY],
8023
                     disks=self.disks,
8024
                     nics=nics,
8025
                     hypervisor=self.op.hypervisor,
8026
                     )
8027

    
8028
    ial.Run(self.op.iallocator)
8029

    
8030
    if not ial.success:
8031
      raise errors.OpPrereqError("Can't compute nodes using"
8032
                                 " iallocator '%s': %s" %
8033
                                 (self.op.iallocator, ial.info),
8034
                                 errors.ECODE_NORES)
8035
    if len(ial.result) != ial.required_nodes:
8036
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8037
                                 " of nodes (%s), required %s" %
8038
                                 (self.op.iallocator, len(ial.result),
8039
                                  ial.required_nodes), errors.ECODE_FAULT)
8040
    self.op.pnode = ial.result[0]
8041
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8042
                 self.op.instance_name, self.op.iallocator,
8043
                 utils.CommaJoin(ial.result))
8044
    if ial.required_nodes == 2:
8045
      self.op.snode = ial.result[1]
8046

    
8047
  def BuildHooksEnv(self):
8048
    """Build hooks env.
8049

8050
    This runs on master, primary and secondary nodes of the instance.
8051

8052
    """
8053
    env = {
8054
      "ADD_MODE": self.op.mode,
8055
      }
8056
    if self.op.mode == constants.INSTANCE_IMPORT:
8057
      env["SRC_NODE"] = self.op.src_node
8058
      env["SRC_PATH"] = self.op.src_path
8059
      env["SRC_IMAGES"] = self.src_images
8060

    
8061
    env.update(_BuildInstanceHookEnv(
8062
      name=self.op.instance_name,
8063
      primary_node=self.op.pnode,
8064
      secondary_nodes=self.secondaries,
8065
      status=self.op.start,
8066
      os_type=self.op.os_type,
8067
      memory=self.be_full[constants.BE_MEMORY],
8068
      vcpus=self.be_full[constants.BE_VCPUS],
8069
      nics=_NICListToTuple(self, self.nics),
8070
      disk_template=self.op.disk_template,
8071
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8072
             for d in self.disks],
8073
      bep=self.be_full,
8074
      hvp=self.hv_full,
8075
      hypervisor_name=self.op.hypervisor,
8076
      tags=self.op.tags,
8077
    ))
8078

    
8079
    return env
8080

    
8081
  def BuildHooksNodes(self):
8082
    """Build hooks nodes.
8083

8084
    """
8085
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8086
    return nl, nl
8087

    
8088
  def _ReadExportInfo(self):
8089
    """Reads the export information from disk.
8090

8091
    It will override the opcode source node and path with the actual
8092
    information, if these two were not specified before.
8093

8094
    @return: the export information
8095

8096
    """
8097
    assert self.op.mode == constants.INSTANCE_IMPORT
8098

    
8099
    src_node = self.op.src_node
8100
    src_path = self.op.src_path
8101

    
8102
    if src_node is None:
8103
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
8104
      exp_list = self.rpc.call_export_list(locked_nodes)
8105
      found = False
8106
      for node in exp_list:
8107
        if exp_list[node].fail_msg:
8108
          continue
8109
        if src_path in exp_list[node].payload:
8110
          found = True
8111
          self.op.src_node = src_node = node
8112
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8113
                                                       src_path)
8114
          break
8115
      if not found:
8116
        raise errors.OpPrereqError("No export found for relative path %s" %
8117
                                    src_path, errors.ECODE_INVAL)
8118

    
8119
    _CheckNodeOnline(self, src_node)
8120
    result = self.rpc.call_export_info(src_node, src_path)
8121
    result.Raise("No export or invalid export found in dir %s" % src_path)
8122

    
8123
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8124
    if not export_info.has_section(constants.INISECT_EXP):
8125
      raise errors.ProgrammerError("Corrupted export config",
8126
                                   errors.ECODE_ENVIRON)
8127

    
8128
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8129
    if (int(ei_version) != constants.EXPORT_VERSION):
8130
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8131
                                 (ei_version, constants.EXPORT_VERSION),
8132
                                 errors.ECODE_ENVIRON)
8133
    return export_info
8134

    
8135
  def _ReadExportParams(self, einfo):
8136
    """Use export parameters as defaults.
8137

8138
    In case the opcode doesn't specify (as in override) some instance
8139
    parameters, then try to use them from the export information, if
8140
    that declares them.
8141

8142
    """
8143
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8144

    
8145
    if self.op.disk_template is None:
8146
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8147
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8148
                                          "disk_template")
8149
      else:
8150
        raise errors.OpPrereqError("No disk template specified and the export"
8151
                                   " is missing the disk_template information",
8152
                                   errors.ECODE_INVAL)
8153

    
8154
    if not self.op.disks:
8155
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
8156
        disks = []
8157
        # TODO: import the disk iv_name too
8158
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8159
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8160
          disks.append({constants.IDISK_SIZE: disk_sz})
8161
        self.op.disks = disks
8162
      else:
8163
        raise errors.OpPrereqError("No disk info specified and the export"
8164
                                   " is missing the disk information",
8165
                                   errors.ECODE_INVAL)
8166

    
8167
    if (not self.op.nics and
8168
        einfo.has_option(constants.INISECT_INS, "nic_count")):
8169
      nics = []
8170
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8171
        ndict = {}
8172
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8173
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8174
          ndict[name] = v
8175
        nics.append(ndict)
8176
      self.op.nics = nics
8177

    
8178
    if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
8179
      self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
8180

    
8181
    if (self.op.hypervisor is None and
8182
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
8183
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8184

    
8185
    if einfo.has_section(constants.INISECT_HYP):
8186
      # use the export parameters but do not override the ones
8187
      # specified by the user
8188
      for name, value in einfo.items(constants.INISECT_HYP):
8189
        if name not in self.op.hvparams:
8190
          self.op.hvparams[name] = value
8191

    
8192
    if einfo.has_section(constants.INISECT_BEP):
8193
      # use the parameters, without overriding
8194
      for name, value in einfo.items(constants.INISECT_BEP):
8195
        if name not in self.op.beparams:
8196
          self.op.beparams[name] = value
8197
    else:
8198
      # try to read the parameters old style, from the main section
8199
      for name in constants.BES_PARAMETERS:
8200
        if (name not in self.op.beparams and
8201
            einfo.has_option(constants.INISECT_INS, name)):
8202
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8203

    
8204
    if einfo.has_section(constants.INISECT_OSP):
8205
      # use the parameters, without overriding
8206
      for name, value in einfo.items(constants.INISECT_OSP):
8207
        if name not in self.op.osparams:
8208
          self.op.osparams[name] = value
8209

    
8210
  def _RevertToDefaults(self, cluster):
8211
    """Revert the instance parameters to the default values.
8212

8213
    """
8214
    # hvparams
8215
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8216
    for name in self.op.hvparams.keys():
8217
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8218
        del self.op.hvparams[name]
8219
    # beparams
8220
    be_defs = cluster.SimpleFillBE({})
8221
    for name in self.op.beparams.keys():
8222
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8223
        del self.op.beparams[name]
8224
    # nic params
8225
    nic_defs = cluster.SimpleFillNIC({})
8226
    for nic in self.op.nics:
8227
      for name in constants.NICS_PARAMETERS:
8228
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8229
          del nic[name]
8230
    # osparams
8231
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8232
    for name in self.op.osparams.keys():
8233
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8234
        del self.op.osparams[name]
8235

    
8236
  def _CalculateFileStorageDir(self):
8237
    """Calculate final instance file storage dir.
8238

8239
    """
8240
    # file storage dir calculation/check
8241
    self.instance_file_storage_dir = None
8242
    if self.op.disk_template in constants.DTS_FILEBASED:
8243
      # build the full file storage dir path
8244
      joinargs = []
8245

    
8246
      if self.op.disk_template == constants.DT_SHARED_FILE:
8247
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8248
      else:
8249
        get_fsd_fn = self.cfg.GetFileStorageDir
8250

    
8251
      cfg_storagedir = get_fsd_fn()
8252
      if not cfg_storagedir:
8253
        raise errors.OpPrereqError("Cluster file storage dir not defined")
8254
      joinargs.append(cfg_storagedir)
8255

    
8256
      if self.op.file_storage_dir is not None:
8257
        joinargs.append(self.op.file_storage_dir)
8258

    
8259
      joinargs.append(self.op.instance_name)
8260

    
8261
      # pylint: disable-msg=W0142
8262
      self.instance_file_storage_dir = utils.PathJoin(*joinargs)
8263

    
8264
  def CheckPrereq(self):
8265
    """Check prerequisites.
8266

8267
    """
8268
    self._CalculateFileStorageDir()
8269

    
8270
    if self.op.mode == constants.INSTANCE_IMPORT:
8271
      export_info = self._ReadExportInfo()
8272
      self._ReadExportParams(export_info)
8273

    
8274
    if (not self.cfg.GetVGName() and
8275
        self.op.disk_template not in constants.DTS_NOT_LVM):
8276
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8277
                                 " instances", errors.ECODE_STATE)
8278

    
8279
    if self.op.hypervisor is None:
8280
      self.op.hypervisor = self.cfg.GetHypervisorType()
8281

    
8282
    cluster = self.cfg.GetClusterInfo()
8283
    enabled_hvs = cluster.enabled_hypervisors
8284
    if self.op.hypervisor not in enabled_hvs:
8285
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8286
                                 " cluster (%s)" % (self.op.hypervisor,
8287
                                  ",".join(enabled_hvs)),
8288
                                 errors.ECODE_STATE)
8289

    
8290
    # Check tag validity
8291
    for tag in self.op.tags:
8292
      objects.TaggableObject.ValidateTag(tag)
8293

    
8294
    # check hypervisor parameter syntax (locally)
8295
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8296
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8297
                                      self.op.hvparams)
8298
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8299
    hv_type.CheckParameterSyntax(filled_hvp)
8300
    self.hv_full = filled_hvp
8301
    # check that we don't specify global parameters on an instance
8302
    _CheckGlobalHvParams(self.op.hvparams)
8303

    
8304
    # fill and remember the beparams dict
8305
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8306
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8307

    
8308
    # build os parameters
8309
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8310

    
8311
    # now that hvp/bep are in final format, let's reset to defaults,
8312
    # if told to do so
8313
    if self.op.identify_defaults:
8314
      self._RevertToDefaults(cluster)
8315

    
8316
    # NIC buildup
8317
    self.nics = []
8318
    for idx, nic in enumerate(self.op.nics):
8319
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8320
      nic_mode = nic_mode_req
8321
      if nic_mode is None:
8322
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8323

    
8324
      # in routed mode, for the first nic, the default ip is 'auto'
8325
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8326
        default_ip_mode = constants.VALUE_AUTO
8327
      else:
8328
        default_ip_mode = constants.VALUE_NONE
8329

    
8330
      # ip validity checks
8331
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8332
      if ip is None or ip.lower() == constants.VALUE_NONE:
8333
        nic_ip = None
8334
      elif ip.lower() == constants.VALUE_AUTO:
8335
        if not self.op.name_check:
8336
          raise errors.OpPrereqError("IP address set to auto but name checks"
8337
                                     " have been skipped",
8338
                                     errors.ECODE_INVAL)
8339
        nic_ip = self.hostname1.ip
8340
      else:
8341
        if not netutils.IPAddress.IsValid(ip):
8342
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8343
                                     errors.ECODE_INVAL)
8344
        nic_ip = ip
8345

    
8346
      # TODO: check the ip address for uniqueness
8347
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8348
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8349
                                   errors.ECODE_INVAL)
8350

    
8351
      # MAC address verification
8352
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8353
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8354
        mac = utils.NormalizeAndValidateMac(mac)
8355

    
8356
        try:
8357
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8358
        except errors.ReservationError:
8359
          raise errors.OpPrereqError("MAC address %s already in use"
8360
                                     " in cluster" % mac,
8361
                                     errors.ECODE_NOTUNIQUE)
8362

    
8363
      #  Build nic parameters
8364
      link = nic.get(constants.INIC_LINK, None)
8365
      nicparams = {}
8366
      if nic_mode_req:
8367
        nicparams[constants.NIC_MODE] = nic_mode_req
8368
      if link:
8369
        nicparams[constants.NIC_LINK] = link
8370

    
8371
      check_params = cluster.SimpleFillNIC(nicparams)
8372
      objects.NIC.CheckParameterSyntax(check_params)
8373
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8374

    
8375
    # disk checks/pre-build
8376
    default_vg = self.cfg.GetVGName()
8377
    self.disks = []
8378
    for disk in self.op.disks:
8379
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8380
      if mode not in constants.DISK_ACCESS_SET:
8381
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8382
                                   mode, errors.ECODE_INVAL)
8383
      size = disk.get(constants.IDISK_SIZE, None)
8384
      if size is None:
8385
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8386
      try:
8387
        size = int(size)
8388
      except (TypeError, ValueError):
8389
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8390
                                   errors.ECODE_INVAL)
8391

    
8392
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8393
      new_disk = {
8394
        constants.IDISK_SIZE: size,
8395
        constants.IDISK_MODE: mode,
8396
        constants.IDISK_VG: data_vg,
8397
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8398
        }
8399
      if constants.IDISK_ADOPT in disk:
8400
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8401
      self.disks.append(new_disk)
8402

    
8403
    if self.op.mode == constants.INSTANCE_IMPORT:
8404

    
8405
      # Check that the new instance doesn't have less disks than the export
8406
      instance_disks = len(self.disks)
8407
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8408
      if instance_disks < export_disks:
8409
        raise errors.OpPrereqError("Not enough disks to import."
8410
                                   " (instance: %d, export: %d)" %
8411
                                   (instance_disks, export_disks),
8412
                                   errors.ECODE_INVAL)
8413

    
8414
      disk_images = []
8415
      for idx in range(export_disks):
8416
        option = 'disk%d_dump' % idx
8417
        if export_info.has_option(constants.INISECT_INS, option):
8418
          # FIXME: are the old os-es, disk sizes, etc. useful?
8419
          export_name = export_info.get(constants.INISECT_INS, option)
8420
          image = utils.PathJoin(self.op.src_path, export_name)
8421
          disk_images.append(image)
8422
        else:
8423
          disk_images.append(False)
8424

    
8425
      self.src_images = disk_images
8426

    
8427
      old_name = export_info.get(constants.INISECT_INS, 'name')
8428
      try:
8429
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8430
      except (TypeError, ValueError), err:
8431
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8432
                                   " an integer: %s" % str(err),
8433
                                   errors.ECODE_STATE)
8434
      if self.op.instance_name == old_name:
8435
        for idx, nic in enumerate(self.nics):
8436
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8437
            nic_mac_ini = 'nic%d_mac' % idx
8438
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8439

    
8440
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8441

    
8442
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8443
    if self.op.ip_check:
8444
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8445
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8446
                                   (self.check_ip, self.op.instance_name),
8447
                                   errors.ECODE_NOTUNIQUE)
8448

    
8449
    #### mac address generation
8450
    # By generating here the mac address both the allocator and the hooks get
8451
    # the real final mac address rather than the 'auto' or 'generate' value.
8452
    # There is a race condition between the generation and the instance object
8453
    # creation, which means that we know the mac is valid now, but we're not
8454
    # sure it will be when we actually add the instance. If things go bad
8455
    # adding the instance will abort because of a duplicate mac, and the
8456
    # creation job will fail.
8457
    for nic in self.nics:
8458
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8459
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8460

    
8461
    #### allocator run
8462

    
8463
    if self.op.iallocator is not None:
8464
      self._RunAllocator()
8465

    
8466
    #### node related checks
8467

    
8468
    # check primary node
8469
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8470
    assert self.pnode is not None, \
8471
      "Cannot retrieve locked node %s" % self.op.pnode
8472
    if pnode.offline:
8473
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8474
                                 pnode.name, errors.ECODE_STATE)
8475
    if pnode.drained:
8476
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8477
                                 pnode.name, errors.ECODE_STATE)
8478
    if not pnode.vm_capable:
8479
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8480
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8481

    
8482
    self.secondaries = []
8483

    
8484
    # mirror node verification
8485
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8486
      if self.op.snode == pnode.name:
8487
        raise errors.OpPrereqError("The secondary node cannot be the"
8488
                                   " primary node", errors.ECODE_INVAL)
8489
      _CheckNodeOnline(self, self.op.snode)
8490
      _CheckNodeNotDrained(self, self.op.snode)
8491
      _CheckNodeVmCapable(self, self.op.snode)
8492
      self.secondaries.append(self.op.snode)
8493

    
8494
    nodenames = [pnode.name] + self.secondaries
8495

    
8496
    if not self.adopt_disks:
8497
      # Check lv size requirements, if not adopting
8498
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8499
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8500

    
8501
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8502
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8503
                                disk[constants.IDISK_ADOPT])
8504
                     for disk in self.disks])
8505
      if len(all_lvs) != len(self.disks):
8506
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8507
                                   errors.ECODE_INVAL)
8508
      for lv_name in all_lvs:
8509
        try:
8510
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8511
          # to ReserveLV uses the same syntax
8512
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8513
        except errors.ReservationError:
8514
          raise errors.OpPrereqError("LV named %s used by another instance" %
8515
                                     lv_name, errors.ECODE_NOTUNIQUE)
8516

    
8517
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8518
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8519

    
8520
      node_lvs = self.rpc.call_lv_list([pnode.name],
8521
                                       vg_names.payload.keys())[pnode.name]
8522
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8523
      node_lvs = node_lvs.payload
8524

    
8525
      delta = all_lvs.difference(node_lvs.keys())
8526
      if delta:
8527
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8528
                                   utils.CommaJoin(delta),
8529
                                   errors.ECODE_INVAL)
8530
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8531
      if online_lvs:
8532
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8533
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8534
                                   errors.ECODE_STATE)
8535
      # update the size of disk based on what is found
8536
      for dsk in self.disks:
8537
        dsk[constants.IDISK_SIZE] = \
8538
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8539
                                        dsk[constants.IDISK_ADOPT])][0]))
8540

    
8541
    elif self.op.disk_template == constants.DT_BLOCK:
8542
      # Normalize and de-duplicate device paths
8543
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8544
                       for disk in self.disks])
8545
      if len(all_disks) != len(self.disks):
8546
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8547
                                   errors.ECODE_INVAL)
8548
      baddisks = [d for d in all_disks
8549
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8550
      if baddisks:
8551
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8552
                                   " cannot be adopted" %
8553
                                   (", ".join(baddisks),
8554
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8555
                                   errors.ECODE_INVAL)
8556

    
8557
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8558
                                            list(all_disks))[pnode.name]
8559
      node_disks.Raise("Cannot get block device information from node %s" %
8560
                       pnode.name)
8561
      node_disks = node_disks.payload
8562
      delta = all_disks.difference(node_disks.keys())
8563
      if delta:
8564
        raise errors.OpPrereqError("Missing block device(s): %s" %
8565
                                   utils.CommaJoin(delta),
8566
                                   errors.ECODE_INVAL)
8567
      for dsk in self.disks:
8568
        dsk[constants.IDISK_SIZE] = \
8569
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8570

    
8571
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8572

    
8573
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8574
    # check OS parameters (remotely)
8575
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8576

    
8577
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8578

    
8579
    # memory check on primary node
8580
    if self.op.start:
8581
      _CheckNodeFreeMemory(self, self.pnode.name,
8582
                           "creating instance %s" % self.op.instance_name,
8583
                           self.be_full[constants.BE_MEMORY],
8584
                           self.op.hypervisor)
8585

    
8586
    self.dry_run_result = list(nodenames)
8587

    
8588
  def Exec(self, feedback_fn):
8589
    """Create and add the instance to the cluster.
8590

8591
    """
8592
    instance = self.op.instance_name
8593
    pnode_name = self.pnode.name
8594

    
8595
    ht_kind = self.op.hypervisor
8596
    if ht_kind in constants.HTS_REQ_PORT:
8597
      network_port = self.cfg.AllocatePort()
8598
    else:
8599
      network_port = None
8600

    
8601
    disks = _GenerateDiskTemplate(self,
8602
                                  self.op.disk_template,
8603
                                  instance, pnode_name,
8604
                                  self.secondaries,
8605
                                  self.disks,
8606
                                  self.instance_file_storage_dir,
8607
                                  self.op.file_driver,
8608
                                  0,
8609
                                  feedback_fn)
8610

    
8611
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8612
                            primary_node=pnode_name,
8613
                            nics=self.nics, disks=disks,
8614
                            disk_template=self.op.disk_template,
8615
                            admin_up=False,
8616
                            network_port=network_port,
8617
                            beparams=self.op.beparams,
8618
                            hvparams=self.op.hvparams,
8619
                            hypervisor=self.op.hypervisor,
8620
                            osparams=self.op.osparams,
8621
                            )
8622

    
8623
    if self.op.tags:
8624
      for tag in self.op.tags:
8625
        iobj.AddTag(tag)
8626

    
8627
    if self.adopt_disks:
8628
      if self.op.disk_template == constants.DT_PLAIN:
8629
        # rename LVs to the newly-generated names; we need to construct
8630
        # 'fake' LV disks with the old data, plus the new unique_id
8631
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8632
        rename_to = []
8633
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8634
          rename_to.append(t_dsk.logical_id)
8635
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8636
          self.cfg.SetDiskID(t_dsk, pnode_name)
8637
        result = self.rpc.call_blockdev_rename(pnode_name,
8638
                                               zip(tmp_disks, rename_to))
8639
        result.Raise("Failed to rename adoped LVs")
8640
    else:
8641
      feedback_fn("* creating instance disks...")
8642
      try:
8643
        _CreateDisks(self, iobj)
8644
      except errors.OpExecError:
8645
        self.LogWarning("Device creation failed, reverting...")
8646
        try:
8647
          _RemoveDisks(self, iobj)
8648
        finally:
8649
          self.cfg.ReleaseDRBDMinors(instance)
8650
          raise
8651

    
8652
    feedback_fn("adding instance %s to cluster config" % instance)
8653

    
8654
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8655

    
8656
    # Declare that we don't want to remove the instance lock anymore, as we've
8657
    # added the instance to the config
8658
    del self.remove_locks[locking.LEVEL_INSTANCE]
8659

    
8660
    if self.op.mode == constants.INSTANCE_IMPORT:
8661
      # Release unused nodes
8662
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8663
    else:
8664
      # Release all nodes
8665
      _ReleaseLocks(self, locking.LEVEL_NODE)
8666

    
8667
    disk_abort = False
8668
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8669
      feedback_fn("* wiping instance disks...")
8670
      try:
8671
        _WipeDisks(self, iobj)
8672
      except errors.OpExecError, err:
8673
        logging.exception("Wiping disks failed")
8674
        self.LogWarning("Wiping instance disks failed (%s)", err)
8675
        disk_abort = True
8676

    
8677
    if disk_abort:
8678
      # Something is already wrong with the disks, don't do anything else
8679
      pass
8680
    elif self.op.wait_for_sync:
8681
      disk_abort = not _WaitForSync(self, iobj)
8682
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8683
      # make sure the disks are not degraded (still sync-ing is ok)
8684
      time.sleep(15)
8685
      feedback_fn("* checking mirrors status")
8686
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8687
    else:
8688
      disk_abort = False
8689

    
8690
    if disk_abort:
8691
      _RemoveDisks(self, iobj)
8692
      self.cfg.RemoveInstance(iobj.name)
8693
      # Make sure the instance lock gets removed
8694
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8695
      raise errors.OpExecError("There are some degraded disks for"
8696
                               " this instance")
8697

    
8698
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8699
      if self.op.mode == constants.INSTANCE_CREATE:
8700
        if not self.op.no_install:
8701
          feedback_fn("* running the instance OS create scripts...")
8702
          # FIXME: pass debug option from opcode to backend
8703
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8704
                                                 self.op.debug_level)
8705
          result.Raise("Could not add os for instance %s"
8706
                       " on node %s" % (instance, pnode_name))
8707

    
8708
      elif self.op.mode == constants.INSTANCE_IMPORT:
8709
        feedback_fn("* running the instance OS import scripts...")
8710

    
8711
        transfers = []
8712

    
8713
        for idx, image in enumerate(self.src_images):
8714
          if not image:
8715
            continue
8716

    
8717
          # FIXME: pass debug option from opcode to backend
8718
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8719
                                             constants.IEIO_FILE, (image, ),
8720
                                             constants.IEIO_SCRIPT,
8721
                                             (iobj.disks[idx], idx),
8722
                                             None)
8723
          transfers.append(dt)
8724

    
8725
        import_result = \
8726
          masterd.instance.TransferInstanceData(self, feedback_fn,
8727
                                                self.op.src_node, pnode_name,
8728
                                                self.pnode.secondary_ip,
8729
                                                iobj, transfers)
8730
        if not compat.all(import_result):
8731
          self.LogWarning("Some disks for instance %s on node %s were not"
8732
                          " imported successfully" % (instance, pnode_name))
8733

    
8734
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8735
        feedback_fn("* preparing remote import...")
8736
        # The source cluster will stop the instance before attempting to make a
8737
        # connection. In some cases stopping an instance can take a long time,
8738
        # hence the shutdown timeout is added to the connection timeout.
8739
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8740
                           self.op.source_shutdown_timeout)
8741
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8742

    
8743
        assert iobj.primary_node == self.pnode.name
8744
        disk_results = \
8745
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8746
                                        self.source_x509_ca,
8747
                                        self._cds, timeouts)
8748
        if not compat.all(disk_results):
8749
          # TODO: Should the instance still be started, even if some disks
8750
          # failed to import (valid for local imports, too)?
8751
          self.LogWarning("Some disks for instance %s on node %s were not"
8752
                          " imported successfully" % (instance, pnode_name))
8753

    
8754
        # Run rename script on newly imported instance
8755
        assert iobj.name == instance
8756
        feedback_fn("Running rename script for %s" % instance)
8757
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8758
                                                   self.source_instance_name,
8759
                                                   self.op.debug_level)
8760
        if result.fail_msg:
8761
          self.LogWarning("Failed to run rename script for %s on node"
8762
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8763

    
8764
      else:
8765
        # also checked in the prereq part
8766
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8767
                                     % self.op.mode)
8768

    
8769
    if self.op.start:
8770
      iobj.admin_up = True
8771
      self.cfg.Update(iobj, feedback_fn)
8772
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8773
      feedback_fn("* starting instance...")
8774
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8775
      result.Raise("Could not start instance")
8776

    
8777
    return list(iobj.all_nodes)
8778

    
8779

    
8780
class LUInstanceConsole(NoHooksLU):
8781
  """Connect to an instance's console.
8782

8783
  This is somewhat special in that it returns the command line that
8784
  you need to run on the master node in order to connect to the
8785
  console.
8786

8787
  """
8788
  REQ_BGL = False
8789

    
8790
  def ExpandNames(self):
8791
    self._ExpandAndLockInstance()
8792

    
8793
  def CheckPrereq(self):
8794
    """Check prerequisites.
8795

8796
    This checks that the instance is in the cluster.
8797

8798
    """
8799
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8800
    assert self.instance is not None, \
8801
      "Cannot retrieve locked instance %s" % self.op.instance_name
8802
    _CheckNodeOnline(self, self.instance.primary_node)
8803

    
8804
  def Exec(self, feedback_fn):
8805
    """Connect to the console of an instance
8806

8807
    """
8808
    instance = self.instance
8809
    node = instance.primary_node
8810

    
8811
    node_insts = self.rpc.call_instance_list([node],
8812
                                             [instance.hypervisor])[node]
8813
    node_insts.Raise("Can't get node information from %s" % node)
8814

    
8815
    if instance.name not in node_insts.payload:
8816
      if instance.admin_up:
8817
        state = constants.INSTST_ERRORDOWN
8818
      else:
8819
        state = constants.INSTST_ADMINDOWN
8820
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8821
                               (instance.name, state))
8822

    
8823
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8824

    
8825
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8826

    
8827

    
8828
def _GetInstanceConsole(cluster, instance):
8829
  """Returns console information for an instance.
8830

8831
  @type cluster: L{objects.Cluster}
8832
  @type instance: L{objects.Instance}
8833
  @rtype: dict
8834

8835
  """
8836
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8837
  # beparams and hvparams are passed separately, to avoid editing the
8838
  # instance and then saving the defaults in the instance itself.
8839
  hvparams = cluster.FillHV(instance)
8840
  beparams = cluster.FillBE(instance)
8841
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8842

    
8843
  assert console.instance == instance.name
8844
  assert console.Validate()
8845

    
8846
  return console.ToDict()
8847

    
8848

    
8849
class LUInstanceReplaceDisks(LogicalUnit):
8850
  """Replace the disks of an instance.
8851

8852
  """
8853
  HPATH = "mirrors-replace"
8854
  HTYPE = constants.HTYPE_INSTANCE
8855
  REQ_BGL = False
8856

    
8857
  def CheckArguments(self):
8858
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8859
                                  self.op.iallocator)
8860

    
8861
  def ExpandNames(self):
8862
    self._ExpandAndLockInstance()
8863

    
8864
    assert locking.LEVEL_NODE not in self.needed_locks
8865
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8866

    
8867
    assert self.op.iallocator is None or self.op.remote_node is None, \
8868
      "Conflicting options"
8869

    
8870
    if self.op.remote_node is not None:
8871
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8872

    
8873
      # Warning: do not remove the locking of the new secondary here
8874
      # unless DRBD8.AddChildren is changed to work in parallel;
8875
      # currently it doesn't since parallel invocations of
8876
      # FindUnusedMinor will conflict
8877
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8878
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8879
    else:
8880
      self.needed_locks[locking.LEVEL_NODE] = []
8881
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8882

    
8883
      if self.op.iallocator is not None:
8884
        # iallocator will select a new node in the same group
8885
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8886

    
8887
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8888
                                   self.op.iallocator, self.op.remote_node,
8889
                                   self.op.disks, False, self.op.early_release)
8890

    
8891
    self.tasklets = [self.replacer]
8892

    
8893
  def DeclareLocks(self, level):
8894
    if level == locking.LEVEL_NODEGROUP:
8895
      assert self.op.remote_node is None
8896
      assert self.op.iallocator is not None
8897
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8898

    
8899
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8900
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8901
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8902

    
8903
    elif level == locking.LEVEL_NODE:
8904
      if self.op.iallocator is not None:
8905
        assert self.op.remote_node is None
8906
        assert not self.needed_locks[locking.LEVEL_NODE]
8907

    
8908
        # Lock member nodes of all locked groups
8909
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8910
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8911
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8912
      else:
8913
        self._LockInstancesNodes()
8914

    
8915
  def BuildHooksEnv(self):
8916
    """Build hooks env.
8917

8918
    This runs on the master, the primary and all the secondaries.
8919

8920
    """
8921
    instance = self.replacer.instance
8922
    env = {
8923
      "MODE": self.op.mode,
8924
      "NEW_SECONDARY": self.op.remote_node,
8925
      "OLD_SECONDARY": instance.secondary_nodes[0],
8926
      }
8927
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8928
    return env
8929

    
8930
  def BuildHooksNodes(self):
8931
    """Build hooks nodes.
8932

8933
    """
8934
    instance = self.replacer.instance
8935
    nl = [
8936
      self.cfg.GetMasterNode(),
8937
      instance.primary_node,
8938
      ]
8939
    if self.op.remote_node is not None:
8940
      nl.append(self.op.remote_node)
8941
    return nl, nl
8942

    
8943
  def CheckPrereq(self):
8944
    """Check prerequisites.
8945

8946
    """
8947
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8948
            self.op.iallocator is None)
8949

    
8950
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8951
    if owned_groups:
8952
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8953
      if owned_groups != groups:
8954
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8955
                                 " since lock was acquired, current list is %r,"
8956
                                 " used to be '%s'" %
8957
                                 (self.op.instance_name,
8958
                                  utils.CommaJoin(groups),
8959
                                  utils.CommaJoin(owned_groups)))
8960

    
8961
    return LogicalUnit.CheckPrereq(self)
8962

    
8963

    
8964
class TLReplaceDisks(Tasklet):
8965
  """Replaces disks for an instance.
8966

8967
  Note: Locking is not within the scope of this class.
8968

8969
  """
8970
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8971
               disks, delay_iallocator, early_release):
8972
    """Initializes this class.
8973

8974
    """
8975
    Tasklet.__init__(self, lu)
8976

    
8977
    # Parameters
8978
    self.instance_name = instance_name
8979
    self.mode = mode
8980
    self.iallocator_name = iallocator_name
8981
    self.remote_node = remote_node
8982
    self.disks = disks
8983
    self.delay_iallocator = delay_iallocator
8984
    self.early_release = early_release
8985

    
8986
    # Runtime data
8987
    self.instance = None
8988
    self.new_node = None
8989
    self.target_node = None
8990
    self.other_node = None
8991
    self.remote_node_info = None
8992
    self.node_secondary_ip = None
8993

    
8994
  @staticmethod
8995
  def CheckArguments(mode, remote_node, iallocator):
8996
    """Helper function for users of this class.
8997

8998
    """
8999
    # check for valid parameter combination
9000
    if mode == constants.REPLACE_DISK_CHG:
9001
      if remote_node is None and iallocator is None:
9002
        raise errors.OpPrereqError("When changing the secondary either an"
9003
                                   " iallocator script must be used or the"
9004
                                   " new node given", errors.ECODE_INVAL)
9005

    
9006
      if remote_node is not None and iallocator is not None:
9007
        raise errors.OpPrereqError("Give either the iallocator or the new"
9008
                                   " secondary, not both", errors.ECODE_INVAL)
9009

    
9010
    elif remote_node is not None or iallocator is not None:
9011
      # Not replacing the secondary
9012
      raise errors.OpPrereqError("The iallocator and new node options can"
9013
                                 " only be used when changing the"
9014
                                 " secondary node", errors.ECODE_INVAL)
9015

    
9016
  @staticmethod
9017
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
9018
    """Compute a new secondary node using an IAllocator.
9019

9020
    """
9021
    ial = IAllocator(lu.cfg, lu.rpc,
9022
                     mode=constants.IALLOCATOR_MODE_RELOC,
9023
                     name=instance_name,
9024
                     relocate_from=relocate_from)
9025

    
9026
    ial.Run(iallocator_name)
9027

    
9028
    if not ial.success:
9029
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
9030
                                 " %s" % (iallocator_name, ial.info),
9031
                                 errors.ECODE_NORES)
9032

    
9033
    if len(ial.result) != ial.required_nodes:
9034
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9035
                                 " of nodes (%s), required %s" %
9036
                                 (iallocator_name,
9037
                                  len(ial.result), ial.required_nodes),
9038
                                 errors.ECODE_FAULT)
9039

    
9040
    remote_node_name = ial.result[0]
9041

    
9042
    lu.LogInfo("Selected new secondary for instance '%s': %s",
9043
               instance_name, remote_node_name)
9044

    
9045
    return remote_node_name
9046

    
9047
  def _FindFaultyDisks(self, node_name):
9048
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9049
                                    node_name, True)
9050

    
9051
  def _CheckDisksActivated(self, instance):
9052
    """Checks if the instance disks are activated.
9053

9054
    @param instance: The instance to check disks
9055
    @return: True if they are activated, False otherwise
9056

9057
    """
9058
    nodes = instance.all_nodes
9059

    
9060
    for idx, dev in enumerate(instance.disks):
9061
      for node in nodes:
9062
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9063
        self.cfg.SetDiskID(dev, node)
9064

    
9065
        result = self.rpc.call_blockdev_find(node, dev)
9066

    
9067
        if result.offline:
9068
          continue
9069
        elif result.fail_msg or not result.payload:
9070
          return False
9071

    
9072
    return True
9073

    
9074
  def CheckPrereq(self):
9075
    """Check prerequisites.
9076

9077
    This checks that the instance is in the cluster.
9078

9079
    """
9080
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9081
    assert instance is not None, \
9082
      "Cannot retrieve locked instance %s" % self.instance_name
9083

    
9084
    if instance.disk_template != constants.DT_DRBD8:
9085
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9086
                                 " instances", errors.ECODE_INVAL)
9087

    
9088
    if len(instance.secondary_nodes) != 1:
9089
      raise errors.OpPrereqError("The instance has a strange layout,"
9090
                                 " expected one secondary but found %d" %
9091
                                 len(instance.secondary_nodes),
9092
                                 errors.ECODE_FAULT)
9093

    
9094
    if not self.delay_iallocator:
9095
      self._CheckPrereq2()
9096

    
9097
  def _CheckPrereq2(self):
9098
    """Check prerequisites, second part.
9099

9100
    This function should always be part of CheckPrereq. It was separated and is
9101
    now called from Exec because during node evacuation iallocator was only
9102
    called with an unmodified cluster model, not taking planned changes into
9103
    account.
9104

9105
    """
9106
    instance = self.instance
9107
    secondary_node = instance.secondary_nodes[0]
9108

    
9109
    if self.iallocator_name is None:
9110
      remote_node = self.remote_node
9111
    else:
9112
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
9113
                                       instance.name, instance.secondary_nodes)
9114

    
9115
    if remote_node is None:
9116
      self.remote_node_info = None
9117
    else:
9118
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
9119
             "Remote node '%s' is not locked" % remote_node
9120

    
9121
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9122
      assert self.remote_node_info is not None, \
9123
        "Cannot retrieve locked node %s" % remote_node
9124

    
9125
    if remote_node == self.instance.primary_node:
9126
      raise errors.OpPrereqError("The specified node is the primary node of"
9127
                                 " the instance", errors.ECODE_INVAL)
9128

    
9129
    if remote_node == secondary_node:
9130
      raise errors.OpPrereqError("The specified node is already the"
9131
                                 " secondary node of the instance",
9132
                                 errors.ECODE_INVAL)
9133

    
9134
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9135
                                    constants.REPLACE_DISK_CHG):
9136
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
9137
                                 errors.ECODE_INVAL)
9138

    
9139
    if self.mode == constants.REPLACE_DISK_AUTO:
9140
      if not self._CheckDisksActivated(instance):
9141
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
9142
                                   " first" % self.instance_name,
9143
                                   errors.ECODE_STATE)
9144
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
9145
      faulty_secondary = self._FindFaultyDisks(secondary_node)
9146

    
9147
      if faulty_primary and faulty_secondary:
9148
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9149
                                   " one node and can not be repaired"
9150
                                   " automatically" % self.instance_name,
9151
                                   errors.ECODE_STATE)
9152

    
9153
      if faulty_primary:
9154
        self.disks = faulty_primary
9155
        self.target_node = instance.primary_node
9156
        self.other_node = secondary_node
9157
        check_nodes = [self.target_node, self.other_node]
9158
      elif faulty_secondary:
9159
        self.disks = faulty_secondary
9160
        self.target_node = secondary_node
9161
        self.other_node = instance.primary_node
9162
        check_nodes = [self.target_node, self.other_node]
9163
      else:
9164
        self.disks = []
9165
        check_nodes = []
9166

    
9167
    else:
9168
      # Non-automatic modes
9169
      if self.mode == constants.REPLACE_DISK_PRI:
9170
        self.target_node = instance.primary_node
9171
        self.other_node = secondary_node
9172
        check_nodes = [self.target_node, self.other_node]
9173

    
9174
      elif self.mode == constants.REPLACE_DISK_SEC:
9175
        self.target_node = secondary_node
9176
        self.other_node = instance.primary_node
9177
        check_nodes = [self.target_node, self.other_node]
9178

    
9179
      elif self.mode == constants.REPLACE_DISK_CHG:
9180
        self.new_node = remote_node
9181
        self.other_node = instance.primary_node
9182
        self.target_node = secondary_node
9183
        check_nodes = [self.new_node, self.other_node]
9184

    
9185
        _CheckNodeNotDrained(self.lu, remote_node)
9186
        _CheckNodeVmCapable(self.lu, remote_node)
9187

    
9188
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
9189
        assert old_node_info is not None
9190
        if old_node_info.offline and not self.early_release:
9191
          # doesn't make sense to delay the release
9192
          self.early_release = True
9193
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9194
                          " early-release mode", secondary_node)
9195

    
9196
      else:
9197
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9198
                                     self.mode)
9199

    
9200
      # If not specified all disks should be replaced
9201
      if not self.disks:
9202
        self.disks = range(len(self.instance.disks))
9203

    
9204
    for node in check_nodes:
9205
      _CheckNodeOnline(self.lu, node)
9206

    
9207
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
9208
                                                          self.other_node,
9209
                                                          self.target_node]
9210
                              if node_name is not None)
9211

    
9212
    # Release unneeded node locks
9213
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9214

    
9215
    # Release any owned node group
9216
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9217
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9218

    
9219
    # Check whether disks are valid
9220
    for disk_idx in self.disks:
9221
      instance.FindDisk(disk_idx)
9222

    
9223
    # Get secondary node IP addresses
9224
    self.node_secondary_ip = \
9225
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
9226
           for node_name in touched_nodes)
9227

    
9228
  def Exec(self, feedback_fn):
9229
    """Execute disk replacement.
9230

9231
    This dispatches the disk replacement to the appropriate handler.
9232

9233
    """
9234
    if self.delay_iallocator:
9235
      self._CheckPrereq2()
9236

    
9237
    if __debug__:
9238
      # Verify owned locks before starting operation
9239
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9240
      assert set(owned_locks) == set(self.node_secondary_ip), \
9241
          ("Incorrect node locks, owning %s, expected %s" %
9242
           (owned_locks, self.node_secondary_ip.keys()))
9243

    
9244
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9245
      assert list(owned_locks) == [self.instance_name], \
9246
          "Instance '%s' not locked" % self.instance_name
9247

    
9248
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9249
          "Should not own any node group lock at this point"
9250

    
9251
    if not self.disks:
9252
      feedback_fn("No disks need replacement")
9253
      return
9254

    
9255
    feedback_fn("Replacing disk(s) %s for %s" %
9256
                (utils.CommaJoin(self.disks), self.instance.name))
9257

    
9258
    activate_disks = (not self.instance.admin_up)
9259

    
9260
    # Activate the instance disks if we're replacing them on a down instance
9261
    if activate_disks:
9262
      _StartInstanceDisks(self.lu, self.instance, True)
9263

    
9264
    try:
9265
      # Should we replace the secondary node?
9266
      if self.new_node is not None:
9267
        fn = self._ExecDrbd8Secondary
9268
      else:
9269
        fn = self._ExecDrbd8DiskOnly
9270

    
9271
      result = fn(feedback_fn)
9272
    finally:
9273
      # Deactivate the instance disks if we're replacing them on a
9274
      # down instance
9275
      if activate_disks:
9276
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9277

    
9278
    if __debug__:
9279
      # Verify owned locks
9280
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9281
      nodes = frozenset(self.node_secondary_ip)
9282
      assert ((self.early_release and not owned_locks) or
9283
              (not self.early_release and not (set(owned_locks) - nodes))), \
9284
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9285
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9286

    
9287
    return result
9288

    
9289
  def _CheckVolumeGroup(self, nodes):
9290
    self.lu.LogInfo("Checking volume groups")
9291

    
9292
    vgname = self.cfg.GetVGName()
9293

    
9294
    # Make sure volume group exists on all involved nodes
9295
    results = self.rpc.call_vg_list(nodes)
9296
    if not results:
9297
      raise errors.OpExecError("Can't list volume groups on the nodes")
9298

    
9299
    for node in nodes:
9300
      res = results[node]
9301
      res.Raise("Error checking node %s" % node)
9302
      if vgname not in res.payload:
9303
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9304
                                 (vgname, node))
9305

    
9306
  def _CheckDisksExistence(self, nodes):
9307
    # Check disk existence
9308
    for idx, dev in enumerate(self.instance.disks):
9309
      if idx not in self.disks:
9310
        continue
9311

    
9312
      for node in nodes:
9313
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9314
        self.cfg.SetDiskID(dev, node)
9315

    
9316
        result = self.rpc.call_blockdev_find(node, dev)
9317

    
9318
        msg = result.fail_msg
9319
        if msg or not result.payload:
9320
          if not msg:
9321
            msg = "disk not found"
9322
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9323
                                   (idx, node, msg))
9324

    
9325
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9326
    for idx, dev in enumerate(self.instance.disks):
9327
      if idx not in self.disks:
9328
        continue
9329

    
9330
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9331
                      (idx, node_name))
9332

    
9333
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9334
                                   ldisk=ldisk):
9335
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9336
                                 " replace disks for instance %s" %
9337
                                 (node_name, self.instance.name))
9338

    
9339
  def _CreateNewStorage(self, node_name):
9340
    iv_names = {}
9341

    
9342
    for idx, dev in enumerate(self.instance.disks):
9343
      if idx not in self.disks:
9344
        continue
9345

    
9346
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
9347

    
9348
      self.cfg.SetDiskID(dev, node_name)
9349

    
9350
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9351
      names = _GenerateUniqueNames(self.lu, lv_names)
9352

    
9353
      vg_data = dev.children[0].logical_id[0]
9354
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9355
                             logical_id=(vg_data, names[0]))
9356
      vg_meta = dev.children[1].logical_id[0]
9357
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9358
                             logical_id=(vg_meta, names[1]))
9359

    
9360
      new_lvs = [lv_data, lv_meta]
9361
      old_lvs = dev.children
9362
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9363

    
9364
      # we pass force_create=True to force the LVM creation
9365
      for new_lv in new_lvs:
9366
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9367
                        _GetInstanceInfoText(self.instance), False)
9368

    
9369
    return iv_names
9370

    
9371
  def _CheckDevices(self, node_name, iv_names):
9372
    for name, (dev, _, _) in iv_names.iteritems():
9373
      self.cfg.SetDiskID(dev, node_name)
9374

    
9375
      result = self.rpc.call_blockdev_find(node_name, dev)
9376

    
9377
      msg = result.fail_msg
9378
      if msg or not result.payload:
9379
        if not msg:
9380
          msg = "disk not found"
9381
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9382
                                 (name, msg))
9383

    
9384
      if result.payload.is_degraded:
9385
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9386

    
9387
  def _RemoveOldStorage(self, node_name, iv_names):
9388
    for name, (_, old_lvs, _) in iv_names.iteritems():
9389
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9390

    
9391
      for lv in old_lvs:
9392
        self.cfg.SetDiskID(lv, node_name)
9393

    
9394
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9395
        if msg:
9396
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9397
                             hint="remove unused LVs manually")
9398

    
9399
  def _ExecDrbd8DiskOnly(self, feedback_fn):
9400
    """Replace a disk on the primary or secondary for DRBD 8.
9401

9402
    The algorithm for replace is quite complicated:
9403

9404
      1. for each disk to be replaced:
9405

9406
        1. create new LVs on the target node with unique names
9407
        1. detach old LVs from the drbd device
9408
        1. rename old LVs to name_replaced.<time_t>
9409
        1. rename new LVs to old LVs
9410
        1. attach the new LVs (with the old names now) to the drbd device
9411

9412
      1. wait for sync across all devices
9413

9414
      1. for each modified disk:
9415

9416
        1. remove old LVs (which have the name name_replaces.<time_t>)
9417

9418
    Failures are not very well handled.
9419

9420
    """
9421
    steps_total = 6
9422

    
9423
    # Step: check device activation
9424
    self.lu.LogStep(1, steps_total, "Check device existence")
9425
    self._CheckDisksExistence([self.other_node, self.target_node])
9426
    self._CheckVolumeGroup([self.target_node, self.other_node])
9427

    
9428
    # Step: check other node consistency
9429
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9430
    self._CheckDisksConsistency(self.other_node,
9431
                                self.other_node == self.instance.primary_node,
9432
                                False)
9433

    
9434
    # Step: create new storage
9435
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9436
    iv_names = self._CreateNewStorage(self.target_node)
9437

    
9438
    # Step: for each lv, detach+rename*2+attach
9439
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9440
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9441
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9442

    
9443
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9444
                                                     old_lvs)
9445
      result.Raise("Can't detach drbd from local storage on node"
9446
                   " %s for device %s" % (self.target_node, dev.iv_name))
9447
      #dev.children = []
9448
      #cfg.Update(instance)
9449

    
9450
      # ok, we created the new LVs, so now we know we have the needed
9451
      # storage; as such, we proceed on the target node to rename
9452
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9453
      # using the assumption that logical_id == physical_id (which in
9454
      # turn is the unique_id on that node)
9455

    
9456
      # FIXME(iustin): use a better name for the replaced LVs
9457
      temp_suffix = int(time.time())
9458
      ren_fn = lambda d, suff: (d.physical_id[0],
9459
                                d.physical_id[1] + "_replaced-%s" % suff)
9460

    
9461
      # Build the rename list based on what LVs exist on the node
9462
      rename_old_to_new = []
9463
      for to_ren in old_lvs:
9464
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9465
        if not result.fail_msg and result.payload:
9466
          # device exists
9467
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9468

    
9469
      self.lu.LogInfo("Renaming the old LVs on the target node")
9470
      result = self.rpc.call_blockdev_rename(self.target_node,
9471
                                             rename_old_to_new)
9472
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9473

    
9474
      # Now we rename the new LVs to the old LVs
9475
      self.lu.LogInfo("Renaming the new LVs on the target node")
9476
      rename_new_to_old = [(new, old.physical_id)
9477
                           for old, new in zip(old_lvs, new_lvs)]
9478
      result = self.rpc.call_blockdev_rename(self.target_node,
9479
                                             rename_new_to_old)
9480
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9481

    
9482
      for old, new in zip(old_lvs, new_lvs):
9483
        new.logical_id = old.logical_id
9484
        self.cfg.SetDiskID(new, self.target_node)
9485

    
9486
      for disk in old_lvs:
9487
        disk.logical_id = ren_fn(disk, temp_suffix)
9488
        self.cfg.SetDiskID(disk, self.target_node)
9489

    
9490
      # Now that the new lvs have the old name, we can add them to the device
9491
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9492
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9493
                                                  new_lvs)
9494
      msg = result.fail_msg
9495
      if msg:
9496
        for new_lv in new_lvs:
9497
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9498
                                               new_lv).fail_msg
9499
          if msg2:
9500
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9501
                               hint=("cleanup manually the unused logical"
9502
                                     "volumes"))
9503
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9504

    
9505
      dev.children = new_lvs
9506

    
9507
      self.cfg.Update(self.instance, feedback_fn)
9508

    
9509
    cstep = 5
9510
    if self.early_release:
9511
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9512
      cstep += 1
9513
      self._RemoveOldStorage(self.target_node, iv_names)
9514
      # WARNING: we release both node locks here, do not do other RPCs
9515
      # than WaitForSync to the primary node
9516
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9517
                    names=[self.target_node, self.other_node])
9518

    
9519
    # Wait for sync
9520
    # This can fail as the old devices are degraded and _WaitForSync
9521
    # does a combined result over all disks, so we don't check its return value
9522
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9523
    cstep += 1
9524
    _WaitForSync(self.lu, self.instance)
9525

    
9526
    # Check all devices manually
9527
    self._CheckDevices(self.instance.primary_node, iv_names)
9528

    
9529
    # Step: remove old storage
9530
    if not self.early_release:
9531
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9532
      cstep += 1
9533
      self._RemoveOldStorage(self.target_node, iv_names)
9534

    
9535
  def _ExecDrbd8Secondary(self, feedback_fn):
9536
    """Replace the secondary node for DRBD 8.
9537

9538
    The algorithm for replace is quite complicated:
9539
      - for all disks of the instance:
9540
        - create new LVs on the new node with same names
9541
        - shutdown the drbd device on the old secondary
9542
        - disconnect the drbd network on the primary
9543
        - create the drbd device on the new secondary
9544
        - network attach the drbd on the primary, using an artifice:
9545
          the drbd code for Attach() will connect to the network if it
9546
          finds a device which is connected to the good local disks but
9547
          not network enabled
9548
      - wait for sync across all devices
9549
      - remove all disks from the old secondary
9550

9551
    Failures are not very well handled.
9552

9553
    """
9554
    steps_total = 6
9555

    
9556
    # Step: check device activation
9557
    self.lu.LogStep(1, steps_total, "Check device existence")
9558
    self._CheckDisksExistence([self.instance.primary_node])
9559
    self._CheckVolumeGroup([self.instance.primary_node])
9560

    
9561
    # Step: check other node consistency
9562
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9563
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9564

    
9565
    # Step: create new storage
9566
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9567
    for idx, dev in enumerate(self.instance.disks):
9568
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9569
                      (self.new_node, idx))
9570
      # we pass force_create=True to force LVM creation
9571
      for new_lv in dev.children:
9572
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9573
                        _GetInstanceInfoText(self.instance), False)
9574

    
9575
    # Step 4: dbrd minors and drbd setups changes
9576
    # after this, we must manually remove the drbd minors on both the
9577
    # error and the success paths
9578
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9579
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9580
                                         for dev in self.instance.disks],
9581
                                        self.instance.name)
9582
    logging.debug("Allocated minors %r", minors)
9583

    
9584
    iv_names = {}
9585
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9586
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9587
                      (self.new_node, idx))
9588
      # create new devices on new_node; note that we create two IDs:
9589
      # one without port, so the drbd will be activated without
9590
      # networking information on the new node at this stage, and one
9591
      # with network, for the latter activation in step 4
9592
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9593
      if self.instance.primary_node == o_node1:
9594
        p_minor = o_minor1
9595
      else:
9596
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9597
        p_minor = o_minor2
9598

    
9599
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9600
                      p_minor, new_minor, o_secret)
9601
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9602
                    p_minor, new_minor, o_secret)
9603

    
9604
      iv_names[idx] = (dev, dev.children, new_net_id)
9605
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9606
                    new_net_id)
9607
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9608
                              logical_id=new_alone_id,
9609
                              children=dev.children,
9610
                              size=dev.size)
9611
      try:
9612
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9613
                              _GetInstanceInfoText(self.instance), False)
9614
      except errors.GenericError:
9615
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9616
        raise
9617

    
9618
    # We have new devices, shutdown the drbd on the old secondary
9619
    for idx, dev in enumerate(self.instance.disks):
9620
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9621
      self.cfg.SetDiskID(dev, self.target_node)
9622
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9623
      if msg:
9624
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9625
                           "node: %s" % (idx, msg),
9626
                           hint=("Please cleanup this device manually as"
9627
                                 " soon as possible"))
9628

    
9629
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9630
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9631
                                               self.node_secondary_ip,
9632
                                               self.instance.disks)\
9633
                                              [self.instance.primary_node]
9634

    
9635
    msg = result.fail_msg
9636
    if msg:
9637
      # detaches didn't succeed (unlikely)
9638
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9639
      raise errors.OpExecError("Can't detach the disks from the network on"
9640
                               " old node: %s" % (msg,))
9641

    
9642
    # if we managed to detach at least one, we update all the disks of
9643
    # the instance to point to the new secondary
9644
    self.lu.LogInfo("Updating instance configuration")
9645
    for dev, _, new_logical_id in iv_names.itervalues():
9646
      dev.logical_id = new_logical_id
9647
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9648

    
9649
    self.cfg.Update(self.instance, feedback_fn)
9650

    
9651
    # and now perform the drbd attach
9652
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9653
                    " (standalone => connected)")
9654
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9655
                                            self.new_node],
9656
                                           self.node_secondary_ip,
9657
                                           self.instance.disks,
9658
                                           self.instance.name,
9659
                                           False)
9660
    for to_node, to_result in result.items():
9661
      msg = to_result.fail_msg
9662
      if msg:
9663
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9664
                           to_node, msg,
9665
                           hint=("please do a gnt-instance info to see the"
9666
                                 " status of disks"))
9667
    cstep = 5
9668
    if self.early_release:
9669
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9670
      cstep += 1
9671
      self._RemoveOldStorage(self.target_node, iv_names)
9672
      # WARNING: we release all node locks here, do not do other RPCs
9673
      # than WaitForSync to the primary node
9674
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9675
                    names=[self.instance.primary_node,
9676
                           self.target_node,
9677
                           self.new_node])
9678

    
9679
    # Wait for sync
9680
    # This can fail as the old devices are degraded and _WaitForSync
9681
    # does a combined result over all disks, so we don't check its return value
9682
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9683
    cstep += 1
9684
    _WaitForSync(self.lu, self.instance)
9685

    
9686
    # Check all devices manually
9687
    self._CheckDevices(self.instance.primary_node, iv_names)
9688

    
9689
    # Step: remove old storage
9690
    if not self.early_release:
9691
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9692
      self._RemoveOldStorage(self.target_node, iv_names)
9693

    
9694

    
9695
class LURepairNodeStorage(NoHooksLU):
9696
  """Repairs the volume group on a node.
9697

9698
  """
9699
  REQ_BGL = False
9700

    
9701
  def CheckArguments(self):
9702
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9703

    
9704
    storage_type = self.op.storage_type
9705

    
9706
    if (constants.SO_FIX_CONSISTENCY not in
9707
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9708
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9709
                                 " repaired" % storage_type,
9710
                                 errors.ECODE_INVAL)
9711

    
9712
  def ExpandNames(self):
9713
    self.needed_locks = {
9714
      locking.LEVEL_NODE: [self.op.node_name],
9715
      }
9716

    
9717
  def _CheckFaultyDisks(self, instance, node_name):
9718
    """Ensure faulty disks abort the opcode or at least warn."""
9719
    try:
9720
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9721
                                  node_name, True):
9722
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9723
                                   " node '%s'" % (instance.name, node_name),
9724
                                   errors.ECODE_STATE)
9725
    except errors.OpPrereqError, err:
9726
      if self.op.ignore_consistency:
9727
        self.proc.LogWarning(str(err.args[0]))
9728
      else:
9729
        raise
9730

    
9731
  def CheckPrereq(self):
9732
    """Check prerequisites.
9733

9734
    """
9735
    # Check whether any instance on this node has faulty disks
9736
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9737
      if not inst.admin_up:
9738
        continue
9739
      check_nodes = set(inst.all_nodes)
9740
      check_nodes.discard(self.op.node_name)
9741
      for inst_node_name in check_nodes:
9742
        self._CheckFaultyDisks(inst, inst_node_name)
9743

    
9744
  def Exec(self, feedback_fn):
9745
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9746
                (self.op.name, self.op.node_name))
9747

    
9748
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9749
    result = self.rpc.call_storage_execute(self.op.node_name,
9750
                                           self.op.storage_type, st_args,
9751
                                           self.op.name,
9752
                                           constants.SO_FIX_CONSISTENCY)
9753
    result.Raise("Failed to repair storage unit '%s' on %s" %
9754
                 (self.op.name, self.op.node_name))
9755

    
9756

    
9757
class LUNodeEvacStrategy(NoHooksLU):
9758
  """Computes the node evacuation strategy.
9759

9760
  """
9761
  REQ_BGL = False
9762

    
9763
  def CheckArguments(self):
9764
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9765

    
9766
  def ExpandNames(self):
9767
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9768
    self.needed_locks = locks = {}
9769
    if self.op.remote_node is None:
9770
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9771
    else:
9772
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9773
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9774

    
9775
  def Exec(self, feedback_fn):
9776
    instances = []
9777
    for node in self.op.nodes:
9778
      instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9779
    if not instances:
9780
      return []
9781

    
9782
    if self.op.remote_node is not None:
9783
      result = []
9784
      for i in instances:
9785
        if i.primary_node == self.op.remote_node:
9786
          raise errors.OpPrereqError("Node %s is the primary node of"
9787
                                     " instance %s, cannot use it as"
9788
                                     " secondary" %
9789
                                     (self.op.remote_node, i.name),
9790
                                     errors.ECODE_INVAL)
9791
        result.append([i.name, self.op.remote_node])
9792
    else:
9793
      ial = IAllocator(self.cfg, self.rpc,
9794
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9795
                       evac_nodes=self.op.nodes)
9796
      ial.Run(self.op.iallocator, validate=True)
9797
      if not ial.success:
9798
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9799
                                 errors.ECODE_NORES)
9800
      result = ial.result
9801
    return result
9802

    
9803

    
9804
class LUInstanceGrowDisk(LogicalUnit):
9805
  """Grow a disk of an instance.
9806

9807
  """
9808
  HPATH = "disk-grow"
9809
  HTYPE = constants.HTYPE_INSTANCE
9810
  REQ_BGL = False
9811

    
9812
  def ExpandNames(self):
9813
    self._ExpandAndLockInstance()
9814
    self.needed_locks[locking.LEVEL_NODE] = []
9815
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9816

    
9817
  def DeclareLocks(self, level):
9818
    if level == locking.LEVEL_NODE:
9819
      self._LockInstancesNodes()
9820

    
9821
  def BuildHooksEnv(self):
9822
    """Build hooks env.
9823

9824
    This runs on the master, the primary and all the secondaries.
9825

9826
    """
9827
    env = {
9828
      "DISK": self.op.disk,
9829
      "AMOUNT": self.op.amount,
9830
      }
9831
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9832
    return env
9833

    
9834
  def BuildHooksNodes(self):
9835
    """Build hooks nodes.
9836

9837
    """
9838
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9839
    return (nl, nl)
9840

    
9841
  def CheckPrereq(self):
9842
    """Check prerequisites.
9843

9844
    This checks that the instance is in the cluster.
9845

9846
    """
9847
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9848
    assert instance is not None, \
9849
      "Cannot retrieve locked instance %s" % self.op.instance_name
9850
    nodenames = list(instance.all_nodes)
9851
    for node in nodenames:
9852
      _CheckNodeOnline(self, node)
9853

    
9854
    self.instance = instance
9855

    
9856
    if instance.disk_template not in constants.DTS_GROWABLE:
9857
      raise errors.OpPrereqError("Instance's disk layout does not support"
9858
                                 " growing", errors.ECODE_INVAL)
9859

    
9860
    self.disk = instance.FindDisk(self.op.disk)
9861

    
9862
    if instance.disk_template not in (constants.DT_FILE,
9863
                                      constants.DT_SHARED_FILE):
9864
      # TODO: check the free disk space for file, when that feature will be
9865
      # supported
9866
      _CheckNodesFreeDiskPerVG(self, nodenames,
9867
                               self.disk.ComputeGrowth(self.op.amount))
9868

    
9869
  def Exec(self, feedback_fn):
9870
    """Execute disk grow.
9871

9872
    """
9873
    instance = self.instance
9874
    disk = self.disk
9875

    
9876
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9877
    if not disks_ok:
9878
      raise errors.OpExecError("Cannot activate block device to grow")
9879

    
9880
    # First run all grow ops in dry-run mode
9881
    for node in instance.all_nodes:
9882
      self.cfg.SetDiskID(disk, node)
9883
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
9884
      result.Raise("Grow request failed to node %s" % node)
9885

    
9886
    # We know that (as far as we can test) operations across different
9887
    # nodes will succeed, time to run it for real
9888
    for node in instance.all_nodes:
9889
      self.cfg.SetDiskID(disk, node)
9890
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
9891
      result.Raise("Grow request failed to node %s" % node)
9892

    
9893
      # TODO: Rewrite code to work properly
9894
      # DRBD goes into sync mode for a short amount of time after executing the
9895
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9896
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9897
      # time is a work-around.
9898
      time.sleep(5)
9899

    
9900
    disk.RecordGrow(self.op.amount)
9901
    self.cfg.Update(instance, feedback_fn)
9902
    if self.op.wait_for_sync:
9903
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9904
      if disk_abort:
9905
        self.proc.LogWarning("Disk sync-ing has not returned a good"
9906
                             " status; please check the instance")
9907
      if not instance.admin_up:
9908
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9909
    elif not instance.admin_up:
9910
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9911
                           " not supposed to be running because no wait for"
9912
                           " sync mode was requested")
9913

    
9914

    
9915
class LUInstanceQueryData(NoHooksLU):
9916
  """Query runtime instance data.
9917

9918
  """
9919
  REQ_BGL = False
9920

    
9921
  def ExpandNames(self):
9922
    self.needed_locks = {}
9923

    
9924
    # Use locking if requested or when non-static information is wanted
9925
    if not (self.op.static or self.op.use_locking):
9926
      self.LogWarning("Non-static data requested, locks need to be acquired")
9927
      self.op.use_locking = True
9928

    
9929
    if self.op.instances or not self.op.use_locking:
9930
      # Expand instance names right here
9931
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
9932
    else:
9933
      # Will use acquired locks
9934
      self.wanted_names = None
9935

    
9936
    if self.op.use_locking:
9937
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9938

    
9939
      if self.wanted_names is None:
9940
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9941
      else:
9942
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9943

    
9944
      self.needed_locks[locking.LEVEL_NODE] = []
9945
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9946
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9947

    
9948
  def DeclareLocks(self, level):
9949
    if self.op.use_locking and level == locking.LEVEL_NODE:
9950
      self._LockInstancesNodes()
9951

    
9952
  def CheckPrereq(self):
9953
    """Check prerequisites.
9954

9955
    This only checks the optional instance list against the existing names.
9956

9957
    """
9958
    if self.wanted_names is None:
9959
      assert self.op.use_locking, "Locking was not used"
9960
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
9961

    
9962
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
9963
                             for name in self.wanted_names]
9964

    
9965
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9966
    """Returns the status of a block device
9967

9968
    """
9969
    if self.op.static or not node:
9970
      return None
9971

    
9972
    self.cfg.SetDiskID(dev, node)
9973

    
9974
    result = self.rpc.call_blockdev_find(node, dev)
9975
    if result.offline:
9976
      return None
9977

    
9978
    result.Raise("Can't compute disk status for %s" % instance_name)
9979

    
9980
    status = result.payload
9981
    if status is None:
9982
      return None
9983

    
9984
    return (status.dev_path, status.major, status.minor,
9985
            status.sync_percent, status.estimated_time,
9986
            status.is_degraded, status.ldisk_status)
9987

    
9988
  def _ComputeDiskStatus(self, instance, snode, dev):
9989
    """Compute block device status.
9990

9991
    """
9992
    if dev.dev_type in constants.LDS_DRBD:
9993
      # we change the snode then (otherwise we use the one passed in)
9994
      if dev.logical_id[0] == instance.primary_node:
9995
        snode = dev.logical_id[1]
9996
      else:
9997
        snode = dev.logical_id[0]
9998

    
9999
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
10000
                                              instance.name, dev)
10001
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
10002

    
10003
    if dev.children:
10004
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
10005
                      for child in dev.children]
10006
    else:
10007
      dev_children = []
10008

    
10009
    return {
10010
      "iv_name": dev.iv_name,
10011
      "dev_type": dev.dev_type,
10012
      "logical_id": dev.logical_id,
10013
      "physical_id": dev.physical_id,
10014
      "pstatus": dev_pstatus,
10015
      "sstatus": dev_sstatus,
10016
      "children": dev_children,
10017
      "mode": dev.mode,
10018
      "size": dev.size,
10019
      }
10020

    
10021
  def Exec(self, feedback_fn):
10022
    """Gather and return data"""
10023
    result = {}
10024

    
10025
    cluster = self.cfg.GetClusterInfo()
10026

    
10027
    for instance in self.wanted_instances:
10028
      if not self.op.static:
10029
        remote_info = self.rpc.call_instance_info(instance.primary_node,
10030
                                                  instance.name,
10031
                                                  instance.hypervisor)
10032
        remote_info.Raise("Error checking node %s" % instance.primary_node)
10033
        remote_info = remote_info.payload
10034
        if remote_info and "state" in remote_info:
10035
          remote_state = "up"
10036
        else:
10037
          remote_state = "down"
10038
      else:
10039
        remote_state = None
10040
      if instance.admin_up:
10041
        config_state = "up"
10042
      else:
10043
        config_state = "down"
10044

    
10045
      disks = [self._ComputeDiskStatus(instance, None, device)
10046
               for device in instance.disks]
10047

    
10048
      result[instance.name] = {
10049
        "name": instance.name,
10050
        "config_state": config_state,
10051
        "run_state": remote_state,
10052
        "pnode": instance.primary_node,
10053
        "snodes": instance.secondary_nodes,
10054
        "os": instance.os,
10055
        # this happens to be the same format used for hooks
10056
        "nics": _NICListToTuple(self, instance.nics),
10057
        "disk_template": instance.disk_template,
10058
        "disks": disks,
10059
        "hypervisor": instance.hypervisor,
10060
        "network_port": instance.network_port,
10061
        "hv_instance": instance.hvparams,
10062
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
10063
        "be_instance": instance.beparams,
10064
        "be_actual": cluster.FillBE(instance),
10065
        "os_instance": instance.osparams,
10066
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
10067
        "serial_no": instance.serial_no,
10068
        "mtime": instance.mtime,
10069
        "ctime": instance.ctime,
10070
        "uuid": instance.uuid,
10071
        }
10072

    
10073
    return result
10074

    
10075

    
10076
class LUInstanceSetParams(LogicalUnit):
10077
  """Modifies an instances's parameters.
10078

10079
  """
10080
  HPATH = "instance-modify"
10081
  HTYPE = constants.HTYPE_INSTANCE
10082
  REQ_BGL = False
10083

    
10084
  def CheckArguments(self):
10085
    if not (self.op.nics or self.op.disks or self.op.disk_template or
10086
            self.op.hvparams or self.op.beparams or self.op.os_name):
10087
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
10088

    
10089
    if self.op.hvparams:
10090
      _CheckGlobalHvParams(self.op.hvparams)
10091

    
10092
    # Disk validation
10093
    disk_addremove = 0
10094
    for disk_op, disk_dict in self.op.disks:
10095
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
10096
      if disk_op == constants.DDM_REMOVE:
10097
        disk_addremove += 1
10098
        continue
10099
      elif disk_op == constants.DDM_ADD:
10100
        disk_addremove += 1
10101
      else:
10102
        if not isinstance(disk_op, int):
10103
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
10104
        if not isinstance(disk_dict, dict):
10105
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
10106
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10107

    
10108
      if disk_op == constants.DDM_ADD:
10109
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
10110
        if mode not in constants.DISK_ACCESS_SET:
10111
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
10112
                                     errors.ECODE_INVAL)
10113
        size = disk_dict.get(constants.IDISK_SIZE, None)
10114
        if size is None:
10115
          raise errors.OpPrereqError("Required disk parameter size missing",
10116
                                     errors.ECODE_INVAL)
10117
        try:
10118
          size = int(size)
10119
        except (TypeError, ValueError), err:
10120
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10121
                                     str(err), errors.ECODE_INVAL)
10122
        disk_dict[constants.IDISK_SIZE] = size
10123
      else:
10124
        # modification of disk
10125
        if constants.IDISK_SIZE in disk_dict:
10126
          raise errors.OpPrereqError("Disk size change not possible, use"
10127
                                     " grow-disk", errors.ECODE_INVAL)
10128

    
10129
    if disk_addremove > 1:
10130
      raise errors.OpPrereqError("Only one disk add or remove operation"
10131
                                 " supported at a time", errors.ECODE_INVAL)
10132

    
10133
    if self.op.disks and self.op.disk_template is not None:
10134
      raise errors.OpPrereqError("Disk template conversion and other disk"
10135
                                 " changes not supported at the same time",
10136
                                 errors.ECODE_INVAL)
10137

    
10138
    if (self.op.disk_template and
10139
        self.op.disk_template in constants.DTS_INT_MIRROR and
10140
        self.op.remote_node is None):
10141
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
10142
                                 " one requires specifying a secondary node",
10143
                                 errors.ECODE_INVAL)
10144

    
10145
    # NIC validation
10146
    nic_addremove = 0
10147
    for nic_op, nic_dict in self.op.nics:
10148
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10149
      if nic_op == constants.DDM_REMOVE:
10150
        nic_addremove += 1
10151
        continue
10152
      elif nic_op == constants.DDM_ADD:
10153
        nic_addremove += 1
10154
      else:
10155
        if not isinstance(nic_op, int):
10156
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10157
        if not isinstance(nic_dict, dict):
10158
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10159
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10160

    
10161
      # nic_dict should be a dict
10162
      nic_ip = nic_dict.get(constants.INIC_IP, None)
10163
      if nic_ip is not None:
10164
        if nic_ip.lower() == constants.VALUE_NONE:
10165
          nic_dict[constants.INIC_IP] = None
10166
        else:
10167
          if not netutils.IPAddress.IsValid(nic_ip):
10168
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10169
                                       errors.ECODE_INVAL)
10170

    
10171
      nic_bridge = nic_dict.get('bridge', None)
10172
      nic_link = nic_dict.get(constants.INIC_LINK, None)
10173
      if nic_bridge and nic_link:
10174
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10175
                                   " at the same time", errors.ECODE_INVAL)
10176
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10177
        nic_dict['bridge'] = None
10178
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10179
        nic_dict[constants.INIC_LINK] = None
10180

    
10181
      if nic_op == constants.DDM_ADD:
10182
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
10183
        if nic_mac is None:
10184
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10185

    
10186
      if constants.INIC_MAC in nic_dict:
10187
        nic_mac = nic_dict[constants.INIC_MAC]
10188
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10189
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10190

    
10191
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10192
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10193
                                     " modifying an existing nic",
10194
                                     errors.ECODE_INVAL)
10195

    
10196
    if nic_addremove > 1:
10197
      raise errors.OpPrereqError("Only one NIC add or remove operation"
10198
                                 " supported at a time", errors.ECODE_INVAL)
10199

    
10200
  def ExpandNames(self):
10201
    self._ExpandAndLockInstance()
10202
    self.needed_locks[locking.LEVEL_NODE] = []
10203
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10204

    
10205
  def DeclareLocks(self, level):
10206
    if level == locking.LEVEL_NODE:
10207
      self._LockInstancesNodes()
10208
      if self.op.disk_template and self.op.remote_node:
10209
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10210
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10211

    
10212
  def BuildHooksEnv(self):
10213
    """Build hooks env.
10214

10215
    This runs on the master, primary and secondaries.
10216

10217
    """
10218
    args = dict()
10219
    if constants.BE_MEMORY in self.be_new:
10220
      args['memory'] = self.be_new[constants.BE_MEMORY]
10221
    if constants.BE_VCPUS in self.be_new:
10222
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
10223
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10224
    # information at all.
10225
    if self.op.nics:
10226
      args['nics'] = []
10227
      nic_override = dict(self.op.nics)
10228
      for idx, nic in enumerate(self.instance.nics):
10229
        if idx in nic_override:
10230
          this_nic_override = nic_override[idx]
10231
        else:
10232
          this_nic_override = {}
10233
        if constants.INIC_IP in this_nic_override:
10234
          ip = this_nic_override[constants.INIC_IP]
10235
        else:
10236
          ip = nic.ip
10237
        if constants.INIC_MAC in this_nic_override:
10238
          mac = this_nic_override[constants.INIC_MAC]
10239
        else:
10240
          mac = nic.mac
10241
        if idx in self.nic_pnew:
10242
          nicparams = self.nic_pnew[idx]
10243
        else:
10244
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10245
        mode = nicparams[constants.NIC_MODE]
10246
        link = nicparams[constants.NIC_LINK]
10247
        args['nics'].append((ip, mac, mode, link))
10248
      if constants.DDM_ADD in nic_override:
10249
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10250
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10251
        nicparams = self.nic_pnew[constants.DDM_ADD]
10252
        mode = nicparams[constants.NIC_MODE]
10253
        link = nicparams[constants.NIC_LINK]
10254
        args['nics'].append((ip, mac, mode, link))
10255
      elif constants.DDM_REMOVE in nic_override:
10256
        del args['nics'][-1]
10257

    
10258
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10259
    if self.op.disk_template:
10260
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10261

    
10262
    return env
10263

    
10264
  def BuildHooksNodes(self):
10265
    """Build hooks nodes.
10266

10267
    """
10268
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10269
    return (nl, nl)
10270

    
10271
  def CheckPrereq(self):
10272
    """Check prerequisites.
10273

10274
    This only checks the instance list against the existing names.
10275

10276
    """
10277
    # checking the new params on the primary/secondary nodes
10278

    
10279
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10280
    cluster = self.cluster = self.cfg.GetClusterInfo()
10281
    assert self.instance is not None, \
10282
      "Cannot retrieve locked instance %s" % self.op.instance_name
10283
    pnode = instance.primary_node
10284
    nodelist = list(instance.all_nodes)
10285

    
10286
    # OS change
10287
    if self.op.os_name and not self.op.force:
10288
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10289
                      self.op.force_variant)
10290
      instance_os = self.op.os_name
10291
    else:
10292
      instance_os = instance.os
10293

    
10294
    if self.op.disk_template:
10295
      if instance.disk_template == self.op.disk_template:
10296
        raise errors.OpPrereqError("Instance already has disk template %s" %
10297
                                   instance.disk_template, errors.ECODE_INVAL)
10298

    
10299
      if (instance.disk_template,
10300
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10301
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10302
                                   " %s to %s" % (instance.disk_template,
10303
                                                  self.op.disk_template),
10304
                                   errors.ECODE_INVAL)
10305
      _CheckInstanceDown(self, instance, "cannot change disk template")
10306
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10307
        if self.op.remote_node == pnode:
10308
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10309
                                     " as the primary node of the instance" %
10310
                                     self.op.remote_node, errors.ECODE_STATE)
10311
        _CheckNodeOnline(self, self.op.remote_node)
10312
        _CheckNodeNotDrained(self, self.op.remote_node)
10313
        # FIXME: here we assume that the old instance type is DT_PLAIN
10314
        assert instance.disk_template == constants.DT_PLAIN
10315
        disks = [{constants.IDISK_SIZE: d.size,
10316
                  constants.IDISK_VG: d.logical_id[0]}
10317
                 for d in instance.disks]
10318
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10319
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10320

    
10321
    # hvparams processing
10322
    if self.op.hvparams:
10323
      hv_type = instance.hypervisor
10324
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10325
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10326
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10327

    
10328
      # local check
10329
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10330
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10331
      self.hv_new = hv_new # the new actual values
10332
      self.hv_inst = i_hvdict # the new dict (without defaults)
10333
    else:
10334
      self.hv_new = self.hv_inst = {}
10335

    
10336
    # beparams processing
10337
    if self.op.beparams:
10338
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10339
                                   use_none=True)
10340
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10341
      be_new = cluster.SimpleFillBE(i_bedict)
10342
      self.be_new = be_new # the new actual values
10343
      self.be_inst = i_bedict # the new dict (without defaults)
10344
    else:
10345
      self.be_new = self.be_inst = {}
10346
    be_old = cluster.FillBE(instance)
10347

    
10348
    # osparams processing
10349
    if self.op.osparams:
10350
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10351
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10352
      self.os_inst = i_osdict # the new dict (without defaults)
10353
    else:
10354
      self.os_inst = {}
10355

    
10356
    self.warn = []
10357

    
10358
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10359
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10360
      mem_check_list = [pnode]
10361
      if be_new[constants.BE_AUTO_BALANCE]:
10362
        # either we changed auto_balance to yes or it was from before
10363
        mem_check_list.extend(instance.secondary_nodes)
10364
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10365
                                                  instance.hypervisor)
10366
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10367
                                         instance.hypervisor)
10368
      pninfo = nodeinfo[pnode]
10369
      msg = pninfo.fail_msg
10370
      if msg:
10371
        # Assume the primary node is unreachable and go ahead
10372
        self.warn.append("Can't get info from primary node %s: %s" %
10373
                         (pnode,  msg))
10374
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10375
        self.warn.append("Node data from primary node %s doesn't contain"
10376
                         " free memory information" % pnode)
10377
      elif instance_info.fail_msg:
10378
        self.warn.append("Can't get instance runtime information: %s" %
10379
                        instance_info.fail_msg)
10380
      else:
10381
        if instance_info.payload:
10382
          current_mem = int(instance_info.payload['memory'])
10383
        else:
10384
          # Assume instance not running
10385
          # (there is a slight race condition here, but it's not very probable,
10386
          # and we have no other way to check)
10387
          current_mem = 0
10388
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10389
                    pninfo.payload['memory_free'])
10390
        if miss_mem > 0:
10391
          raise errors.OpPrereqError("This change will prevent the instance"
10392
                                     " from starting, due to %d MB of memory"
10393
                                     " missing on its primary node" % miss_mem,
10394
                                     errors.ECODE_NORES)
10395

    
10396
      if be_new[constants.BE_AUTO_BALANCE]:
10397
        for node, nres in nodeinfo.items():
10398
          if node not in instance.secondary_nodes:
10399
            continue
10400
          nres.Raise("Can't get info from secondary node %s" % node,
10401
                     prereq=True, ecode=errors.ECODE_STATE)
10402
          if not isinstance(nres.payload.get('memory_free', None), int):
10403
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10404
                                       " memory information" % node,
10405
                                       errors.ECODE_STATE)
10406
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10407
            raise errors.OpPrereqError("This change will prevent the instance"
10408
                                       " from failover to its secondary node"
10409
                                       " %s, due to not enough memory" % node,
10410
                                       errors.ECODE_STATE)
10411

    
10412
    # NIC processing
10413
    self.nic_pnew = {}
10414
    self.nic_pinst = {}
10415
    for nic_op, nic_dict in self.op.nics:
10416
      if nic_op == constants.DDM_REMOVE:
10417
        if not instance.nics:
10418
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10419
                                     errors.ECODE_INVAL)
10420
        continue
10421
      if nic_op != constants.DDM_ADD:
10422
        # an existing nic
10423
        if not instance.nics:
10424
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10425
                                     " no NICs" % nic_op,
10426
                                     errors.ECODE_INVAL)
10427
        if nic_op < 0 or nic_op >= len(instance.nics):
10428
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10429
                                     " are 0 to %d" %
10430
                                     (nic_op, len(instance.nics) - 1),
10431
                                     errors.ECODE_INVAL)
10432
        old_nic_params = instance.nics[nic_op].nicparams
10433
        old_nic_ip = instance.nics[nic_op].ip
10434
      else:
10435
        old_nic_params = {}
10436
        old_nic_ip = None
10437

    
10438
      update_params_dict = dict([(key, nic_dict[key])
10439
                                 for key in constants.NICS_PARAMETERS
10440
                                 if key in nic_dict])
10441

    
10442
      if 'bridge' in nic_dict:
10443
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10444

    
10445
      new_nic_params = _GetUpdatedParams(old_nic_params,
10446
                                         update_params_dict)
10447
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10448
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10449
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10450
      self.nic_pinst[nic_op] = new_nic_params
10451
      self.nic_pnew[nic_op] = new_filled_nic_params
10452
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10453

    
10454
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10455
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10456
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10457
        if msg:
10458
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10459
          if self.op.force:
10460
            self.warn.append(msg)
10461
          else:
10462
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10463
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10464
        if constants.INIC_IP in nic_dict:
10465
          nic_ip = nic_dict[constants.INIC_IP]
10466
        else:
10467
          nic_ip = old_nic_ip
10468
        if nic_ip is None:
10469
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10470
                                     ' on a routed nic', errors.ECODE_INVAL)
10471
      if constants.INIC_MAC in nic_dict:
10472
        nic_mac = nic_dict[constants.INIC_MAC]
10473
        if nic_mac is None:
10474
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10475
                                     errors.ECODE_INVAL)
10476
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10477
          # otherwise generate the mac
10478
          nic_dict[constants.INIC_MAC] = \
10479
            self.cfg.GenerateMAC(self.proc.GetECId())
10480
        else:
10481
          # or validate/reserve the current one
10482
          try:
10483
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10484
          except errors.ReservationError:
10485
            raise errors.OpPrereqError("MAC address %s already in use"
10486
                                       " in cluster" % nic_mac,
10487
                                       errors.ECODE_NOTUNIQUE)
10488

    
10489
    # DISK processing
10490
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10491
      raise errors.OpPrereqError("Disk operations not supported for"
10492
                                 " diskless instances",
10493
                                 errors.ECODE_INVAL)
10494
    for disk_op, _ in self.op.disks:
10495
      if disk_op == constants.DDM_REMOVE:
10496
        if len(instance.disks) == 1:
10497
          raise errors.OpPrereqError("Cannot remove the last disk of"
10498
                                     " an instance", errors.ECODE_INVAL)
10499
        _CheckInstanceDown(self, instance, "cannot remove disks")
10500

    
10501
      if (disk_op == constants.DDM_ADD and
10502
          len(instance.disks) >= constants.MAX_DISKS):
10503
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10504
                                   " add more" % constants.MAX_DISKS,
10505
                                   errors.ECODE_STATE)
10506
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10507
        # an existing disk
10508
        if disk_op < 0 or disk_op >= len(instance.disks):
10509
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10510
                                     " are 0 to %d" %
10511
                                     (disk_op, len(instance.disks)),
10512
                                     errors.ECODE_INVAL)
10513

    
10514
    return
10515

    
10516
  def _ConvertPlainToDrbd(self, feedback_fn):
10517
    """Converts an instance from plain to drbd.
10518

10519
    """
10520
    feedback_fn("Converting template to drbd")
10521
    instance = self.instance
10522
    pnode = instance.primary_node
10523
    snode = self.op.remote_node
10524

    
10525
    # create a fake disk info for _GenerateDiskTemplate
10526
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10527
                  constants.IDISK_VG: d.logical_id[0]}
10528
                 for d in instance.disks]
10529
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10530
                                      instance.name, pnode, [snode],
10531
                                      disk_info, None, None, 0, feedback_fn)
10532
    info = _GetInstanceInfoText(instance)
10533
    feedback_fn("Creating aditional volumes...")
10534
    # first, create the missing data and meta devices
10535
    for disk in new_disks:
10536
      # unfortunately this is... not too nice
10537
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10538
                            info, True)
10539
      for child in disk.children:
10540
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10541
    # at this stage, all new LVs have been created, we can rename the
10542
    # old ones
10543
    feedback_fn("Renaming original volumes...")
10544
    rename_list = [(o, n.children[0].logical_id)
10545
                   for (o, n) in zip(instance.disks, new_disks)]
10546
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10547
    result.Raise("Failed to rename original LVs")
10548

    
10549
    feedback_fn("Initializing DRBD devices...")
10550
    # all child devices are in place, we can now create the DRBD devices
10551
    for disk in new_disks:
10552
      for node in [pnode, snode]:
10553
        f_create = node == pnode
10554
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10555

    
10556
    # at this point, the instance has been modified
10557
    instance.disk_template = constants.DT_DRBD8
10558
    instance.disks = new_disks
10559
    self.cfg.Update(instance, feedback_fn)
10560

    
10561
    # disks are created, waiting for sync
10562
    disk_abort = not _WaitForSync(self, instance,
10563
                                  oneshot=not self.op.wait_for_sync)
10564
    if disk_abort:
10565
      raise errors.OpExecError("There are some degraded disks for"
10566
                               " this instance, please cleanup manually")
10567

    
10568
  def _ConvertDrbdToPlain(self, feedback_fn):
10569
    """Converts an instance from drbd to plain.
10570

10571
    """
10572
    instance = self.instance
10573
    assert len(instance.secondary_nodes) == 1
10574
    pnode = instance.primary_node
10575
    snode = instance.secondary_nodes[0]
10576
    feedback_fn("Converting template to plain")
10577

    
10578
    old_disks = instance.disks
10579
    new_disks = [d.children[0] for d in old_disks]
10580

    
10581
    # copy over size and mode
10582
    for parent, child in zip(old_disks, new_disks):
10583
      child.size = parent.size
10584
      child.mode = parent.mode
10585

    
10586
    # update instance structure
10587
    instance.disks = new_disks
10588
    instance.disk_template = constants.DT_PLAIN
10589
    self.cfg.Update(instance, feedback_fn)
10590

    
10591
    feedback_fn("Removing volumes on the secondary node...")
10592
    for disk in old_disks:
10593
      self.cfg.SetDiskID(disk, snode)
10594
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10595
      if msg:
10596
        self.LogWarning("Could not remove block device %s on node %s,"
10597
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10598

    
10599
    feedback_fn("Removing unneeded volumes on the primary node...")
10600
    for idx, disk in enumerate(old_disks):
10601
      meta = disk.children[1]
10602
      self.cfg.SetDiskID(meta, pnode)
10603
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10604
      if msg:
10605
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10606
                        " continuing anyway: %s", idx, pnode, msg)
10607

    
10608
  def Exec(self, feedback_fn):
10609
    """Modifies an instance.
10610

10611
    All parameters take effect only at the next restart of the instance.
10612

10613
    """
10614
    # Process here the warnings from CheckPrereq, as we don't have a
10615
    # feedback_fn there.
10616
    for warn in self.warn:
10617
      feedback_fn("WARNING: %s" % warn)
10618

    
10619
    result = []
10620
    instance = self.instance
10621
    # disk changes
10622
    for disk_op, disk_dict in self.op.disks:
10623
      if disk_op == constants.DDM_REMOVE:
10624
        # remove the last disk
10625
        device = instance.disks.pop()
10626
        device_idx = len(instance.disks)
10627
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10628
          self.cfg.SetDiskID(disk, node)
10629
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10630
          if msg:
10631
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10632
                            " continuing anyway", device_idx, node, msg)
10633
        result.append(("disk/%d" % device_idx, "remove"))
10634
      elif disk_op == constants.DDM_ADD:
10635
        # add a new disk
10636
        if instance.disk_template in (constants.DT_FILE,
10637
                                        constants.DT_SHARED_FILE):
10638
          file_driver, file_path = instance.disks[0].logical_id
10639
          file_path = os.path.dirname(file_path)
10640
        else:
10641
          file_driver = file_path = None
10642
        disk_idx_base = len(instance.disks)
10643
        new_disk = _GenerateDiskTemplate(self,
10644
                                         instance.disk_template,
10645
                                         instance.name, instance.primary_node,
10646
                                         instance.secondary_nodes,
10647
                                         [disk_dict],
10648
                                         file_path,
10649
                                         file_driver,
10650
                                         disk_idx_base, feedback_fn)[0]
10651
        instance.disks.append(new_disk)
10652
        info = _GetInstanceInfoText(instance)
10653

    
10654
        logging.info("Creating volume %s for instance %s",
10655
                     new_disk.iv_name, instance.name)
10656
        # Note: this needs to be kept in sync with _CreateDisks
10657
        #HARDCODE
10658
        for node in instance.all_nodes:
10659
          f_create = node == instance.primary_node
10660
          try:
10661
            _CreateBlockDev(self, node, instance, new_disk,
10662
                            f_create, info, f_create)
10663
          except errors.OpExecError, err:
10664
            self.LogWarning("Failed to create volume %s (%s) on"
10665
                            " node %s: %s",
10666
                            new_disk.iv_name, new_disk, node, err)
10667
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10668
                       (new_disk.size, new_disk.mode)))
10669
      else:
10670
        # change a given disk
10671
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10672
        result.append(("disk.mode/%d" % disk_op,
10673
                       disk_dict[constants.IDISK_MODE]))
10674

    
10675
    if self.op.disk_template:
10676
      r_shut = _ShutdownInstanceDisks(self, instance)
10677
      if not r_shut:
10678
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10679
                                 " proceed with disk template conversion")
10680
      mode = (instance.disk_template, self.op.disk_template)
10681
      try:
10682
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10683
      except:
10684
        self.cfg.ReleaseDRBDMinors(instance.name)
10685
        raise
10686
      result.append(("disk_template", self.op.disk_template))
10687

    
10688
    # NIC changes
10689
    for nic_op, nic_dict in self.op.nics:
10690
      if nic_op == constants.DDM_REMOVE:
10691
        # remove the last nic
10692
        del instance.nics[-1]
10693
        result.append(("nic.%d" % len(instance.nics), "remove"))
10694
      elif nic_op == constants.DDM_ADD:
10695
        # mac and bridge should be set, by now
10696
        mac = nic_dict[constants.INIC_MAC]
10697
        ip = nic_dict.get(constants.INIC_IP, None)
10698
        nicparams = self.nic_pinst[constants.DDM_ADD]
10699
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10700
        instance.nics.append(new_nic)
10701
        result.append(("nic.%d" % (len(instance.nics) - 1),
10702
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10703
                       (new_nic.mac, new_nic.ip,
10704
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10705
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10706
                       )))
10707
      else:
10708
        for key in (constants.INIC_MAC, constants.INIC_IP):
10709
          if key in nic_dict:
10710
            setattr(instance.nics[nic_op], key, nic_dict[key])
10711
        if nic_op in self.nic_pinst:
10712
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10713
        for key, val in nic_dict.iteritems():
10714
          result.append(("nic.%s/%d" % (key, nic_op), val))
10715

    
10716
    # hvparams changes
10717
    if self.op.hvparams:
10718
      instance.hvparams = self.hv_inst
10719
      for key, val in self.op.hvparams.iteritems():
10720
        result.append(("hv/%s" % key, val))
10721

    
10722
    # beparams changes
10723
    if self.op.beparams:
10724
      instance.beparams = self.be_inst
10725
      for key, val in self.op.beparams.iteritems():
10726
        result.append(("be/%s" % key, val))
10727

    
10728
    # OS change
10729
    if self.op.os_name:
10730
      instance.os = self.op.os_name
10731

    
10732
    # osparams changes
10733
    if self.op.osparams:
10734
      instance.osparams = self.os_inst
10735
      for key, val in self.op.osparams.iteritems():
10736
        result.append(("os/%s" % key, val))
10737

    
10738
    self.cfg.Update(instance, feedback_fn)
10739

    
10740
    return result
10741

    
10742
  _DISK_CONVERSIONS = {
10743
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10744
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10745
    }
10746

    
10747

    
10748
class LUBackupQuery(NoHooksLU):
10749
  """Query the exports list
10750

10751
  """
10752
  REQ_BGL = False
10753

    
10754
  def ExpandNames(self):
10755
    self.needed_locks = {}
10756
    self.share_locks[locking.LEVEL_NODE] = 1
10757
    if not self.op.nodes:
10758
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10759
    else:
10760
      self.needed_locks[locking.LEVEL_NODE] = \
10761
        _GetWantedNodes(self, self.op.nodes)
10762

    
10763
  def Exec(self, feedback_fn):
10764
    """Compute the list of all the exported system images.
10765

10766
    @rtype: dict
10767
    @return: a dictionary with the structure node->(export-list)
10768
        where export-list is a list of the instances exported on
10769
        that node.
10770

10771
    """
10772
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10773
    rpcresult = self.rpc.call_export_list(self.nodes)
10774
    result = {}
10775
    for node in rpcresult:
10776
      if rpcresult[node].fail_msg:
10777
        result[node] = False
10778
      else:
10779
        result[node] = rpcresult[node].payload
10780

    
10781
    return result
10782

    
10783

    
10784
class LUBackupPrepare(NoHooksLU):
10785
  """Prepares an instance for an export and returns useful information.
10786

10787
  """
10788
  REQ_BGL = False
10789

    
10790
  def ExpandNames(self):
10791
    self._ExpandAndLockInstance()
10792

    
10793
  def CheckPrereq(self):
10794
    """Check prerequisites.
10795

10796
    """
10797
    instance_name = self.op.instance_name
10798

    
10799
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10800
    assert self.instance is not None, \
10801
          "Cannot retrieve locked instance %s" % self.op.instance_name
10802
    _CheckNodeOnline(self, self.instance.primary_node)
10803

    
10804
    self._cds = _GetClusterDomainSecret()
10805

    
10806
  def Exec(self, feedback_fn):
10807
    """Prepares an instance for an export.
10808

10809
    """
10810
    instance = self.instance
10811

    
10812
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10813
      salt = utils.GenerateSecret(8)
10814

    
10815
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10816
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10817
                                              constants.RIE_CERT_VALIDITY)
10818
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10819

    
10820
      (name, cert_pem) = result.payload
10821

    
10822
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10823
                                             cert_pem)
10824

    
10825
      return {
10826
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10827
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10828
                          salt),
10829
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10830
        }
10831

    
10832
    return None
10833

    
10834

    
10835
class LUBackupExport(LogicalUnit):
10836
  """Export an instance to an image in the cluster.
10837

10838
  """
10839
  HPATH = "instance-export"
10840
  HTYPE = constants.HTYPE_INSTANCE
10841
  REQ_BGL = False
10842

    
10843
  def CheckArguments(self):
10844
    """Check the arguments.
10845

10846
    """
10847
    self.x509_key_name = self.op.x509_key_name
10848
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10849

    
10850
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10851
      if not self.x509_key_name:
10852
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10853
                                   errors.ECODE_INVAL)
10854

    
10855
      if not self.dest_x509_ca_pem:
10856
        raise errors.OpPrereqError("Missing destination X509 CA",
10857
                                   errors.ECODE_INVAL)
10858

    
10859
  def ExpandNames(self):
10860
    self._ExpandAndLockInstance()
10861

    
10862
    # Lock all nodes for local exports
10863
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10864
      # FIXME: lock only instance primary and destination node
10865
      #
10866
      # Sad but true, for now we have do lock all nodes, as we don't know where
10867
      # the previous export might be, and in this LU we search for it and
10868
      # remove it from its current node. In the future we could fix this by:
10869
      #  - making a tasklet to search (share-lock all), then create the
10870
      #    new one, then one to remove, after
10871
      #  - removing the removal operation altogether
10872
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10873

    
10874
  def DeclareLocks(self, level):
10875
    """Last minute lock declaration."""
10876
    # All nodes are locked anyway, so nothing to do here.
10877

    
10878
  def BuildHooksEnv(self):
10879
    """Build hooks env.
10880

10881
    This will run on the master, primary node and target node.
10882

10883
    """
10884
    env = {
10885
      "EXPORT_MODE": self.op.mode,
10886
      "EXPORT_NODE": self.op.target_node,
10887
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10888
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10889
      # TODO: Generic function for boolean env variables
10890
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10891
      }
10892

    
10893
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10894

    
10895
    return env
10896

    
10897
  def BuildHooksNodes(self):
10898
    """Build hooks nodes.
10899

10900
    """
10901
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10902

    
10903
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10904
      nl.append(self.op.target_node)
10905

    
10906
    return (nl, nl)
10907

    
10908
  def CheckPrereq(self):
10909
    """Check prerequisites.
10910

10911
    This checks that the instance and node names are valid.
10912

10913
    """
10914
    instance_name = self.op.instance_name
10915

    
10916
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10917
    assert self.instance is not None, \
10918
          "Cannot retrieve locked instance %s" % self.op.instance_name
10919
    _CheckNodeOnline(self, self.instance.primary_node)
10920

    
10921
    if (self.op.remove_instance and self.instance.admin_up and
10922
        not self.op.shutdown):
10923
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10924
                                 " down before")
10925

    
10926
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10927
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10928
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10929
      assert self.dst_node is not None
10930

    
10931
      _CheckNodeOnline(self, self.dst_node.name)
10932
      _CheckNodeNotDrained(self, self.dst_node.name)
10933

    
10934
      self._cds = None
10935
      self.dest_disk_info = None
10936
      self.dest_x509_ca = None
10937

    
10938
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10939
      self.dst_node = None
10940

    
10941
      if len(self.op.target_node) != len(self.instance.disks):
10942
        raise errors.OpPrereqError(("Received destination information for %s"
10943
                                    " disks, but instance %s has %s disks") %
10944
                                   (len(self.op.target_node), instance_name,
10945
                                    len(self.instance.disks)),
10946
                                   errors.ECODE_INVAL)
10947

    
10948
      cds = _GetClusterDomainSecret()
10949

    
10950
      # Check X509 key name
10951
      try:
10952
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10953
      except (TypeError, ValueError), err:
10954
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10955

    
10956
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10957
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10958
                                   errors.ECODE_INVAL)
10959

    
10960
      # Load and verify CA
10961
      try:
10962
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10963
      except OpenSSL.crypto.Error, err:
10964
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10965
                                   (err, ), errors.ECODE_INVAL)
10966

    
10967
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10968
      if errcode is not None:
10969
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10970
                                   (msg, ), errors.ECODE_INVAL)
10971

    
10972
      self.dest_x509_ca = cert
10973

    
10974
      # Verify target information
10975
      disk_info = []
10976
      for idx, disk_data in enumerate(self.op.target_node):
10977
        try:
10978
          (host, port, magic) = \
10979
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10980
        except errors.GenericError, err:
10981
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10982
                                     (idx, err), errors.ECODE_INVAL)
10983

    
10984
        disk_info.append((host, port, magic))
10985

    
10986
      assert len(disk_info) == len(self.op.target_node)
10987
      self.dest_disk_info = disk_info
10988

    
10989
    else:
10990
      raise errors.ProgrammerError("Unhandled export mode %r" %
10991
                                   self.op.mode)
10992

    
10993
    # instance disk type verification
10994
    # TODO: Implement export support for file-based disks
10995
    for disk in self.instance.disks:
10996
      if disk.dev_type == constants.LD_FILE:
10997
        raise errors.OpPrereqError("Export not supported for instances with"
10998
                                   " file-based disks", errors.ECODE_INVAL)
10999

    
11000
  def _CleanupExports(self, feedback_fn):
11001
    """Removes exports of current instance from all other nodes.
11002

11003
    If an instance in a cluster with nodes A..D was exported to node C, its
11004
    exports will be removed from the nodes A, B and D.
11005

11006
    """
11007
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
11008

    
11009
    nodelist = self.cfg.GetNodeList()
11010
    nodelist.remove(self.dst_node.name)
11011

    
11012
    # on one-node clusters nodelist will be empty after the removal
11013
    # if we proceed the backup would be removed because OpBackupQuery
11014
    # substitutes an empty list with the full cluster node list.
11015
    iname = self.instance.name
11016
    if nodelist:
11017
      feedback_fn("Removing old exports for instance %s" % iname)
11018
      exportlist = self.rpc.call_export_list(nodelist)
11019
      for node in exportlist:
11020
        if exportlist[node].fail_msg:
11021
          continue
11022
        if iname in exportlist[node].payload:
11023
          msg = self.rpc.call_export_remove(node, iname).fail_msg
11024
          if msg:
11025
            self.LogWarning("Could not remove older export for instance %s"
11026
                            " on node %s: %s", iname, node, msg)
11027

    
11028
  def Exec(self, feedback_fn):
11029
    """Export an instance to an image in the cluster.
11030

11031
    """
11032
    assert self.op.mode in constants.EXPORT_MODES
11033

    
11034
    instance = self.instance
11035
    src_node = instance.primary_node
11036

    
11037
    if self.op.shutdown:
11038
      # shutdown the instance, but not the disks
11039
      feedback_fn("Shutting down instance %s" % instance.name)
11040
      result = self.rpc.call_instance_shutdown(src_node, instance,
11041
                                               self.op.shutdown_timeout)
11042
      # TODO: Maybe ignore failures if ignore_remove_failures is set
11043
      result.Raise("Could not shutdown instance %s on"
11044
                   " node %s" % (instance.name, src_node))
11045

    
11046
    # set the disks ID correctly since call_instance_start needs the
11047
    # correct drbd minor to create the symlinks
11048
    for disk in instance.disks:
11049
      self.cfg.SetDiskID(disk, src_node)
11050

    
11051
    activate_disks = (not instance.admin_up)
11052

    
11053
    if activate_disks:
11054
      # Activate the instance disks if we'exporting a stopped instance
11055
      feedback_fn("Activating disks for %s" % instance.name)
11056
      _StartInstanceDisks(self, instance, None)
11057

    
11058
    try:
11059
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
11060
                                                     instance)
11061

    
11062
      helper.CreateSnapshots()
11063
      try:
11064
        if (self.op.shutdown and instance.admin_up and
11065
            not self.op.remove_instance):
11066
          assert not activate_disks
11067
          feedback_fn("Starting instance %s" % instance.name)
11068
          result = self.rpc.call_instance_start(src_node, instance, None, None)
11069
          msg = result.fail_msg
11070
          if msg:
11071
            feedback_fn("Failed to start instance: %s" % msg)
11072
            _ShutdownInstanceDisks(self, instance)
11073
            raise errors.OpExecError("Could not start instance: %s" % msg)
11074

    
11075
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
11076
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
11077
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11078
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
11079
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
11080

    
11081
          (key_name, _, _) = self.x509_key_name
11082

    
11083
          dest_ca_pem = \
11084
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
11085
                                            self.dest_x509_ca)
11086

    
11087
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
11088
                                                     key_name, dest_ca_pem,
11089
                                                     timeouts)
11090
      finally:
11091
        helper.Cleanup()
11092

    
11093
      # Check for backwards compatibility
11094
      assert len(dresults) == len(instance.disks)
11095
      assert compat.all(isinstance(i, bool) for i in dresults), \
11096
             "Not all results are boolean: %r" % dresults
11097

    
11098
    finally:
11099
      if activate_disks:
11100
        feedback_fn("Deactivating disks for %s" % instance.name)
11101
        _ShutdownInstanceDisks(self, instance)
11102

    
11103
    if not (compat.all(dresults) and fin_resu):
11104
      failures = []
11105
      if not fin_resu:
11106
        failures.append("export finalization")
11107
      if not compat.all(dresults):
11108
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
11109
                               if not dsk)
11110
        failures.append("disk export: disk(s) %s" % fdsk)
11111

    
11112
      raise errors.OpExecError("Export failed, errors in %s" %
11113
                               utils.CommaJoin(failures))
11114

    
11115
    # At this point, the export was successful, we can cleanup/finish
11116

    
11117
    # Remove instance if requested
11118
    if self.op.remove_instance:
11119
      feedback_fn("Removing instance %s" % instance.name)
11120
      _RemoveInstance(self, feedback_fn, instance,
11121
                      self.op.ignore_remove_failures)
11122

    
11123
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11124
      self._CleanupExports(feedback_fn)
11125

    
11126
    return fin_resu, dresults
11127

    
11128

    
11129
class LUBackupRemove(NoHooksLU):
11130
  """Remove exports related to the named instance.
11131

11132
  """
11133
  REQ_BGL = False
11134

    
11135
  def ExpandNames(self):
11136
    self.needed_locks = {}
11137
    # We need all nodes to be locked in order for RemoveExport to work, but we
11138
    # don't need to lock the instance itself, as nothing will happen to it (and
11139
    # we can remove exports also for a removed instance)
11140
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11141

    
11142
  def Exec(self, feedback_fn):
11143
    """Remove any export.
11144

11145
    """
11146
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11147
    # If the instance was not found we'll try with the name that was passed in.
11148
    # This will only work if it was an FQDN, though.
11149
    fqdn_warn = False
11150
    if not instance_name:
11151
      fqdn_warn = True
11152
      instance_name = self.op.instance_name
11153

    
11154
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
11155
    exportlist = self.rpc.call_export_list(locked_nodes)
11156
    found = False
11157
    for node in exportlist:
11158
      msg = exportlist[node].fail_msg
11159
      if msg:
11160
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11161
        continue
11162
      if instance_name in exportlist[node].payload:
11163
        found = True
11164
        result = self.rpc.call_export_remove(node, instance_name)
11165
        msg = result.fail_msg
11166
        if msg:
11167
          logging.error("Could not remove export for instance %s"
11168
                        " on node %s: %s", instance_name, node, msg)
11169

    
11170
    if fqdn_warn and not found:
11171
      feedback_fn("Export not found. If trying to remove an export belonging"
11172
                  " to a deleted instance please use its Fully Qualified"
11173
                  " Domain Name.")
11174

    
11175

    
11176
class LUGroupAdd(LogicalUnit):
11177
  """Logical unit for creating node groups.
11178

11179
  """
11180
  HPATH = "group-add"
11181
  HTYPE = constants.HTYPE_GROUP
11182
  REQ_BGL = False
11183

    
11184
  def ExpandNames(self):
11185
    # We need the new group's UUID here so that we can create and acquire the
11186
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11187
    # that it should not check whether the UUID exists in the configuration.
11188
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11189
    self.needed_locks = {}
11190
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11191

    
11192
  def CheckPrereq(self):
11193
    """Check prerequisites.
11194

11195
    This checks that the given group name is not an existing node group
11196
    already.
11197

11198
    """
11199
    try:
11200
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11201
    except errors.OpPrereqError:
11202
      pass
11203
    else:
11204
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11205
                                 " node group (UUID: %s)" %
11206
                                 (self.op.group_name, existing_uuid),
11207
                                 errors.ECODE_EXISTS)
11208

    
11209
    if self.op.ndparams:
11210
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11211

    
11212
  def BuildHooksEnv(self):
11213
    """Build hooks env.
11214

11215
    """
11216
    return {
11217
      "GROUP_NAME": self.op.group_name,
11218
      }
11219

    
11220
  def BuildHooksNodes(self):
11221
    """Build hooks nodes.
11222

11223
    """
11224
    mn = self.cfg.GetMasterNode()
11225
    return ([mn], [mn])
11226

    
11227
  def Exec(self, feedback_fn):
11228
    """Add the node group to the cluster.
11229

11230
    """
11231
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11232
                                  uuid=self.group_uuid,
11233
                                  alloc_policy=self.op.alloc_policy,
11234
                                  ndparams=self.op.ndparams)
11235

    
11236
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11237
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11238

    
11239

    
11240
class LUGroupAssignNodes(NoHooksLU):
11241
  """Logical unit for assigning nodes to groups.
11242

11243
  """
11244
  REQ_BGL = False
11245

    
11246
  def ExpandNames(self):
11247
    # These raise errors.OpPrereqError on their own:
11248
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11249
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11250

    
11251
    # We want to lock all the affected nodes and groups. We have readily
11252
    # available the list of nodes, and the *destination* group. To gather the
11253
    # list of "source" groups, we need to fetch node information later on.
11254
    self.needed_locks = {
11255
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11256
      locking.LEVEL_NODE: self.op.nodes,
11257
      }
11258

    
11259
  def DeclareLocks(self, level):
11260
    if level == locking.LEVEL_NODEGROUP:
11261
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11262

    
11263
      # Try to get all affected nodes' groups without having the group or node
11264
      # lock yet. Needs verification later in the code flow.
11265
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11266

    
11267
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11268

    
11269
  def CheckPrereq(self):
11270
    """Check prerequisites.
11271

11272
    """
11273
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11274
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11275
            frozenset(self.op.nodes))
11276

    
11277
    expected_locks = (set([self.group_uuid]) |
11278
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11279
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11280
    if actual_locks != expected_locks:
11281
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11282
                               " current groups are '%s', used to be '%s'" %
11283
                               (utils.CommaJoin(expected_locks),
11284
                                utils.CommaJoin(actual_locks)))
11285

    
11286
    self.node_data = self.cfg.GetAllNodesInfo()
11287
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11288
    instance_data = self.cfg.GetAllInstancesInfo()
11289

    
11290
    if self.group is None:
11291
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11292
                               (self.op.group_name, self.group_uuid))
11293

    
11294
    (new_splits, previous_splits) = \
11295
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11296
                                             for node in self.op.nodes],
11297
                                            self.node_data, instance_data)
11298

    
11299
    if new_splits:
11300
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11301

    
11302
      if not self.op.force:
11303
        raise errors.OpExecError("The following instances get split by this"
11304
                                 " change and --force was not given: %s" %
11305
                                 fmt_new_splits)
11306
      else:
11307
        self.LogWarning("This operation will split the following instances: %s",
11308
                        fmt_new_splits)
11309

    
11310
        if previous_splits:
11311
          self.LogWarning("In addition, these already-split instances continue"
11312
                          " to be split across groups: %s",
11313
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11314

    
11315
  def Exec(self, feedback_fn):
11316
    """Assign nodes to a new group.
11317

11318
    """
11319
    for node in self.op.nodes:
11320
      self.node_data[node].group = self.group_uuid
11321

    
11322
    # FIXME: Depends on side-effects of modifying the result of
11323
    # C{cfg.GetAllNodesInfo}
11324

    
11325
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11326

    
11327
  @staticmethod
11328
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11329
    """Check for split instances after a node assignment.
11330

11331
    This method considers a series of node assignments as an atomic operation,
11332
    and returns information about split instances after applying the set of
11333
    changes.
11334

11335
    In particular, it returns information about newly split instances, and
11336
    instances that were already split, and remain so after the change.
11337

11338
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11339
    considered.
11340

11341
    @type changes: list of (node_name, new_group_uuid) pairs.
11342
    @param changes: list of node assignments to consider.
11343
    @param node_data: a dict with data for all nodes
11344
    @param instance_data: a dict with all instances to consider
11345
    @rtype: a two-tuple
11346
    @return: a list of instances that were previously okay and result split as a
11347
      consequence of this change, and a list of instances that were previously
11348
      split and this change does not fix.
11349

11350
    """
11351
    changed_nodes = dict((node, group) for node, group in changes
11352
                         if node_data[node].group != group)
11353

    
11354
    all_split_instances = set()
11355
    previously_split_instances = set()
11356

    
11357
    def InstanceNodes(instance):
11358
      return [instance.primary_node] + list(instance.secondary_nodes)
11359

    
11360
    for inst in instance_data.values():
11361
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11362
        continue
11363

    
11364
      instance_nodes = InstanceNodes(inst)
11365

    
11366
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11367
        previously_split_instances.add(inst.name)
11368

    
11369
      if len(set(changed_nodes.get(node, node_data[node].group)
11370
                 for node in instance_nodes)) > 1:
11371
        all_split_instances.add(inst.name)
11372

    
11373
    return (list(all_split_instances - previously_split_instances),
11374
            list(previously_split_instances & all_split_instances))
11375

    
11376

    
11377
class _GroupQuery(_QueryBase):
11378
  FIELDS = query.GROUP_FIELDS
11379

    
11380
  def ExpandNames(self, lu):
11381
    lu.needed_locks = {}
11382

    
11383
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11384
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11385

    
11386
    if not self.names:
11387
      self.wanted = [name_to_uuid[name]
11388
                     for name in utils.NiceSort(name_to_uuid.keys())]
11389
    else:
11390
      # Accept names to be either names or UUIDs.
11391
      missing = []
11392
      self.wanted = []
11393
      all_uuid = frozenset(self._all_groups.keys())
11394

    
11395
      for name in self.names:
11396
        if name in all_uuid:
11397
          self.wanted.append(name)
11398
        elif name in name_to_uuid:
11399
          self.wanted.append(name_to_uuid[name])
11400
        else:
11401
          missing.append(name)
11402

    
11403
      if missing:
11404
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11405
                                   utils.CommaJoin(missing),
11406
                                   errors.ECODE_NOENT)
11407

    
11408
  def DeclareLocks(self, lu, level):
11409
    pass
11410

    
11411
  def _GetQueryData(self, lu):
11412
    """Computes the list of node groups and their attributes.
11413

11414
    """
11415
    do_nodes = query.GQ_NODE in self.requested_data
11416
    do_instances = query.GQ_INST in self.requested_data
11417

    
11418
    group_to_nodes = None
11419
    group_to_instances = None
11420

    
11421
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11422
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11423
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11424
    # instance->node. Hence, we will need to process nodes even if we only need
11425
    # instance information.
11426
    if do_nodes or do_instances:
11427
      all_nodes = lu.cfg.GetAllNodesInfo()
11428
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11429
      node_to_group = {}
11430

    
11431
      for node in all_nodes.values():
11432
        if node.group in group_to_nodes:
11433
          group_to_nodes[node.group].append(node.name)
11434
          node_to_group[node.name] = node.group
11435

    
11436
      if do_instances:
11437
        all_instances = lu.cfg.GetAllInstancesInfo()
11438
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11439

    
11440
        for instance in all_instances.values():
11441
          node = instance.primary_node
11442
          if node in node_to_group:
11443
            group_to_instances[node_to_group[node]].append(instance.name)
11444

    
11445
        if not do_nodes:
11446
          # Do not pass on node information if it was not requested.
11447
          group_to_nodes = None
11448

    
11449
    return query.GroupQueryData([self._all_groups[uuid]
11450
                                 for uuid in self.wanted],
11451
                                group_to_nodes, group_to_instances)
11452

    
11453

    
11454
class LUGroupQuery(NoHooksLU):
11455
  """Logical unit for querying node groups.
11456

11457
  """
11458
  REQ_BGL = False
11459

    
11460
  def CheckArguments(self):
11461
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11462
                          self.op.output_fields, False)
11463

    
11464
  def ExpandNames(self):
11465
    self.gq.ExpandNames(self)
11466

    
11467
  def Exec(self, feedback_fn):
11468
    return self.gq.OldStyleQuery(self)
11469

    
11470

    
11471
class LUGroupSetParams(LogicalUnit):
11472
  """Modifies the parameters of a node group.
11473

11474
  """
11475
  HPATH = "group-modify"
11476
  HTYPE = constants.HTYPE_GROUP
11477
  REQ_BGL = False
11478

    
11479
  def CheckArguments(self):
11480
    all_changes = [
11481
      self.op.ndparams,
11482
      self.op.alloc_policy,
11483
      ]
11484

    
11485
    if all_changes.count(None) == len(all_changes):
11486
      raise errors.OpPrereqError("Please pass at least one modification",
11487
                                 errors.ECODE_INVAL)
11488

    
11489
  def ExpandNames(self):
11490
    # This raises errors.OpPrereqError on its own:
11491
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11492

    
11493
    self.needed_locks = {
11494
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11495
      }
11496

    
11497
  def CheckPrereq(self):
11498
    """Check prerequisites.
11499

11500
    """
11501
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11502

    
11503
    if self.group is None:
11504
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11505
                               (self.op.group_name, self.group_uuid))
11506

    
11507
    if self.op.ndparams:
11508
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11509
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11510
      self.new_ndparams = new_ndparams
11511

    
11512
  def BuildHooksEnv(self):
11513
    """Build hooks env.
11514

11515
    """
11516
    return {
11517
      "GROUP_NAME": self.op.group_name,
11518
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11519
      }
11520

    
11521
  def BuildHooksNodes(self):
11522
    """Build hooks nodes.
11523

11524
    """
11525
    mn = self.cfg.GetMasterNode()
11526
    return ([mn], [mn])
11527

    
11528
  def Exec(self, feedback_fn):
11529
    """Modifies the node group.
11530

11531
    """
11532
    result = []
11533

    
11534
    if self.op.ndparams:
11535
      self.group.ndparams = self.new_ndparams
11536
      result.append(("ndparams", str(self.group.ndparams)))
11537

    
11538
    if self.op.alloc_policy:
11539
      self.group.alloc_policy = self.op.alloc_policy
11540

    
11541
    self.cfg.Update(self.group, feedback_fn)
11542
    return result
11543

    
11544

    
11545

    
11546
class LUGroupRemove(LogicalUnit):
11547
  HPATH = "group-remove"
11548
  HTYPE = constants.HTYPE_GROUP
11549
  REQ_BGL = False
11550

    
11551
  def ExpandNames(self):
11552
    # This will raises errors.OpPrereqError on its own:
11553
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11554
    self.needed_locks = {
11555
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11556
      }
11557

    
11558
  def CheckPrereq(self):
11559
    """Check prerequisites.
11560

11561
    This checks that the given group name exists as a node group, that is
11562
    empty (i.e., contains no nodes), and that is not the last group of the
11563
    cluster.
11564

11565
    """
11566
    # Verify that the group is empty.
11567
    group_nodes = [node.name
11568
                   for node in self.cfg.GetAllNodesInfo().values()
11569
                   if node.group == self.group_uuid]
11570

    
11571
    if group_nodes:
11572
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11573
                                 " nodes: %s" %
11574
                                 (self.op.group_name,
11575
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11576
                                 errors.ECODE_STATE)
11577

    
11578
    # Verify the cluster would not be left group-less.
11579
    if len(self.cfg.GetNodeGroupList()) == 1:
11580
      raise errors.OpPrereqError("Group '%s' is the only group,"
11581
                                 " cannot be removed" %
11582
                                 self.op.group_name,
11583
                                 errors.ECODE_STATE)
11584

    
11585
  def BuildHooksEnv(self):
11586
    """Build hooks env.
11587

11588
    """
11589
    return {
11590
      "GROUP_NAME": self.op.group_name,
11591
      }
11592

    
11593
  def BuildHooksNodes(self):
11594
    """Build hooks nodes.
11595

11596
    """
11597
    mn = self.cfg.GetMasterNode()
11598
    return ([mn], [mn])
11599

    
11600
  def Exec(self, feedback_fn):
11601
    """Remove the node group.
11602

11603
    """
11604
    try:
11605
      self.cfg.RemoveNodeGroup(self.group_uuid)
11606
    except errors.ConfigurationError:
11607
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11608
                               (self.op.group_name, self.group_uuid))
11609

    
11610
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11611

    
11612

    
11613
class LUGroupRename(LogicalUnit):
11614
  HPATH = "group-rename"
11615
  HTYPE = constants.HTYPE_GROUP
11616
  REQ_BGL = False
11617

    
11618
  def ExpandNames(self):
11619
    # This raises errors.OpPrereqError on its own:
11620
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11621

    
11622
    self.needed_locks = {
11623
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11624
      }
11625

    
11626
  def CheckPrereq(self):
11627
    """Check prerequisites.
11628

11629
    Ensures requested new name is not yet used.
11630

11631
    """
11632
    try:
11633
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11634
    except errors.OpPrereqError:
11635
      pass
11636
    else:
11637
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11638
                                 " node group (UUID: %s)" %
11639
                                 (self.op.new_name, new_name_uuid),
11640
                                 errors.ECODE_EXISTS)
11641

    
11642
  def BuildHooksEnv(self):
11643
    """Build hooks env.
11644

11645
    """
11646
    return {
11647
      "OLD_NAME": self.op.group_name,
11648
      "NEW_NAME": self.op.new_name,
11649
      }
11650

    
11651
  def BuildHooksNodes(self):
11652
    """Build hooks nodes.
11653

11654
    """
11655
    mn = self.cfg.GetMasterNode()
11656

    
11657
    all_nodes = self.cfg.GetAllNodesInfo()
11658
    all_nodes.pop(mn, None)
11659

    
11660
    run_nodes = [mn]
11661
    run_nodes.extend(node.name for node in all_nodes.values()
11662
                     if node.group == self.group_uuid)
11663

    
11664
    return (run_nodes, run_nodes)
11665

    
11666
  def Exec(self, feedback_fn):
11667
    """Rename the node group.
11668

11669
    """
11670
    group = self.cfg.GetNodeGroup(self.group_uuid)
11671

    
11672
    if group is None:
11673
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11674
                               (self.op.group_name, self.group_uuid))
11675

    
11676
    group.name = self.op.new_name
11677
    self.cfg.Update(group, feedback_fn)
11678

    
11679
    return self.op.new_name
11680

    
11681

    
11682
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11683
  """Generic tags LU.
11684

11685
  This is an abstract class which is the parent of all the other tags LUs.
11686

11687
  """
11688
  def ExpandNames(self):
11689
    self.group_uuid = None
11690
    self.needed_locks = {}
11691
    if self.op.kind == constants.TAG_NODE:
11692
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11693
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11694
    elif self.op.kind == constants.TAG_INSTANCE:
11695
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11696
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11697
    elif self.op.kind == constants.TAG_NODEGROUP:
11698
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
11699

    
11700
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11701
    # not possible to acquire the BGL based on opcode parameters)
11702

    
11703
  def CheckPrereq(self):
11704
    """Check prerequisites.
11705

11706
    """
11707
    if self.op.kind == constants.TAG_CLUSTER:
11708
      self.target = self.cfg.GetClusterInfo()
11709
    elif self.op.kind == constants.TAG_NODE:
11710
      self.target = self.cfg.GetNodeInfo(self.op.name)
11711
    elif self.op.kind == constants.TAG_INSTANCE:
11712
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11713
    elif self.op.kind == constants.TAG_NODEGROUP:
11714
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
11715
    else:
11716
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11717
                                 str(self.op.kind), errors.ECODE_INVAL)
11718

    
11719

    
11720
class LUTagsGet(TagsLU):
11721
  """Returns the tags of a given object.
11722

11723
  """
11724
  REQ_BGL = False
11725

    
11726
  def ExpandNames(self):
11727
    TagsLU.ExpandNames(self)
11728

    
11729
    # Share locks as this is only a read operation
11730
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11731

    
11732
  def Exec(self, feedback_fn):
11733
    """Returns the tag list.
11734

11735
    """
11736
    return list(self.target.GetTags())
11737

    
11738

    
11739
class LUTagsSearch(NoHooksLU):
11740
  """Searches the tags for a given pattern.
11741

11742
  """
11743
  REQ_BGL = False
11744

    
11745
  def ExpandNames(self):
11746
    self.needed_locks = {}
11747

    
11748
  def CheckPrereq(self):
11749
    """Check prerequisites.
11750

11751
    This checks the pattern passed for validity by compiling it.
11752

11753
    """
11754
    try:
11755
      self.re = re.compile(self.op.pattern)
11756
    except re.error, err:
11757
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11758
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11759

    
11760
  def Exec(self, feedback_fn):
11761
    """Returns the tag list.
11762

11763
    """
11764
    cfg = self.cfg
11765
    tgts = [("/cluster", cfg.GetClusterInfo())]
11766
    ilist = cfg.GetAllInstancesInfo().values()
11767
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11768
    nlist = cfg.GetAllNodesInfo().values()
11769
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11770
    tgts.extend(("/nodegroup/%s" % n.name, n)
11771
                for n in cfg.GetAllNodeGroupsInfo().values())
11772
    results = []
11773
    for path, target in tgts:
11774
      for tag in target.GetTags():
11775
        if self.re.search(tag):
11776
          results.append((path, tag))
11777
    return results
11778

    
11779

    
11780
class LUTagsSet(TagsLU):
11781
  """Sets a tag on a given object.
11782

11783
  """
11784
  REQ_BGL = False
11785

    
11786
  def CheckPrereq(self):
11787
    """Check prerequisites.
11788

11789
    This checks the type and length of the tag name and value.
11790

11791
    """
11792
    TagsLU.CheckPrereq(self)
11793
    for tag in self.op.tags:
11794
      objects.TaggableObject.ValidateTag(tag)
11795

    
11796
  def Exec(self, feedback_fn):
11797
    """Sets the tag.
11798

11799
    """
11800
    try:
11801
      for tag in self.op.tags:
11802
        self.target.AddTag(tag)
11803
    except errors.TagError, err:
11804
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11805
    self.cfg.Update(self.target, feedback_fn)
11806

    
11807

    
11808
class LUTagsDel(TagsLU):
11809
  """Delete a list of tags from a given object.
11810

11811
  """
11812
  REQ_BGL = False
11813

    
11814
  def CheckPrereq(self):
11815
    """Check prerequisites.
11816

11817
    This checks that we have the given tag.
11818

11819
    """
11820
    TagsLU.CheckPrereq(self)
11821
    for tag in self.op.tags:
11822
      objects.TaggableObject.ValidateTag(tag)
11823
    del_tags = frozenset(self.op.tags)
11824
    cur_tags = self.target.GetTags()
11825

    
11826
    diff_tags = del_tags - cur_tags
11827
    if diff_tags:
11828
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11829
      raise errors.OpPrereqError("Tag(s) %s not found" %
11830
                                 (utils.CommaJoin(diff_names), ),
11831
                                 errors.ECODE_NOENT)
11832

    
11833
  def Exec(self, feedback_fn):
11834
    """Remove the tag from the object.
11835

11836
    """
11837
    for tag in self.op.tags:
11838
      self.target.RemoveTag(tag)
11839
    self.cfg.Update(self.target, feedback_fn)
11840

    
11841

    
11842
class LUTestDelay(NoHooksLU):
11843
  """Sleep for a specified amount of time.
11844

11845
  This LU sleeps on the master and/or nodes for a specified amount of
11846
  time.
11847

11848
  """
11849
  REQ_BGL = False
11850

    
11851
  def ExpandNames(self):
11852
    """Expand names and set required locks.
11853

11854
    This expands the node list, if any.
11855

11856
    """
11857
    self.needed_locks = {}
11858
    if self.op.on_nodes:
11859
      # _GetWantedNodes can be used here, but is not always appropriate to use
11860
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11861
      # more information.
11862
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11863
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11864

    
11865
  def _TestDelay(self):
11866
    """Do the actual sleep.
11867

11868
    """
11869
    if self.op.on_master:
11870
      if not utils.TestDelay(self.op.duration):
11871
        raise errors.OpExecError("Error during master delay test")
11872
    if self.op.on_nodes:
11873
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11874
      for node, node_result in result.items():
11875
        node_result.Raise("Failure during rpc call to node %s" % node)
11876

    
11877
  def Exec(self, feedback_fn):
11878
    """Execute the test delay opcode, with the wanted repetitions.
11879

11880
    """
11881
    if self.op.repeat == 0:
11882
      self._TestDelay()
11883
    else:
11884
      top_value = self.op.repeat - 1
11885
      for i in range(self.op.repeat):
11886
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11887
        self._TestDelay()
11888

    
11889

    
11890
class LUTestJqueue(NoHooksLU):
11891
  """Utility LU to test some aspects of the job queue.
11892

11893
  """
11894
  REQ_BGL = False
11895

    
11896
  # Must be lower than default timeout for WaitForJobChange to see whether it
11897
  # notices changed jobs
11898
  _CLIENT_CONNECT_TIMEOUT = 20.0
11899
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11900

    
11901
  @classmethod
11902
  def _NotifyUsingSocket(cls, cb, errcls):
11903
    """Opens a Unix socket and waits for another program to connect.
11904

11905
    @type cb: callable
11906
    @param cb: Callback to send socket name to client
11907
    @type errcls: class
11908
    @param errcls: Exception class to use for errors
11909

11910
    """
11911
    # Using a temporary directory as there's no easy way to create temporary
11912
    # sockets without writing a custom loop around tempfile.mktemp and
11913
    # socket.bind
11914
    tmpdir = tempfile.mkdtemp()
11915
    try:
11916
      tmpsock = utils.PathJoin(tmpdir, "sock")
11917

    
11918
      logging.debug("Creating temporary socket at %s", tmpsock)
11919
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11920
      try:
11921
        sock.bind(tmpsock)
11922
        sock.listen(1)
11923

    
11924
        # Send details to client
11925
        cb(tmpsock)
11926

    
11927
        # Wait for client to connect before continuing
11928
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11929
        try:
11930
          (conn, _) = sock.accept()
11931
        except socket.error, err:
11932
          raise errcls("Client didn't connect in time (%s)" % err)
11933
      finally:
11934
        sock.close()
11935
    finally:
11936
      # Remove as soon as client is connected
11937
      shutil.rmtree(tmpdir)
11938

    
11939
    # Wait for client to close
11940
    try:
11941
      try:
11942
        # pylint: disable-msg=E1101
11943
        # Instance of '_socketobject' has no ... member
11944
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11945
        conn.recv(1)
11946
      except socket.error, err:
11947
        raise errcls("Client failed to confirm notification (%s)" % err)
11948
    finally:
11949
      conn.close()
11950

    
11951
  def _SendNotification(self, test, arg, sockname):
11952
    """Sends a notification to the client.
11953

11954
    @type test: string
11955
    @param test: Test name
11956
    @param arg: Test argument (depends on test)
11957
    @type sockname: string
11958
    @param sockname: Socket path
11959

11960
    """
11961
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11962

    
11963
  def _Notify(self, prereq, test, arg):
11964
    """Notifies the client of a test.
11965

11966
    @type prereq: bool
11967
    @param prereq: Whether this is a prereq-phase test
11968
    @type test: string
11969
    @param test: Test name
11970
    @param arg: Test argument (depends on test)
11971

11972
    """
11973
    if prereq:
11974
      errcls = errors.OpPrereqError
11975
    else:
11976
      errcls = errors.OpExecError
11977

    
11978
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11979
                                                  test, arg),
11980
                                   errcls)
11981

    
11982
  def CheckArguments(self):
11983
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11984
    self.expandnames_calls = 0
11985

    
11986
  def ExpandNames(self):
11987
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11988
    if checkargs_calls < 1:
11989
      raise errors.ProgrammerError("CheckArguments was not called")
11990

    
11991
    self.expandnames_calls += 1
11992

    
11993
    if self.op.notify_waitlock:
11994
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11995

    
11996
    self.LogInfo("Expanding names")
11997

    
11998
    # Get lock on master node (just to get a lock, not for a particular reason)
11999
    self.needed_locks = {
12000
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
12001
      }
12002

    
12003
  def Exec(self, feedback_fn):
12004
    if self.expandnames_calls < 1:
12005
      raise errors.ProgrammerError("ExpandNames was not called")
12006

    
12007
    if self.op.notify_exec:
12008
      self._Notify(False, constants.JQT_EXEC, None)
12009

    
12010
    self.LogInfo("Executing")
12011

    
12012
    if self.op.log_messages:
12013
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
12014
      for idx, msg in enumerate(self.op.log_messages):
12015
        self.LogInfo("Sending log message %s", idx + 1)
12016
        feedback_fn(constants.JQT_MSGPREFIX + msg)
12017
        # Report how many test messages have been sent
12018
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
12019

    
12020
    if self.op.fail:
12021
      raise errors.OpExecError("Opcode failure was requested")
12022

    
12023
    return True
12024

    
12025

    
12026
class IAllocator(object):
12027
  """IAllocator framework.
12028

12029
  An IAllocator instance has three sets of attributes:
12030
    - cfg that is needed to query the cluster
12031
    - input data (all members of the _KEYS class attribute are required)
12032
    - four buffer attributes (in|out_data|text), that represent the
12033
      input (to the external script) in text and data structure format,
12034
      and the output from it, again in two formats
12035
    - the result variables from the script (success, info, nodes) for
12036
      easy usage
12037

12038
  """
12039
  # pylint: disable-msg=R0902
12040
  # lots of instance attributes
12041

    
12042
  def __init__(self, cfg, rpc, mode, **kwargs):
12043
    self.cfg = cfg
12044
    self.rpc = rpc
12045
    # init buffer variables
12046
    self.in_text = self.out_text = self.in_data = self.out_data = None
12047
    # init all input fields so that pylint is happy
12048
    self.mode = mode
12049
    self.memory = self.disks = self.disk_template = None
12050
    self.os = self.tags = self.nics = self.vcpus = None
12051
    self.hypervisor = None
12052
    self.relocate_from = None
12053
    self.name = None
12054
    self.evac_nodes = None
12055
    self.instances = None
12056
    self.evac_mode = None
12057
    self.target_groups = []
12058
    # computed fields
12059
    self.required_nodes = None
12060
    # init result fields
12061
    self.success = self.info = self.result = None
12062

    
12063
    try:
12064
      (fn, keydata, self._result_check) = self._MODE_DATA[self.mode]
12065
    except KeyError:
12066
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
12067
                                   " IAllocator" % self.mode)
12068

    
12069
    keyset = [n for (n, _) in keydata]
12070

    
12071
    for key in kwargs:
12072
      if key not in keyset:
12073
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
12074
                                     " IAllocator" % key)
12075
      setattr(self, key, kwargs[key])
12076

    
12077
    for key in keyset:
12078
      if key not in kwargs:
12079
        raise errors.ProgrammerError("Missing input parameter '%s' to"
12080
                                     " IAllocator" % key)
12081
    self._BuildInputData(compat.partial(fn, self), keydata)
12082

    
12083
  def _ComputeClusterData(self):
12084
    """Compute the generic allocator input data.
12085

12086
    This is the data that is independent of the actual operation.
12087

12088
    """
12089
    cfg = self.cfg
12090
    cluster_info = cfg.GetClusterInfo()
12091
    # cluster data
12092
    data = {
12093
      "version": constants.IALLOCATOR_VERSION,
12094
      "cluster_name": cfg.GetClusterName(),
12095
      "cluster_tags": list(cluster_info.GetTags()),
12096
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
12097
      # we don't have job IDs
12098
      }
12099
    ninfo = cfg.GetAllNodesInfo()
12100
    iinfo = cfg.GetAllInstancesInfo().values()
12101
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
12102

    
12103
    # node data
12104
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
12105

    
12106
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
12107
      hypervisor_name = self.hypervisor
12108
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
12109
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
12110
    else:
12111
      hypervisor_name = cluster_info.enabled_hypervisors[0]
12112

    
12113
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
12114
                                        hypervisor_name)
12115
    node_iinfo = \
12116
      self.rpc.call_all_instances_info(node_list,
12117
                                       cluster_info.enabled_hypervisors)
12118

    
12119
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
12120

    
12121
    config_ndata = self._ComputeBasicNodeData(ninfo)
12122
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12123
                                                 i_list, config_ndata)
12124
    assert len(data["nodes"]) == len(ninfo), \
12125
        "Incomplete node data computed"
12126

    
12127
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12128

    
12129
    self.in_data = data
12130

    
12131
  @staticmethod
12132
  def _ComputeNodeGroupData(cfg):
12133
    """Compute node groups data.
12134

12135
    """
12136
    ng = dict((guuid, {
12137
      "name": gdata.name,
12138
      "alloc_policy": gdata.alloc_policy,
12139
      })
12140
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12141

    
12142
    return ng
12143

    
12144
  @staticmethod
12145
  def _ComputeBasicNodeData(node_cfg):
12146
    """Compute global node data.
12147

12148
    @rtype: dict
12149
    @returns: a dict of name: (node dict, node config)
12150

12151
    """
12152
    # fill in static (config-based) values
12153
    node_results = dict((ninfo.name, {
12154
      "tags": list(ninfo.GetTags()),
12155
      "primary_ip": ninfo.primary_ip,
12156
      "secondary_ip": ninfo.secondary_ip,
12157
      "offline": ninfo.offline,
12158
      "drained": ninfo.drained,
12159
      "master_candidate": ninfo.master_candidate,
12160
      "group": ninfo.group,
12161
      "master_capable": ninfo.master_capable,
12162
      "vm_capable": ninfo.vm_capable,
12163
      })
12164
      for ninfo in node_cfg.values())
12165

    
12166
    return node_results
12167

    
12168
  @staticmethod
12169
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
12170
                              node_results):
12171
    """Compute global node data.
12172

12173
    @param node_results: the basic node structures as filled from the config
12174

12175
    """
12176
    # make a copy of the current dict
12177
    node_results = dict(node_results)
12178
    for nname, nresult in node_data.items():
12179
      assert nname in node_results, "Missing basic data for node %s" % nname
12180
      ninfo = node_cfg[nname]
12181

    
12182
      if not (ninfo.offline or ninfo.drained):
12183
        nresult.Raise("Can't get data for node %s" % nname)
12184
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
12185
                                nname)
12186
        remote_info = nresult.payload
12187

    
12188
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
12189
                     'vg_size', 'vg_free', 'cpu_total']:
12190
          if attr not in remote_info:
12191
            raise errors.OpExecError("Node '%s' didn't return attribute"
12192
                                     " '%s'" % (nname, attr))
12193
          if not isinstance(remote_info[attr], int):
12194
            raise errors.OpExecError("Node '%s' returned invalid value"
12195
                                     " for '%s': %s" %
12196
                                     (nname, attr, remote_info[attr]))
12197
        # compute memory used by primary instances
12198
        i_p_mem = i_p_up_mem = 0
12199
        for iinfo, beinfo in i_list:
12200
          if iinfo.primary_node == nname:
12201
            i_p_mem += beinfo[constants.BE_MEMORY]
12202
            if iinfo.name not in node_iinfo[nname].payload:
12203
              i_used_mem = 0
12204
            else:
12205
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
12206
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
12207
            remote_info['memory_free'] -= max(0, i_mem_diff)
12208

    
12209
            if iinfo.admin_up:
12210
              i_p_up_mem += beinfo[constants.BE_MEMORY]
12211

    
12212
        # compute memory used by instances
12213
        pnr_dyn = {
12214
          "total_memory": remote_info['memory_total'],
12215
          "reserved_memory": remote_info['memory_dom0'],
12216
          "free_memory": remote_info['memory_free'],
12217
          "total_disk": remote_info['vg_size'],
12218
          "free_disk": remote_info['vg_free'],
12219
          "total_cpus": remote_info['cpu_total'],
12220
          "i_pri_memory": i_p_mem,
12221
          "i_pri_up_memory": i_p_up_mem,
12222
          }
12223
        pnr_dyn.update(node_results[nname])
12224
        node_results[nname] = pnr_dyn
12225

    
12226
    return node_results
12227

    
12228
  @staticmethod
12229
  def _ComputeInstanceData(cluster_info, i_list):
12230
    """Compute global instance data.
12231

12232
    """
12233
    instance_data = {}
12234
    for iinfo, beinfo in i_list:
12235
      nic_data = []
12236
      for nic in iinfo.nics:
12237
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
12238
        nic_dict = {
12239
          "mac": nic.mac,
12240
          "ip": nic.ip,
12241
          "mode": filled_params[constants.NIC_MODE],
12242
          "link": filled_params[constants.NIC_LINK],
12243
          }
12244
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
12245
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
12246
        nic_data.append(nic_dict)
12247
      pir = {
12248
        "tags": list(iinfo.GetTags()),
12249
        "admin_up": iinfo.admin_up,
12250
        "vcpus": beinfo[constants.BE_VCPUS],
12251
        "memory": beinfo[constants.BE_MEMORY],
12252
        "os": iinfo.os,
12253
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12254
        "nics": nic_data,
12255
        "disks": [{constants.IDISK_SIZE: dsk.size,
12256
                   constants.IDISK_MODE: dsk.mode}
12257
                  for dsk in iinfo.disks],
12258
        "disk_template": iinfo.disk_template,
12259
        "hypervisor": iinfo.hypervisor,
12260
        }
12261
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12262
                                                 pir["disks"])
12263
      instance_data[iinfo.name] = pir
12264

    
12265
    return instance_data
12266

    
12267
  def _AddNewInstance(self):
12268
    """Add new instance data to allocator structure.
12269

12270
    This in combination with _AllocatorGetClusterData will create the
12271
    correct structure needed as input for the allocator.
12272

12273
    The checks for the completeness of the opcode must have already been
12274
    done.
12275

12276
    """
12277
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12278

    
12279
    if self.disk_template in constants.DTS_INT_MIRROR:
12280
      self.required_nodes = 2
12281
    else:
12282
      self.required_nodes = 1
12283

    
12284
    request = {
12285
      "name": self.name,
12286
      "disk_template": self.disk_template,
12287
      "tags": self.tags,
12288
      "os": self.os,
12289
      "vcpus": self.vcpus,
12290
      "memory": self.memory,
12291
      "disks": self.disks,
12292
      "disk_space_total": disk_space,
12293
      "nics": self.nics,
12294
      "required_nodes": self.required_nodes,
12295
      "hypervisor": self.hypervisor,
12296
      }
12297

    
12298
    return request
12299

    
12300
  def _AddRelocateInstance(self):
12301
    """Add relocate instance data to allocator structure.
12302

12303
    This in combination with _IAllocatorGetClusterData will create the
12304
    correct structure needed as input for the allocator.
12305

12306
    The checks for the completeness of the opcode must have already been
12307
    done.
12308

12309
    """
12310
    instance = self.cfg.GetInstanceInfo(self.name)
12311
    if instance is None:
12312
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12313
                                   " IAllocator" % self.name)
12314

    
12315
    if instance.disk_template not in constants.DTS_MIRRORED:
12316
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12317
                                 errors.ECODE_INVAL)
12318

    
12319
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12320
        len(instance.secondary_nodes) != 1:
12321
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12322
                                 errors.ECODE_STATE)
12323

    
12324
    self.required_nodes = 1
12325
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12326
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12327

    
12328
    request = {
12329
      "name": self.name,
12330
      "disk_space_total": disk_space,
12331
      "required_nodes": self.required_nodes,
12332
      "relocate_from": self.relocate_from,
12333
      }
12334
    return request
12335

    
12336
  def _AddEvacuateNodes(self):
12337
    """Add evacuate nodes data to allocator structure.
12338

12339
    """
12340
    request = {
12341
      "evac_nodes": self.evac_nodes
12342
      }
12343
    return request
12344

    
12345
  def _AddNodeEvacuate(self):
12346
    """Get data for node-evacuate requests.
12347

12348
    """
12349
    return {
12350
      "instances": self.instances,
12351
      "evac_mode": self.evac_mode,
12352
      }
12353

    
12354
  def _AddChangeGroup(self):
12355
    """Get data for node-evacuate requests.
12356

12357
    """
12358
    return {
12359
      "instances": self.instances,
12360
      "target_groups": self.target_groups,
12361
      }
12362

    
12363
  def _BuildInputData(self, fn, keydata):
12364
    """Build input data structures.
12365

12366
    """
12367
    self._ComputeClusterData()
12368

    
12369
    request = fn()
12370
    request["type"] = self.mode
12371
    for keyname, keytype in keydata:
12372
      if keyname not in request:
12373
        raise errors.ProgrammerError("Request parameter %s is missing" %
12374
                                     keyname)
12375
      val = request[keyname]
12376
      if not keytype(val):
12377
        raise errors.ProgrammerError("Request parameter %s doesn't pass"
12378
                                     " validation, value %s, expected"
12379
                                     " type %s" % (keyname, val, keytype))
12380
    self.in_data["request"] = request
12381

    
12382
    self.in_text = serializer.Dump(self.in_data)
12383

    
12384
  _STRING_LIST = ht.TListOf(ht.TString)
12385
  _JOBSET_LIST = ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12386
     # pylint: disable-msg=E1101
12387
     # Class '...' has no 'OP_ID' member
12388
     "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12389
                          opcodes.OpInstanceMigrate.OP_ID,
12390
                          opcodes.OpInstanceReplaceDisks.OP_ID])
12391
     })))
12392
  _MODE_DATA = {
12393
    constants.IALLOCATOR_MODE_ALLOC:
12394
      (_AddNewInstance,
12395
       [
12396
        ("name", ht.TString),
12397
        ("memory", ht.TInt),
12398
        ("disks", ht.TListOf(ht.TDict)),
12399
        ("disk_template", ht.TString),
12400
        ("os", ht.TString),
12401
        ("tags", _STRING_LIST),
12402
        ("nics", ht.TListOf(ht.TDict)),
12403
        ("vcpus", ht.TInt),
12404
        ("hypervisor", ht.TString),
12405
        ], ht.TList),
12406
    constants.IALLOCATOR_MODE_RELOC:
12407
      (_AddRelocateInstance,
12408
       [("name", ht.TString), ("relocate_from", _STRING_LIST)],
12409
       ht.TList),
12410
    constants.IALLOCATOR_MODE_MEVAC:
12411
      (_AddEvacuateNodes, [("evac_nodes", _STRING_LIST)],
12412
       ht.TListOf(ht.TAnd(ht.TIsLength(2), _STRING_LIST))),
12413
     constants.IALLOCATOR_MODE_NODE_EVAC:
12414
      (_AddNodeEvacuate, [
12415
        ("instances", _STRING_LIST),
12416
        ("evac_mode", ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)),
12417
        ], _JOBSET_LIST),
12418
     constants.IALLOCATOR_MODE_CHG_GROUP:
12419
      (_AddChangeGroup, [
12420
        ("instances", _STRING_LIST),
12421
        ("target_groups", _STRING_LIST),
12422
        ], _JOBSET_LIST),
12423
    }
12424

    
12425
  def Run(self, name, validate=True, call_fn=None):
12426
    """Run an instance allocator and return the results.
12427

12428
    """
12429
    if call_fn is None:
12430
      call_fn = self.rpc.call_iallocator_runner
12431

    
12432
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12433
    result.Raise("Failure while running the iallocator script")
12434

    
12435
    self.out_text = result.payload
12436
    if validate:
12437
      self._ValidateResult()
12438

    
12439
  def _ValidateResult(self):
12440
    """Process the allocator results.
12441

12442
    This will process and if successful save the result in
12443
    self.out_data and the other parameters.
12444

12445
    """
12446
    try:
12447
      rdict = serializer.Load(self.out_text)
12448
    except Exception, err:
12449
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12450

    
12451
    if not isinstance(rdict, dict):
12452
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12453

    
12454
    # TODO: remove backwards compatiblity in later versions
12455
    if "nodes" in rdict and "result" not in rdict:
12456
      rdict["result"] = rdict["nodes"]
12457
      del rdict["nodes"]
12458

    
12459
    for key in "success", "info", "result":
12460
      if key not in rdict:
12461
        raise errors.OpExecError("Can't parse iallocator results:"
12462
                                 " missing key '%s'" % key)
12463
      setattr(self, key, rdict[key])
12464

    
12465
    if not self._result_check(self.result):
12466
      raise errors.OpExecError("Iallocator returned invalid result,"
12467
                               " expected %s, got %s" %
12468
                               (self._result_check, self.result),
12469
                               errors.ECODE_INVAL)
12470

    
12471
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12472
                     constants.IALLOCATOR_MODE_MEVAC):
12473
      node2group = dict((name, ndata["group"])
12474
                        for (name, ndata) in self.in_data["nodes"].items())
12475

    
12476
      fn = compat.partial(self._NodesToGroups, node2group,
12477
                          self.in_data["nodegroups"])
12478

    
12479
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12480
        assert self.relocate_from is not None
12481
        assert self.required_nodes == 1
12482

    
12483
        request_groups = fn(self.relocate_from)
12484
        result_groups = fn(rdict["result"])
12485

    
12486
        if result_groups != request_groups:
12487
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12488
                                   " differ from original groups (%s)" %
12489
                                   (utils.CommaJoin(result_groups),
12490
                                    utils.CommaJoin(request_groups)))
12491
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12492
        request_groups = fn(self.evac_nodes)
12493
        for (instance_name, secnode) in self.result:
12494
          result_groups = fn([secnode])
12495
          if result_groups != request_groups:
12496
            raise errors.OpExecError("Iallocator returned new secondary node"
12497
                                     " '%s' (group '%s') for instance '%s'"
12498
                                     " which is not in original group '%s'" %
12499
                                     (secnode, utils.CommaJoin(result_groups),
12500
                                      instance_name,
12501
                                      utils.CommaJoin(request_groups)))
12502
      else:
12503
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12504

    
12505
    self.out_data = rdict
12506

    
12507
  @staticmethod
12508
  def _NodesToGroups(node2group, groups, nodes):
12509
    """Returns a list of unique group names for a list of nodes.
12510

12511
    @type node2group: dict
12512
    @param node2group: Map from node name to group UUID
12513
    @type groups: dict
12514
    @param groups: Group information
12515
    @type nodes: list
12516
    @param nodes: Node names
12517

12518
    """
12519
    result = set()
12520

    
12521
    for node in nodes:
12522
      try:
12523
        group_uuid = node2group[node]
12524
      except KeyError:
12525
        # Ignore unknown node
12526
        pass
12527
      else:
12528
        try:
12529
          group = groups[group_uuid]
12530
        except KeyError:
12531
          # Can't find group, let's use UUID
12532
          group_name = group_uuid
12533
        else:
12534
          group_name = group["name"]
12535

    
12536
        result.add(group_name)
12537

    
12538
    return sorted(result)
12539

    
12540

    
12541
class LUTestAllocator(NoHooksLU):
12542
  """Run allocator tests.
12543

12544
  This LU runs the allocator tests
12545

12546
  """
12547
  def CheckPrereq(self):
12548
    """Check prerequisites.
12549

12550
    This checks the opcode parameters depending on the director and mode test.
12551

12552
    """
12553
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12554
      for attr in ["memory", "disks", "disk_template",
12555
                   "os", "tags", "nics", "vcpus"]:
12556
        if not hasattr(self.op, attr):
12557
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12558
                                     attr, errors.ECODE_INVAL)
12559
      iname = self.cfg.ExpandInstanceName(self.op.name)
12560
      if iname is not None:
12561
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12562
                                   iname, errors.ECODE_EXISTS)
12563
      if not isinstance(self.op.nics, list):
12564
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12565
                                   errors.ECODE_INVAL)
12566
      if not isinstance(self.op.disks, list):
12567
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12568
                                   errors.ECODE_INVAL)
12569
      for row in self.op.disks:
12570
        if (not isinstance(row, dict) or
12571
            constants.IDISK_SIZE not in row or
12572
            not isinstance(row[constants.IDISK_SIZE], int) or
12573
            constants.IDISK_MODE not in row or
12574
            row[constants.IDISK_MODE] not in constants.DISK_ACCESS_SET):
12575
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12576
                                     " parameter", errors.ECODE_INVAL)
12577
      if self.op.hypervisor is None:
12578
        self.op.hypervisor = self.cfg.GetHypervisorType()
12579
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12580
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12581
      self.op.name = fname
12582
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12583
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12584
      if not hasattr(self.op, "evac_nodes"):
12585
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12586
                                   " opcode input", errors.ECODE_INVAL)
12587
    elif self.op.mode in (constants.IALLOCATOR_MODE_CHG_GROUP,
12588
                          constants.IALLOCATOR_MODE_NODE_EVAC):
12589
      if not self.op.instances:
12590
        raise errors.OpPrereqError("Missing instances", errors.ECODE_INVAL)
12591
      self.op.instances = _GetWantedInstances(self, self.op.instances)
12592
    else:
12593
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12594
                                 self.op.mode, errors.ECODE_INVAL)
12595

    
12596
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12597
      if self.op.allocator is None:
12598
        raise errors.OpPrereqError("Missing allocator name",
12599
                                   errors.ECODE_INVAL)
12600
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12601
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12602
                                 self.op.direction, errors.ECODE_INVAL)
12603

    
12604
  def Exec(self, feedback_fn):
12605
    """Run the allocator test.
12606

12607
    """
12608
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12609
      ial = IAllocator(self.cfg, self.rpc,
12610
                       mode=self.op.mode,
12611
                       name=self.op.name,
12612
                       memory=self.op.memory,
12613
                       disks=self.op.disks,
12614
                       disk_template=self.op.disk_template,
12615
                       os=self.op.os,
12616
                       tags=self.op.tags,
12617
                       nics=self.op.nics,
12618
                       vcpus=self.op.vcpus,
12619
                       hypervisor=self.op.hypervisor,
12620
                       )
12621
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12622
      ial = IAllocator(self.cfg, self.rpc,
12623
                       mode=self.op.mode,
12624
                       name=self.op.name,
12625
                       relocate_from=list(self.relocate_from),
12626
                       )
12627
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12628
      ial = IAllocator(self.cfg, self.rpc,
12629
                       mode=self.op.mode,
12630
                       evac_nodes=self.op.evac_nodes)
12631
    elif self.op.mode == constants.IALLOCATOR_MODE_CHG_GROUP:
12632
      ial = IAllocator(self.cfg, self.rpc,
12633
                       mode=self.op.mode,
12634
                       instances=self.op.instances,
12635
                       target_groups=self.op.target_groups)
12636
    elif self.op.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
12637
      ial = IAllocator(self.cfg, self.rpc,
12638
                       mode=self.op.mode,
12639
                       instances=self.op.instances,
12640
                       evac_mode=self.op.evac_mode)
12641
    else:
12642
      raise errors.ProgrammerError("Uncatched mode %s in"
12643
                                   " LUTestAllocator.Exec", self.op.mode)
12644

    
12645
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
12646
      result = ial.in_text
12647
    else:
12648
      ial.Run(self.op.allocator, validate=False)
12649
      result = ial.out_text
12650
    return result
12651

    
12652

    
12653
#: Query type implementations
12654
_QUERY_IMPL = {
12655
  constants.QR_INSTANCE: _InstanceQuery,
12656
  constants.QR_NODE: _NodeQuery,
12657
  constants.QR_GROUP: _GroupQuery,
12658
  constants.QR_OS: _OsQuery,
12659
  }
12660

    
12661
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
12662

    
12663

    
12664
def _GetQueryImplementation(name):
12665
  """Returns the implemtnation for a query type.
12666

12667
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
12668

12669
  """
12670
  try:
12671
    return _QUERY_IMPL[name]
12672
  except KeyError:
12673
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
12674
                               errors.ECODE_INVAL)