Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 323f9095

History | View | Annotate | Download (450.3 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
                                            self.op.startup_paused)
5710
      msg = result.fail_msg
5711
      if msg:
5712
        _ShutdownInstanceDisks(self, instance)
5713
        raise errors.OpExecError("Could not start instance: %s" % msg)
5714

    
5715

    
5716
class LUInstanceReboot(LogicalUnit):
5717
  """Reboot an instance.
5718

5719
  """
5720
  HPATH = "instance-reboot"
5721
  HTYPE = constants.HTYPE_INSTANCE
5722
  REQ_BGL = False
5723

    
5724
  def ExpandNames(self):
5725
    self._ExpandAndLockInstance()
5726

    
5727
  def BuildHooksEnv(self):
5728
    """Build hooks env.
5729

5730
    This runs on master, primary and secondary nodes of the instance.
5731

5732
    """
5733
    env = {
5734
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5735
      "REBOOT_TYPE": self.op.reboot_type,
5736
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5737
      }
5738

    
5739
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5740

    
5741
    return env
5742

    
5743
  def BuildHooksNodes(self):
5744
    """Build hooks nodes.
5745

5746
    """
5747
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5748
    return (nl, nl)
5749

    
5750
  def CheckPrereq(self):
5751
    """Check prerequisites.
5752

5753
    This checks that the instance is in the cluster.
5754

5755
    """
5756
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5757
    assert self.instance is not None, \
5758
      "Cannot retrieve locked instance %s" % self.op.instance_name
5759

    
5760
    _CheckNodeOnline(self, instance.primary_node)
5761

    
5762
    # check bridges existence
5763
    _CheckInstanceBridgesExist(self, instance)
5764

    
5765
  def Exec(self, feedback_fn):
5766
    """Reboot the instance.
5767

5768
    """
5769
    instance = self.instance
5770
    ignore_secondaries = self.op.ignore_secondaries
5771
    reboot_type = self.op.reboot_type
5772

    
5773
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5774
                                              instance.name,
5775
                                              instance.hypervisor)
5776
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5777
    instance_running = bool(remote_info.payload)
5778

    
5779
    node_current = instance.primary_node
5780

    
5781
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5782
                                            constants.INSTANCE_REBOOT_HARD]:
5783
      for disk in instance.disks:
5784
        self.cfg.SetDiskID(disk, node_current)
5785
      result = self.rpc.call_instance_reboot(node_current, instance,
5786
                                             reboot_type,
5787
                                             self.op.shutdown_timeout)
5788
      result.Raise("Could not reboot instance")
5789
    else:
5790
      if instance_running:
5791
        result = self.rpc.call_instance_shutdown(node_current, instance,
5792
                                                 self.op.shutdown_timeout)
5793
        result.Raise("Could not shutdown instance for full reboot")
5794
        _ShutdownInstanceDisks(self, instance)
5795
      else:
5796
        self.LogInfo("Instance %s was already stopped, starting now",
5797
                     instance.name)
5798
      _StartInstanceDisks(self, instance, ignore_secondaries)
5799
      result = self.rpc.call_instance_start(node_current, instance,
5800
                                            None, None, False)
5801
      msg = result.fail_msg
5802
      if msg:
5803
        _ShutdownInstanceDisks(self, instance)
5804
        raise errors.OpExecError("Could not start instance for"
5805
                                 " full reboot: %s" % msg)
5806

    
5807
    self.cfg.MarkInstanceUp(instance.name)
5808

    
5809

    
5810
class LUInstanceShutdown(LogicalUnit):
5811
  """Shutdown an instance.
5812

5813
  """
5814
  HPATH = "instance-stop"
5815
  HTYPE = constants.HTYPE_INSTANCE
5816
  REQ_BGL = False
5817

    
5818
  def ExpandNames(self):
5819
    self._ExpandAndLockInstance()
5820

    
5821
  def BuildHooksEnv(self):
5822
    """Build hooks env.
5823

5824
    This runs on master, primary and secondary nodes of the instance.
5825

5826
    """
5827
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5828
    env["TIMEOUT"] = self.op.timeout
5829
    return env
5830

    
5831
  def BuildHooksNodes(self):
5832
    """Build hooks nodes.
5833

5834
    """
5835
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5836
    return (nl, nl)
5837

    
5838
  def CheckPrereq(self):
5839
    """Check prerequisites.
5840

5841
    This checks that the instance is in the cluster.
5842

5843
    """
5844
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5845
    assert self.instance is not None, \
5846
      "Cannot retrieve locked instance %s" % self.op.instance_name
5847

    
5848
    self.primary_offline = \
5849
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5850

    
5851
    if self.primary_offline and self.op.ignore_offline_nodes:
5852
      self.proc.LogWarning("Ignoring offline primary node")
5853
    else:
5854
      _CheckNodeOnline(self, self.instance.primary_node)
5855

    
5856
  def Exec(self, feedback_fn):
5857
    """Shutdown the instance.
5858

5859
    """
5860
    instance = self.instance
5861
    node_current = instance.primary_node
5862
    timeout = self.op.timeout
5863

    
5864
    if not self.op.no_remember:
5865
      self.cfg.MarkInstanceDown(instance.name)
5866

    
5867
    if self.primary_offline:
5868
      assert self.op.ignore_offline_nodes
5869
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5870
    else:
5871
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5872
      msg = result.fail_msg
5873
      if msg:
5874
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5875

    
5876
      _ShutdownInstanceDisks(self, instance)
5877

    
5878

    
5879
class LUInstanceReinstall(LogicalUnit):
5880
  """Reinstall an instance.
5881

5882
  """
5883
  HPATH = "instance-reinstall"
5884
  HTYPE = constants.HTYPE_INSTANCE
5885
  REQ_BGL = False
5886

    
5887
  def ExpandNames(self):
5888
    self._ExpandAndLockInstance()
5889

    
5890
  def BuildHooksEnv(self):
5891
    """Build hooks env.
5892

5893
    This runs on master, primary and secondary nodes of the instance.
5894

5895
    """
5896
    return _BuildInstanceHookEnvByObject(self, self.instance)
5897

    
5898
  def BuildHooksNodes(self):
5899
    """Build hooks nodes.
5900

5901
    """
5902
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5903
    return (nl, nl)
5904

    
5905
  def CheckPrereq(self):
5906
    """Check prerequisites.
5907

5908
    This checks that the instance is in the cluster and is not running.
5909

5910
    """
5911
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5912
    assert instance is not None, \
5913
      "Cannot retrieve locked instance %s" % self.op.instance_name
5914
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5915
                     " offline, cannot reinstall")
5916
    for node in instance.secondary_nodes:
5917
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5918
                       " cannot reinstall")
5919

    
5920
    if instance.disk_template == constants.DT_DISKLESS:
5921
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5922
                                 self.op.instance_name,
5923
                                 errors.ECODE_INVAL)
5924
    _CheckInstanceDown(self, instance, "cannot reinstall")
5925

    
5926
    if self.op.os_type is not None:
5927
      # OS verification
5928
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5929
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5930
      instance_os = self.op.os_type
5931
    else:
5932
      instance_os = instance.os
5933

    
5934
    nodelist = list(instance.all_nodes)
5935

    
5936
    if self.op.osparams:
5937
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5938
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5939
      self.os_inst = i_osdict # the new dict (without defaults)
5940
    else:
5941
      self.os_inst = None
5942

    
5943
    self.instance = instance
5944

    
5945
  def Exec(self, feedback_fn):
5946
    """Reinstall the instance.
5947

5948
    """
5949
    inst = self.instance
5950

    
5951
    if self.op.os_type is not None:
5952
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5953
      inst.os = self.op.os_type
5954
      # Write to configuration
5955
      self.cfg.Update(inst, feedback_fn)
5956

    
5957
    _StartInstanceDisks(self, inst, None)
5958
    try:
5959
      feedback_fn("Running the instance OS create scripts...")
5960
      # FIXME: pass debug option from opcode to backend
5961
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5962
                                             self.op.debug_level,
5963
                                             osparams=self.os_inst)
5964
      result.Raise("Could not install OS for instance %s on node %s" %
5965
                   (inst.name, inst.primary_node))
5966
    finally:
5967
      _ShutdownInstanceDisks(self, inst)
5968

    
5969

    
5970
class LUInstanceRecreateDisks(LogicalUnit):
5971
  """Recreate an instance's missing disks.
5972

5973
  """
5974
  HPATH = "instance-recreate-disks"
5975
  HTYPE = constants.HTYPE_INSTANCE
5976
  REQ_BGL = False
5977

    
5978
  def CheckArguments(self):
5979
    # normalise the disk list
5980
    self.op.disks = sorted(frozenset(self.op.disks))
5981

    
5982
  def ExpandNames(self):
5983
    self._ExpandAndLockInstance()
5984
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5985
    if self.op.nodes:
5986
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5987
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5988
    else:
5989
      self.needed_locks[locking.LEVEL_NODE] = []
5990

    
5991
  def DeclareLocks(self, level):
5992
    if level == locking.LEVEL_NODE:
5993
      # if we replace the nodes, we only need to lock the old primary,
5994
      # otherwise we need to lock all nodes for disk re-creation
5995
      primary_only = bool(self.op.nodes)
5996
      self._LockInstancesNodes(primary_only=primary_only)
5997

    
5998
  def BuildHooksEnv(self):
5999
    """Build hooks env.
6000

6001
    This runs on master, primary and secondary nodes of the instance.
6002

6003
    """
6004
    return _BuildInstanceHookEnvByObject(self, self.instance)
6005

    
6006
  def BuildHooksNodes(self):
6007
    """Build hooks nodes.
6008

6009
    """
6010
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6011
    return (nl, nl)
6012

    
6013
  def CheckPrereq(self):
6014
    """Check prerequisites.
6015

6016
    This checks that the instance is in the cluster and is not running.
6017

6018
    """
6019
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6020
    assert instance is not None, \
6021
      "Cannot retrieve locked instance %s" % self.op.instance_name
6022
    if self.op.nodes:
6023
      if len(self.op.nodes) != len(instance.all_nodes):
6024
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6025
                                   " %d replacement nodes were specified" %
6026
                                   (instance.name, len(instance.all_nodes),
6027
                                    len(self.op.nodes)),
6028
                                   errors.ECODE_INVAL)
6029
      assert instance.disk_template != constants.DT_DRBD8 or \
6030
          len(self.op.nodes) == 2
6031
      assert instance.disk_template != constants.DT_PLAIN or \
6032
          len(self.op.nodes) == 1
6033
      primary_node = self.op.nodes[0]
6034
    else:
6035
      primary_node = instance.primary_node
6036
    _CheckNodeOnline(self, primary_node)
6037

    
6038
    if instance.disk_template == constants.DT_DISKLESS:
6039
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6040
                                 self.op.instance_name, errors.ECODE_INVAL)
6041
    # if we replace nodes *and* the old primary is offline, we don't
6042
    # check
6043
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
6044
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6045
    if not (self.op.nodes and old_pnode.offline):
6046
      _CheckInstanceDown(self, instance, "cannot recreate disks")
6047

    
6048
    if not self.op.disks:
6049
      self.op.disks = range(len(instance.disks))
6050
    else:
6051
      for idx in self.op.disks:
6052
        if idx >= len(instance.disks):
6053
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6054
                                     errors.ECODE_INVAL)
6055
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6056
      raise errors.OpPrereqError("Can't recreate disks partially and"
6057
                                 " change the nodes at the same time",
6058
                                 errors.ECODE_INVAL)
6059
    self.instance = instance
6060

    
6061
  def Exec(self, feedback_fn):
6062
    """Recreate the disks.
6063

6064
    """
6065
    # change primary node, if needed
6066
    if self.op.nodes:
6067
      self.instance.primary_node = self.op.nodes[0]
6068
      self.LogWarning("Changing the instance's nodes, you will have to"
6069
                      " remove any disks left on the older nodes manually")
6070

    
6071
    to_skip = []
6072
    for idx, disk in enumerate(self.instance.disks):
6073
      if idx not in self.op.disks: # disk idx has not been passed in
6074
        to_skip.append(idx)
6075
        continue
6076
      # update secondaries for disks, if needed
6077
      if self.op.nodes:
6078
        if disk.dev_type == constants.LD_DRBD8:
6079
          # need to update the nodes
6080
          assert len(self.op.nodes) == 2
6081
          logical_id = list(disk.logical_id)
6082
          logical_id[0] = self.op.nodes[0]
6083
          logical_id[1] = self.op.nodes[1]
6084
          disk.logical_id = tuple(logical_id)
6085

    
6086
    if self.op.nodes:
6087
      self.cfg.Update(self.instance, feedback_fn)
6088

    
6089
    _CreateDisks(self, self.instance, to_skip=to_skip)
6090

    
6091

    
6092
class LUInstanceRename(LogicalUnit):
6093
  """Rename an instance.
6094

6095
  """
6096
  HPATH = "instance-rename"
6097
  HTYPE = constants.HTYPE_INSTANCE
6098

    
6099
  def CheckArguments(self):
6100
    """Check arguments.
6101

6102
    """
6103
    if self.op.ip_check and not self.op.name_check:
6104
      # TODO: make the ip check more flexible and not depend on the name check
6105
      raise errors.OpPrereqError("IP address check requires a name check",
6106
                                 errors.ECODE_INVAL)
6107

    
6108
  def BuildHooksEnv(self):
6109
    """Build hooks env.
6110

6111
    This runs on master, primary and secondary nodes of the instance.
6112

6113
    """
6114
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6115
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6116
    return env
6117

    
6118
  def BuildHooksNodes(self):
6119
    """Build hooks nodes.
6120

6121
    """
6122
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6123
    return (nl, nl)
6124

    
6125
  def CheckPrereq(self):
6126
    """Check prerequisites.
6127

6128
    This checks that the instance is in the cluster and is not running.
6129

6130
    """
6131
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6132
                                                self.op.instance_name)
6133
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6134
    assert instance is not None
6135
    _CheckNodeOnline(self, instance.primary_node)
6136
    _CheckInstanceDown(self, instance, "cannot rename")
6137
    self.instance = instance
6138

    
6139
    new_name = self.op.new_name
6140
    if self.op.name_check:
6141
      hostname = netutils.GetHostname(name=new_name)
6142
      if hostname != new_name:
6143
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6144
                     hostname.name)
6145
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6146
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6147
                                    " same as given hostname '%s'") %
6148
                                    (hostname.name, self.op.new_name),
6149
                                    errors.ECODE_INVAL)
6150
      new_name = self.op.new_name = hostname.name
6151
      if (self.op.ip_check and
6152
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6153
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6154
                                   (hostname.ip, new_name),
6155
                                   errors.ECODE_NOTUNIQUE)
6156

    
6157
    instance_list = self.cfg.GetInstanceList()
6158
    if new_name in instance_list and new_name != instance.name:
6159
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6160
                                 new_name, errors.ECODE_EXISTS)
6161

    
6162
  def Exec(self, feedback_fn):
6163
    """Rename the instance.
6164

6165
    """
6166
    inst = self.instance
6167
    old_name = inst.name
6168

    
6169
    rename_file_storage = False
6170
    if (inst.disk_template in constants.DTS_FILEBASED and
6171
        self.op.new_name != inst.name):
6172
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6173
      rename_file_storage = True
6174

    
6175
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6176
    # Change the instance lock. This is definitely safe while we hold the BGL.
6177
    # Otherwise the new lock would have to be added in acquired mode.
6178
    assert self.REQ_BGL
6179
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6180
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6181

    
6182
    # re-read the instance from the configuration after rename
6183
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6184

    
6185
    if rename_file_storage:
6186
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6187
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6188
                                                     old_file_storage_dir,
6189
                                                     new_file_storage_dir)
6190
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6191
                   " (but the instance has been renamed in Ganeti)" %
6192
                   (inst.primary_node, old_file_storage_dir,
6193
                    new_file_storage_dir))
6194

    
6195
    _StartInstanceDisks(self, inst, None)
6196
    try:
6197
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6198
                                                 old_name, self.op.debug_level)
6199
      msg = result.fail_msg
6200
      if msg:
6201
        msg = ("Could not run OS rename script for instance %s on node %s"
6202
               " (but the instance has been renamed in Ganeti): %s" %
6203
               (inst.name, inst.primary_node, msg))
6204
        self.proc.LogWarning(msg)
6205
    finally:
6206
      _ShutdownInstanceDisks(self, inst)
6207

    
6208
    return inst.name
6209

    
6210

    
6211
class LUInstanceRemove(LogicalUnit):
6212
  """Remove an instance.
6213

6214
  """
6215
  HPATH = "instance-remove"
6216
  HTYPE = constants.HTYPE_INSTANCE
6217
  REQ_BGL = False
6218

    
6219
  def ExpandNames(self):
6220
    self._ExpandAndLockInstance()
6221
    self.needed_locks[locking.LEVEL_NODE] = []
6222
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6223

    
6224
  def DeclareLocks(self, level):
6225
    if level == locking.LEVEL_NODE:
6226
      self._LockInstancesNodes()
6227

    
6228
  def BuildHooksEnv(self):
6229
    """Build hooks env.
6230

6231
    This runs on master, primary and secondary nodes of the instance.
6232

6233
    """
6234
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6235
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6236
    return env
6237

    
6238
  def BuildHooksNodes(self):
6239
    """Build hooks nodes.
6240

6241
    """
6242
    nl = [self.cfg.GetMasterNode()]
6243
    nl_post = list(self.instance.all_nodes) + nl
6244
    return (nl, nl_post)
6245

    
6246
  def CheckPrereq(self):
6247
    """Check prerequisites.
6248

6249
    This checks that the instance is in the cluster.
6250

6251
    """
6252
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6253
    assert self.instance is not None, \
6254
      "Cannot retrieve locked instance %s" % self.op.instance_name
6255

    
6256
  def Exec(self, feedback_fn):
6257
    """Remove the instance.
6258

6259
    """
6260
    instance = self.instance
6261
    logging.info("Shutting down instance %s on node %s",
6262
                 instance.name, instance.primary_node)
6263

    
6264
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6265
                                             self.op.shutdown_timeout)
6266
    msg = result.fail_msg
6267
    if msg:
6268
      if self.op.ignore_failures:
6269
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6270
      else:
6271
        raise errors.OpExecError("Could not shutdown instance %s on"
6272
                                 " node %s: %s" %
6273
                                 (instance.name, instance.primary_node, msg))
6274

    
6275
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6276

    
6277

    
6278
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6279
  """Utility function to remove an instance.
6280

6281
  """
6282
  logging.info("Removing block devices for instance %s", instance.name)
6283

    
6284
  if not _RemoveDisks(lu, instance):
6285
    if not ignore_failures:
6286
      raise errors.OpExecError("Can't remove instance's disks")
6287
    feedback_fn("Warning: can't remove instance's disks")
6288

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

    
6291
  lu.cfg.RemoveInstance(instance.name)
6292

    
6293
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6294
    "Instance lock removal conflict"
6295

    
6296
  # Remove lock for the instance
6297
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6298

    
6299

    
6300
class LUInstanceQuery(NoHooksLU):
6301
  """Logical unit for querying instances.
6302

6303
  """
6304
  # pylint: disable-msg=W0142
6305
  REQ_BGL = False
6306

    
6307
  def CheckArguments(self):
6308
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6309
                             self.op.output_fields, self.op.use_locking)
6310

    
6311
  def ExpandNames(self):
6312
    self.iq.ExpandNames(self)
6313

    
6314
  def DeclareLocks(self, level):
6315
    self.iq.DeclareLocks(self, level)
6316

    
6317
  def Exec(self, feedback_fn):
6318
    return self.iq.OldStyleQuery(self)
6319

    
6320

    
6321
class LUInstanceFailover(LogicalUnit):
6322
  """Failover an instance.
6323

6324
  """
6325
  HPATH = "instance-failover"
6326
  HTYPE = constants.HTYPE_INSTANCE
6327
  REQ_BGL = False
6328

    
6329
  def CheckArguments(self):
6330
    """Check the arguments.
6331

6332
    """
6333
    self.iallocator = getattr(self.op, "iallocator", None)
6334
    self.target_node = getattr(self.op, "target_node", None)
6335

    
6336
  def ExpandNames(self):
6337
    self._ExpandAndLockInstance()
6338

    
6339
    if self.op.target_node is not None:
6340
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6341

    
6342
    self.needed_locks[locking.LEVEL_NODE] = []
6343
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6344

    
6345
    ignore_consistency = self.op.ignore_consistency
6346
    shutdown_timeout = self.op.shutdown_timeout
6347
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6348
                                       cleanup=False,
6349
                                       failover=True,
6350
                                       ignore_consistency=ignore_consistency,
6351
                                       shutdown_timeout=shutdown_timeout)
6352
    self.tasklets = [self._migrater]
6353

    
6354
  def DeclareLocks(self, level):
6355
    if level == locking.LEVEL_NODE:
6356
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6357
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6358
        if self.op.target_node is None:
6359
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6360
        else:
6361
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6362
                                                   self.op.target_node]
6363
        del self.recalculate_locks[locking.LEVEL_NODE]
6364
      else:
6365
        self._LockInstancesNodes()
6366

    
6367
  def BuildHooksEnv(self):
6368
    """Build hooks env.
6369

6370
    This runs on master, primary and secondary nodes of the instance.
6371

6372
    """
6373
    instance = self._migrater.instance
6374
    source_node = instance.primary_node
6375
    target_node = self.op.target_node
6376
    env = {
6377
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6378
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6379
      "OLD_PRIMARY": source_node,
6380
      "NEW_PRIMARY": target_node,
6381
      }
6382

    
6383
    if instance.disk_template in constants.DTS_INT_MIRROR:
6384
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6385
      env["NEW_SECONDARY"] = source_node
6386
    else:
6387
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6388

    
6389
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6390

    
6391
    return env
6392

    
6393
  def BuildHooksNodes(self):
6394
    """Build hooks nodes.
6395

6396
    """
6397
    instance = self._migrater.instance
6398
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6399
    return (nl, nl + [instance.primary_node])
6400

    
6401

    
6402
class LUInstanceMigrate(LogicalUnit):
6403
  """Migrate an instance.
6404

6405
  This is migration without shutting down, compared to the failover,
6406
  which is done with shutdown.
6407

6408
  """
6409
  HPATH = "instance-migrate"
6410
  HTYPE = constants.HTYPE_INSTANCE
6411
  REQ_BGL = False
6412

    
6413
  def ExpandNames(self):
6414
    self._ExpandAndLockInstance()
6415

    
6416
    if self.op.target_node is not None:
6417
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6418

    
6419
    self.needed_locks[locking.LEVEL_NODE] = []
6420
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6421

    
6422
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6423
                                       cleanup=self.op.cleanup,
6424
                                       failover=False,
6425
                                       fallback=self.op.allow_failover)
6426
    self.tasklets = [self._migrater]
6427

    
6428
  def DeclareLocks(self, level):
6429
    if level == locking.LEVEL_NODE:
6430
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6431
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6432
        if self.op.target_node is None:
6433
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6434
        else:
6435
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6436
                                                   self.op.target_node]
6437
        del self.recalculate_locks[locking.LEVEL_NODE]
6438
      else:
6439
        self._LockInstancesNodes()
6440

    
6441
  def BuildHooksEnv(self):
6442
    """Build hooks env.
6443

6444
    This runs on master, primary and secondary nodes of the instance.
6445

6446
    """
6447
    instance = self._migrater.instance
6448
    source_node = instance.primary_node
6449
    target_node = self.op.target_node
6450
    env = _BuildInstanceHookEnvByObject(self, instance)
6451
    env.update({
6452
      "MIGRATE_LIVE": self._migrater.live,
6453
      "MIGRATE_CLEANUP": self.op.cleanup,
6454
      "OLD_PRIMARY": source_node,
6455
      "NEW_PRIMARY": target_node,
6456
      })
6457

    
6458
    if instance.disk_template in constants.DTS_INT_MIRROR:
6459
      env["OLD_SECONDARY"] = target_node
6460
      env["NEW_SECONDARY"] = source_node
6461
    else:
6462
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6463

    
6464
    return env
6465

    
6466
  def BuildHooksNodes(self):
6467
    """Build hooks nodes.
6468

6469
    """
6470
    instance = self._migrater.instance
6471
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6472
    return (nl, nl + [instance.primary_node])
6473

    
6474

    
6475
class LUInstanceMove(LogicalUnit):
6476
  """Move an instance by data-copying.
6477

6478
  """
6479
  HPATH = "instance-move"
6480
  HTYPE = constants.HTYPE_INSTANCE
6481
  REQ_BGL = False
6482

    
6483
  def ExpandNames(self):
6484
    self._ExpandAndLockInstance()
6485
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6486
    self.op.target_node = target_node
6487
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6488
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6489

    
6490
  def DeclareLocks(self, level):
6491
    if level == locking.LEVEL_NODE:
6492
      self._LockInstancesNodes(primary_only=True)
6493

    
6494
  def BuildHooksEnv(self):
6495
    """Build hooks env.
6496

6497
    This runs on master, primary and secondary nodes of the instance.
6498

6499
    """
6500
    env = {
6501
      "TARGET_NODE": self.op.target_node,
6502
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6503
      }
6504
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6505
    return env
6506

    
6507
  def BuildHooksNodes(self):
6508
    """Build hooks nodes.
6509

6510
    """
6511
    nl = [
6512
      self.cfg.GetMasterNode(),
6513
      self.instance.primary_node,
6514
      self.op.target_node,
6515
      ]
6516
    return (nl, nl)
6517

    
6518
  def CheckPrereq(self):
6519
    """Check prerequisites.
6520

6521
    This checks that the instance is in the cluster.
6522

6523
    """
6524
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6525
    assert self.instance is not None, \
6526
      "Cannot retrieve locked instance %s" % self.op.instance_name
6527

    
6528
    node = self.cfg.GetNodeInfo(self.op.target_node)
6529
    assert node is not None, \
6530
      "Cannot retrieve locked node %s" % self.op.target_node
6531

    
6532
    self.target_node = target_node = node.name
6533

    
6534
    if target_node == instance.primary_node:
6535
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6536
                                 (instance.name, target_node),
6537
                                 errors.ECODE_STATE)
6538

    
6539
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6540

    
6541
    for idx, dsk in enumerate(instance.disks):
6542
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6543
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6544
                                   " cannot copy" % idx, errors.ECODE_STATE)
6545

    
6546
    _CheckNodeOnline(self, target_node)
6547
    _CheckNodeNotDrained(self, target_node)
6548
    _CheckNodeVmCapable(self, target_node)
6549

    
6550
    if instance.admin_up:
6551
      # check memory requirements on the secondary node
6552
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6553
                           instance.name, bep[constants.BE_MEMORY],
6554
                           instance.hypervisor)
6555
    else:
6556
      self.LogInfo("Not checking memory on the secondary node as"
6557
                   " instance will not be started")
6558

    
6559
    # check bridge existance
6560
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6561

    
6562
  def Exec(self, feedback_fn):
6563
    """Move an instance.
6564

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

6568
    """
6569
    instance = self.instance
6570

    
6571
    source_node = instance.primary_node
6572
    target_node = self.target_node
6573

    
6574
    self.LogInfo("Shutting down instance %s on source node %s",
6575
                 instance.name, source_node)
6576

    
6577
    result = self.rpc.call_instance_shutdown(source_node, instance,
6578
                                             self.op.shutdown_timeout)
6579
    msg = result.fail_msg
6580
    if msg:
6581
      if self.op.ignore_consistency:
6582
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6583
                             " Proceeding anyway. Please make sure node"
6584
                             " %s is down. Error details: %s",
6585
                             instance.name, source_node, source_node, msg)
6586
      else:
6587
        raise errors.OpExecError("Could not shutdown instance %s on"
6588
                                 " node %s: %s" %
6589
                                 (instance.name, source_node, msg))
6590

    
6591
    # create the target disks
6592
    try:
6593
      _CreateDisks(self, instance, target_node=target_node)
6594
    except errors.OpExecError:
6595
      self.LogWarning("Device creation failed, reverting...")
6596
      try:
6597
        _RemoveDisks(self, instance, target_node=target_node)
6598
      finally:
6599
        self.cfg.ReleaseDRBDMinors(instance.name)
6600
        raise
6601

    
6602
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6603

    
6604
    errs = []
6605
    # activate, get path, copy the data over
6606
    for idx, disk in enumerate(instance.disks):
6607
      self.LogInfo("Copying data for disk %d", idx)
6608
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6609
                                               instance.name, True, idx)
6610
      if result.fail_msg:
6611
        self.LogWarning("Can't assemble newly created disk %d: %s",
6612
                        idx, result.fail_msg)
6613
        errs.append(result.fail_msg)
6614
        break
6615
      dev_path = result.payload
6616
      result = self.rpc.call_blockdev_export(source_node, disk,
6617
                                             target_node, dev_path,
6618
                                             cluster_name)
6619
      if result.fail_msg:
6620
        self.LogWarning("Can't copy data over for disk %d: %s",
6621
                        idx, result.fail_msg)
6622
        errs.append(result.fail_msg)
6623
        break
6624

    
6625
    if errs:
6626
      self.LogWarning("Some disks failed to copy, aborting")
6627
      try:
6628
        _RemoveDisks(self, instance, target_node=target_node)
6629
      finally:
6630
        self.cfg.ReleaseDRBDMinors(instance.name)
6631
        raise errors.OpExecError("Errors during disk copy: %s" %
6632
                                 (",".join(errs),))
6633

    
6634
    instance.primary_node = target_node
6635
    self.cfg.Update(instance, feedback_fn)
6636

    
6637
    self.LogInfo("Removing the disks on the original node")
6638
    _RemoveDisks(self, instance, target_node=source_node)
6639

    
6640
    # Only start the instance if it's marked as up
6641
    if instance.admin_up:
6642
      self.LogInfo("Starting instance %s on node %s",
6643
                   instance.name, target_node)
6644

    
6645
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6646
                                           ignore_secondaries=True)
6647
      if not disks_ok:
6648
        _ShutdownInstanceDisks(self, instance)
6649
        raise errors.OpExecError("Can't activate the instance's disks")
6650

    
6651
      result = self.rpc.call_instance_start(target_node, instance,
6652
                                            None, None, False)
6653
      msg = result.fail_msg
6654
      if msg:
6655
        _ShutdownInstanceDisks(self, instance)
6656
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6657
                                 (instance.name, target_node, msg))
6658

    
6659

    
6660
class LUNodeMigrate(LogicalUnit):
6661
  """Migrate all instances from a node.
6662

6663
  """
6664
  HPATH = "node-migrate"
6665
  HTYPE = constants.HTYPE_NODE
6666
  REQ_BGL = False
6667

    
6668
  def CheckArguments(self):
6669
    pass
6670

    
6671
  def ExpandNames(self):
6672
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6673

    
6674
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
6675
    self.needed_locks = {
6676
      locking.LEVEL_NODE: [self.op.node_name],
6677
      }
6678

    
6679
  def BuildHooksEnv(self):
6680
    """Build hooks env.
6681

6682
    This runs on the master, the primary and all the secondaries.
6683

6684
    """
6685
    return {
6686
      "NODE_NAME": self.op.node_name,
6687
      }
6688

    
6689
  def BuildHooksNodes(self):
6690
    """Build hooks nodes.
6691

6692
    """
6693
    nl = [self.cfg.GetMasterNode()]
6694
    return (nl, nl)
6695

    
6696
  def CheckPrereq(self):
6697
    pass
6698

    
6699
  def Exec(self, feedback_fn):
6700
    # Prepare jobs for migration instances
6701
    jobs = [
6702
      [opcodes.OpInstanceMigrate(instance_name=inst.name,
6703
                                 mode=self.op.mode,
6704
                                 live=self.op.live,
6705
                                 iallocator=self.op.iallocator,
6706
                                 target_node=self.op.target_node)]
6707
      for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name)
6708
      ]
6709

    
6710
    # TODO: Run iallocator in this opcode and pass correct placement options to
6711
    # OpInstanceMigrate. Since other jobs can modify the cluster between
6712
    # running the iallocator and the actual migration, a good consistency model
6713
    # will have to be found.
6714

    
6715
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
6716
            frozenset([self.op.node_name]))
6717

    
6718
    return ResultWithJobs(jobs)
6719

    
6720

    
6721
class TLMigrateInstance(Tasklet):
6722
  """Tasklet class for instance migration.
6723

6724
  @type live: boolean
6725
  @ivar live: whether the migration will be done live or non-live;
6726
      this variable is initalized only after CheckPrereq has run
6727
  @type cleanup: boolean
6728
  @ivar cleanup: Wheater we cleanup from a failed migration
6729
  @type iallocator: string
6730
  @ivar iallocator: The iallocator used to determine target_node
6731
  @type target_node: string
6732
  @ivar target_node: If given, the target_node to reallocate the instance to
6733
  @type failover: boolean
6734
  @ivar failover: Whether operation results in failover or migration
6735
  @type fallback: boolean
6736
  @ivar fallback: Whether fallback to failover is allowed if migration not
6737
                  possible
6738
  @type ignore_consistency: boolean
6739
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6740
                            and target node
6741
  @type shutdown_timeout: int
6742
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6743

6744
  """
6745
  def __init__(self, lu, instance_name, cleanup=False,
6746
               failover=False, fallback=False,
6747
               ignore_consistency=False,
6748
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6749
    """Initializes this class.
6750

6751
    """
6752
    Tasklet.__init__(self, lu)
6753

    
6754
    # Parameters
6755
    self.instance_name = instance_name
6756
    self.cleanup = cleanup
6757
    self.live = False # will be overridden later
6758
    self.failover = failover
6759
    self.fallback = fallback
6760
    self.ignore_consistency = ignore_consistency
6761
    self.shutdown_timeout = shutdown_timeout
6762

    
6763
  def CheckPrereq(self):
6764
    """Check prerequisites.
6765

6766
    This checks that the instance is in the cluster.
6767

6768
    """
6769
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6770
    instance = self.cfg.GetInstanceInfo(instance_name)
6771
    assert instance is not None
6772
    self.instance = instance
6773

    
6774
    if (not self.cleanup and not instance.admin_up and not self.failover and
6775
        self.fallback):
6776
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6777
                      " to failover")
6778
      self.failover = True
6779

    
6780
    if instance.disk_template not in constants.DTS_MIRRORED:
6781
      if self.failover:
6782
        text = "failovers"
6783
      else:
6784
        text = "migrations"
6785
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6786
                                 " %s" % (instance.disk_template, text),
6787
                                 errors.ECODE_STATE)
6788

    
6789
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6790
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6791

    
6792
      if self.lu.op.iallocator:
6793
        self._RunAllocator()
6794
      else:
6795
        # We set set self.target_node as it is required by
6796
        # BuildHooksEnv
6797
        self.target_node = self.lu.op.target_node
6798

    
6799
      # self.target_node is already populated, either directly or by the
6800
      # iallocator run
6801
      target_node = self.target_node
6802
      if self.target_node == instance.primary_node:
6803
        raise errors.OpPrereqError("Cannot migrate instance %s"
6804
                                   " to its primary (%s)" %
6805
                                   (instance.name, instance.primary_node))
6806

    
6807
      if len(self.lu.tasklets) == 1:
6808
        # It is safe to release locks only when we're the only tasklet
6809
        # in the LU
6810
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6811
                      keep=[instance.primary_node, self.target_node])
6812

    
6813
    else:
6814
      secondary_nodes = instance.secondary_nodes
6815
      if not secondary_nodes:
6816
        raise errors.ConfigurationError("No secondary node but using"
6817
                                        " %s disk template" %
6818
                                        instance.disk_template)
6819
      target_node = secondary_nodes[0]
6820
      if self.lu.op.iallocator or (self.lu.op.target_node and
6821
                                   self.lu.op.target_node != target_node):
6822
        if self.failover:
6823
          text = "failed over"
6824
        else:
6825
          text = "migrated"
6826
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6827
                                   " be %s to arbitrary nodes"
6828
                                   " (neither an iallocator nor a target"
6829
                                   " node can be passed)" %
6830
                                   (instance.disk_template, text),
6831
                                   errors.ECODE_INVAL)
6832

    
6833
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6834

    
6835
    # check memory requirements on the secondary node
6836
    if not self.failover or instance.admin_up:
6837
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6838
                           instance.name, i_be[constants.BE_MEMORY],
6839
                           instance.hypervisor)
6840
    else:
6841
      self.lu.LogInfo("Not checking memory on the secondary node as"
6842
                      " instance will not be started")
6843

    
6844
    # check bridge existance
6845
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6846

    
6847
    if not self.cleanup:
6848
      _CheckNodeNotDrained(self.lu, target_node)
6849
      if not self.failover:
6850
        result = self.rpc.call_instance_migratable(instance.primary_node,
6851
                                                   instance)
6852
        if result.fail_msg and self.fallback:
6853
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6854
                          " failover")
6855
          self.failover = True
6856
        else:
6857
          result.Raise("Can't migrate, please use failover",
6858
                       prereq=True, ecode=errors.ECODE_STATE)
6859

    
6860
    assert not (self.failover and self.cleanup)
6861

    
6862
    if not self.failover:
6863
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6864
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6865
                                   " parameters are accepted",
6866
                                   errors.ECODE_INVAL)
6867
      if self.lu.op.live is not None:
6868
        if self.lu.op.live:
6869
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6870
        else:
6871
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6872
        # reset the 'live' parameter to None so that repeated
6873
        # invocations of CheckPrereq do not raise an exception
6874
        self.lu.op.live = None
6875
      elif self.lu.op.mode is None:
6876
        # read the default value from the hypervisor
6877
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6878
                                                skip_globals=False)
6879
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6880

    
6881
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6882
    else:
6883
      # Failover is never live
6884
      self.live = False
6885

    
6886
  def _RunAllocator(self):
6887
    """Run the allocator based on input opcode.
6888

6889
    """
6890
    ial = IAllocator(self.cfg, self.rpc,
6891
                     mode=constants.IALLOCATOR_MODE_RELOC,
6892
                     name=self.instance_name,
6893
                     # TODO See why hail breaks with a single node below
6894
                     relocate_from=[self.instance.primary_node,
6895
                                    self.instance.primary_node],
6896
                     )
6897

    
6898
    ial.Run(self.lu.op.iallocator)
6899

    
6900
    if not ial.success:
6901
      raise errors.OpPrereqError("Can't compute nodes using"
6902
                                 " iallocator '%s': %s" %
6903
                                 (self.lu.op.iallocator, ial.info),
6904
                                 errors.ECODE_NORES)
6905
    if len(ial.result) != ial.required_nodes:
6906
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6907
                                 " of nodes (%s), required %s" %
6908
                                 (self.lu.op.iallocator, len(ial.result),
6909
                                  ial.required_nodes), errors.ECODE_FAULT)
6910
    self.target_node = ial.result[0]
6911
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6912
                 self.instance_name, self.lu.op.iallocator,
6913
                 utils.CommaJoin(ial.result))
6914

    
6915
  def _WaitUntilSync(self):
6916
    """Poll with custom rpc for disk sync.
6917

6918
    This uses our own step-based rpc call.
6919

6920
    """
6921
    self.feedback_fn("* wait until resync is done")
6922
    all_done = False
6923
    while not all_done:
6924
      all_done = True
6925
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6926
                                            self.nodes_ip,
6927
                                            self.instance.disks)
6928
      min_percent = 100
6929
      for node, nres in result.items():
6930
        nres.Raise("Cannot resync disks on node %s" % node)
6931
        node_done, node_percent = nres.payload
6932
        all_done = all_done and node_done
6933
        if node_percent is not None:
6934
          min_percent = min(min_percent, node_percent)
6935
      if not all_done:
6936
        if min_percent < 100:
6937
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6938
        time.sleep(2)
6939

    
6940
  def _EnsureSecondary(self, node):
6941
    """Demote a node to secondary.
6942

6943
    """
6944
    self.feedback_fn("* switching node %s to secondary mode" % node)
6945

    
6946
    for dev in self.instance.disks:
6947
      self.cfg.SetDiskID(dev, node)
6948

    
6949
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6950
                                          self.instance.disks)
6951
    result.Raise("Cannot change disk to secondary on node %s" % node)
6952

    
6953
  def _GoStandalone(self):
6954
    """Disconnect from the network.
6955

6956
    """
6957
    self.feedback_fn("* changing into standalone mode")
6958
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6959
                                               self.instance.disks)
6960
    for node, nres in result.items():
6961
      nres.Raise("Cannot disconnect disks node %s" % node)
6962

    
6963
  def _GoReconnect(self, multimaster):
6964
    """Reconnect to the network.
6965

6966
    """
6967
    if multimaster:
6968
      msg = "dual-master"
6969
    else:
6970
      msg = "single-master"
6971
    self.feedback_fn("* changing disks into %s mode" % msg)
6972
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6973
                                           self.instance.disks,
6974
                                           self.instance.name, multimaster)
6975
    for node, nres in result.items():
6976
      nres.Raise("Cannot change disks config on node %s" % node)
6977

    
6978
  def _ExecCleanup(self):
6979
    """Try to cleanup after a failed migration.
6980

6981
    The cleanup is done by:
6982
      - check that the instance is running only on one node
6983
        (and update the config if needed)
6984
      - change disks on its secondary node to secondary
6985
      - wait until disks are fully synchronized
6986
      - disconnect from the network
6987
      - change disks into single-master mode
6988
      - wait again until disks are fully synchronized
6989

6990
    """
6991
    instance = self.instance
6992
    target_node = self.target_node
6993
    source_node = self.source_node
6994

    
6995
    # check running on only one node
6996
    self.feedback_fn("* checking where the instance actually runs"
6997
                     " (if this hangs, the hypervisor might be in"
6998
                     " a bad state)")
6999
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
7000
    for node, result in ins_l.items():
7001
      result.Raise("Can't contact node %s" % node)
7002

    
7003
    runningon_source = instance.name in ins_l[source_node].payload
7004
    runningon_target = instance.name in ins_l[target_node].payload
7005

    
7006
    if runningon_source and runningon_target:
7007
      raise errors.OpExecError("Instance seems to be running on two nodes,"
7008
                               " or the hypervisor is confused; you will have"
7009
                               " to ensure manually that it runs only on one"
7010
                               " and restart this operation")
7011

    
7012
    if not (runningon_source or runningon_target):
7013
      raise errors.OpExecError("Instance does not seem to be running at all;"
7014
                               " in this case it's safer to repair by"
7015
                               " running 'gnt-instance stop' to ensure disk"
7016
                               " shutdown, and then restarting it")
7017

    
7018
    if runningon_target:
7019
      # the migration has actually succeeded, we need to update the config
7020
      self.feedback_fn("* instance running on secondary node (%s),"
7021
                       " updating config" % target_node)
7022
      instance.primary_node = target_node
7023
      self.cfg.Update(instance, self.feedback_fn)
7024
      demoted_node = source_node
7025
    else:
7026
      self.feedback_fn("* instance confirmed to be running on its"
7027
                       " primary node (%s)" % source_node)
7028
      demoted_node = target_node
7029

    
7030
    if instance.disk_template in constants.DTS_INT_MIRROR:
7031
      self._EnsureSecondary(demoted_node)
7032
      try:
7033
        self._WaitUntilSync()
7034
      except errors.OpExecError:
7035
        # we ignore here errors, since if the device is standalone, it
7036
        # won't be able to sync
7037
        pass
7038
      self._GoStandalone()
7039
      self._GoReconnect(False)
7040
      self._WaitUntilSync()
7041

    
7042
    self.feedback_fn("* done")
7043

    
7044
  def _RevertDiskStatus(self):
7045
    """Try to revert the disk status after a failed migration.
7046

7047
    """
7048
    target_node = self.target_node
7049
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7050
      return
7051

    
7052
    try:
7053
      self._EnsureSecondary(target_node)
7054
      self._GoStandalone()
7055
      self._GoReconnect(False)
7056
      self._WaitUntilSync()
7057
    except errors.OpExecError, err:
7058
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7059
                         " please try to recover the instance manually;"
7060
                         " error '%s'" % str(err))
7061

    
7062
  def _AbortMigration(self):
7063
    """Call the hypervisor code to abort a started migration.
7064

7065
    """
7066
    instance = self.instance
7067
    target_node = self.target_node
7068
    migration_info = self.migration_info
7069

    
7070
    abort_result = self.rpc.call_finalize_migration(target_node,
7071
                                                    instance,
7072
                                                    migration_info,
7073
                                                    False)
7074
    abort_msg = abort_result.fail_msg
7075
    if abort_msg:
7076
      logging.error("Aborting migration failed on target node %s: %s",
7077
                    target_node, abort_msg)
7078
      # Don't raise an exception here, as we stil have to try to revert the
7079
      # disk status, even if this step failed.
7080

    
7081
  def _ExecMigration(self):
7082
    """Migrate an instance.
7083

7084
    The migrate is done by:
7085
      - change the disks into dual-master mode
7086
      - wait until disks are fully synchronized again
7087
      - migrate the instance
7088
      - change disks on the new secondary node (the old primary) to secondary
7089
      - wait until disks are fully synchronized
7090
      - change disks into single-master mode
7091

7092
    """
7093
    instance = self.instance
7094
    target_node = self.target_node
7095
    source_node = self.source_node
7096

    
7097
    self.feedback_fn("* checking disk consistency between source and target")
7098
    for dev in instance.disks:
7099
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7100
        raise errors.OpExecError("Disk %s is degraded or not fully"
7101
                                 " synchronized on target node,"
7102
                                 " aborting migration" % dev.iv_name)
7103

    
7104
    # First get the migration information from the remote node
7105
    result = self.rpc.call_migration_info(source_node, instance)
7106
    msg = result.fail_msg
7107
    if msg:
7108
      log_err = ("Failed fetching source migration information from %s: %s" %
7109
                 (source_node, msg))
7110
      logging.error(log_err)
7111
      raise errors.OpExecError(log_err)
7112

    
7113
    self.migration_info = migration_info = result.payload
7114

    
7115
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7116
      # Then switch the disks to master/master mode
7117
      self._EnsureSecondary(target_node)
7118
      self._GoStandalone()
7119
      self._GoReconnect(True)
7120
      self._WaitUntilSync()
7121

    
7122
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7123
    result = self.rpc.call_accept_instance(target_node,
7124
                                           instance,
7125
                                           migration_info,
7126
                                           self.nodes_ip[target_node])
7127

    
7128
    msg = result.fail_msg
7129
    if msg:
7130
      logging.error("Instance pre-migration failed, trying to revert"
7131
                    " disk status: %s", msg)
7132
      self.feedback_fn("Pre-migration failed, aborting")
7133
      self._AbortMigration()
7134
      self._RevertDiskStatus()
7135
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7136
                               (instance.name, msg))
7137

    
7138
    self.feedback_fn("* migrating instance to %s" % target_node)
7139
    result = self.rpc.call_instance_migrate(source_node, instance,
7140
                                            self.nodes_ip[target_node],
7141
                                            self.live)
7142
    msg = result.fail_msg
7143
    if msg:
7144
      logging.error("Instance migration failed, trying to revert"
7145
                    " disk status: %s", msg)
7146
      self.feedback_fn("Migration failed, aborting")
7147
      self._AbortMigration()
7148
      self._RevertDiskStatus()
7149
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7150
                               (instance.name, msg))
7151

    
7152
    instance.primary_node = target_node
7153
    # distribute new instance config to the other nodes
7154
    self.cfg.Update(instance, self.feedback_fn)
7155

    
7156
    result = self.rpc.call_finalize_migration(target_node,
7157
                                              instance,
7158
                                              migration_info,
7159
                                              True)
7160
    msg = result.fail_msg
7161
    if msg:
7162
      logging.error("Instance migration succeeded, but finalization failed:"
7163
                    " %s", msg)
7164
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7165
                               msg)
7166

    
7167
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7168
      self._EnsureSecondary(source_node)
7169
      self._WaitUntilSync()
7170
      self._GoStandalone()
7171
      self._GoReconnect(False)
7172
      self._WaitUntilSync()
7173

    
7174
    self.feedback_fn("* done")
7175

    
7176
  def _ExecFailover(self):
7177
    """Failover an instance.
7178

7179
    The failover is done by shutting it down on its present node and
7180
    starting it on the secondary.
7181

7182
    """
7183
    instance = self.instance
7184
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7185

    
7186
    source_node = instance.primary_node
7187
    target_node = self.target_node
7188

    
7189
    if instance.admin_up:
7190
      self.feedback_fn("* checking disk consistency between source and target")
7191
      for dev in instance.disks:
7192
        # for drbd, these are drbd over lvm
7193
        if not _CheckDiskConsistency(self, dev, target_node, False):
7194
          if not self.ignore_consistency:
7195
            raise errors.OpExecError("Disk %s is degraded on target node,"
7196
                                     " aborting failover" % dev.iv_name)
7197
    else:
7198
      self.feedback_fn("* not checking disk consistency as instance is not"
7199
                       " running")
7200

    
7201
    self.feedback_fn("* shutting down instance on source node")
7202
    logging.info("Shutting down instance %s on node %s",
7203
                 instance.name, source_node)
7204

    
7205
    result = self.rpc.call_instance_shutdown(source_node, instance,
7206
                                             self.shutdown_timeout)
7207
    msg = result.fail_msg
7208
    if msg:
7209
      if self.ignore_consistency or primary_node.offline:
7210
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7211
                           " proceeding anyway; please make sure node"
7212
                           " %s is down; error details: %s",
7213
                           instance.name, source_node, source_node, msg)
7214
      else:
7215
        raise errors.OpExecError("Could not shutdown instance %s on"
7216
                                 " node %s: %s" %
7217
                                 (instance.name, source_node, msg))
7218

    
7219
    self.feedback_fn("* deactivating the instance's disks on source node")
7220
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
7221
      raise errors.OpExecError("Can't shut down the instance's disks.")
7222

    
7223
    instance.primary_node = target_node
7224
    # distribute new instance config to the other nodes
7225
    self.cfg.Update(instance, self.feedback_fn)
7226

    
7227
    # Only start the instance if it's marked as up
7228
    if instance.admin_up:
7229
      self.feedback_fn("* activating the instance's disks on target node")
7230
      logging.info("Starting instance %s on node %s",
7231
                   instance.name, target_node)
7232

    
7233
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7234
                                           ignore_secondaries=True)
7235
      if not disks_ok:
7236
        _ShutdownInstanceDisks(self, instance)
7237
        raise errors.OpExecError("Can't activate the instance's disks")
7238

    
7239
      self.feedback_fn("* starting the instance on the target node")
7240
      result = self.rpc.call_instance_start(target_node, instance, None, None)
7241
      msg = result.fail_msg
7242
      if msg:
7243
        _ShutdownInstanceDisks(self, instance)
7244
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7245
                                 (instance.name, target_node, msg))
7246

    
7247
  def Exec(self, feedback_fn):
7248
    """Perform the migration.
7249

7250
    """
7251
    self.feedback_fn = feedback_fn
7252
    self.source_node = self.instance.primary_node
7253

    
7254
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7255
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7256
      self.target_node = self.instance.secondary_nodes[0]
7257
      # Otherwise self.target_node has been populated either
7258
      # directly, or through an iallocator.
7259

    
7260
    self.all_nodes = [self.source_node, self.target_node]
7261
    self.nodes_ip = {
7262
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7263
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7264
      }
7265

    
7266
    if self.failover:
7267
      feedback_fn("Failover instance %s" % self.instance.name)
7268
      self._ExecFailover()
7269
    else:
7270
      feedback_fn("Migrating instance %s" % self.instance.name)
7271

    
7272
      if self.cleanup:
7273
        return self._ExecCleanup()
7274
      else:
7275
        return self._ExecMigration()
7276

    
7277

    
7278
def _CreateBlockDev(lu, node, instance, device, force_create,
7279
                    info, force_open):
7280
  """Create a tree of block devices on a given node.
7281

7282
  If this device type has to be created on secondaries, create it and
7283
  all its children.
7284

7285
  If not, just recurse to children keeping the same 'force' value.
7286

7287
  @param lu: the lu on whose behalf we execute
7288
  @param node: the node on which to create the device
7289
  @type instance: L{objects.Instance}
7290
  @param instance: the instance which owns the device
7291
  @type device: L{objects.Disk}
7292
  @param device: the device to create
7293
  @type force_create: boolean
7294
  @param force_create: whether to force creation of this device; this
7295
      will be change to True whenever we find a device which has
7296
      CreateOnSecondary() attribute
7297
  @param info: the extra 'metadata' we should attach to the device
7298
      (this will be represented as a LVM tag)
7299
  @type force_open: boolean
7300
  @param force_open: this parameter will be passes to the
7301
      L{backend.BlockdevCreate} function where it specifies
7302
      whether we run on primary or not, and it affects both
7303
      the child assembly and the device own Open() execution
7304

7305
  """
7306
  if device.CreateOnSecondary():
7307
    force_create = True
7308

    
7309
  if device.children:
7310
    for child in device.children:
7311
      _CreateBlockDev(lu, node, instance, child, force_create,
7312
                      info, force_open)
7313

    
7314
  if not force_create:
7315
    return
7316

    
7317
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7318

    
7319

    
7320
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7321
  """Create a single block device on a given node.
7322

7323
  This will not recurse over children of the device, so they must be
7324
  created in advance.
7325

7326
  @param lu: the lu on whose behalf we execute
7327
  @param node: the node on which to create the device
7328
  @type instance: L{objects.Instance}
7329
  @param instance: the instance which owns the device
7330
  @type device: L{objects.Disk}
7331
  @param device: the device to create
7332
  @param info: the extra 'metadata' we should attach to the device
7333
      (this will be represented as a LVM tag)
7334
  @type force_open: boolean
7335
  @param force_open: this parameter will be passes to the
7336
      L{backend.BlockdevCreate} function where it specifies
7337
      whether we run on primary or not, and it affects both
7338
      the child assembly and the device own Open() execution
7339

7340
  """
7341
  lu.cfg.SetDiskID(device, node)
7342
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7343
                                       instance.name, force_open, info)
7344
  result.Raise("Can't create block device %s on"
7345
               " node %s for instance %s" % (device, node, instance.name))
7346
  if device.physical_id is None:
7347
    device.physical_id = result.payload
7348

    
7349

    
7350
def _GenerateUniqueNames(lu, exts):
7351
  """Generate a suitable LV name.
7352

7353
  This will generate a logical volume name for the given instance.
7354

7355
  """
7356
  results = []
7357
  for val in exts:
7358
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7359
    results.append("%s%s" % (new_id, val))
7360
  return results
7361

    
7362

    
7363
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7364
                         iv_name, p_minor, s_minor):
7365
  """Generate a drbd8 device complete with its children.
7366

7367
  """
7368
  assert len(vgnames) == len(names) == 2
7369
  port = lu.cfg.AllocatePort()
7370
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7371
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7372
                          logical_id=(vgnames[0], names[0]))
7373
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7374
                          logical_id=(vgnames[1], names[1]))
7375
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7376
                          logical_id=(primary, secondary, port,
7377
                                      p_minor, s_minor,
7378
                                      shared_secret),
7379
                          children=[dev_data, dev_meta],
7380
                          iv_name=iv_name)
7381
  return drbd_dev
7382

    
7383

    
7384
def _GenerateDiskTemplate(lu, template_name,
7385
                          instance_name, primary_node,
7386
                          secondary_nodes, disk_info,
7387
                          file_storage_dir, file_driver,
7388
                          base_index, feedback_fn):
7389
  """Generate the entire disk layout for a given template type.
7390

7391
  """
7392
  #TODO: compute space requirements
7393

    
7394
  vgname = lu.cfg.GetVGName()
7395
  disk_count = len(disk_info)
7396
  disks = []
7397
  if template_name == constants.DT_DISKLESS:
7398
    pass
7399
  elif template_name == constants.DT_PLAIN:
7400
    if len(secondary_nodes) != 0:
7401
      raise errors.ProgrammerError("Wrong template configuration")
7402

    
7403
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7404
                                      for i in range(disk_count)])
7405
    for idx, disk in enumerate(disk_info):
7406
      disk_index = idx + base_index
7407
      vg = disk.get(constants.IDISK_VG, vgname)
7408
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7409
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7410
                              size=disk[constants.IDISK_SIZE],
7411
                              logical_id=(vg, names[idx]),
7412
                              iv_name="disk/%d" % disk_index,
7413
                              mode=disk[constants.IDISK_MODE])
7414
      disks.append(disk_dev)
7415
  elif template_name == constants.DT_DRBD8:
7416
    if len(secondary_nodes) != 1:
7417
      raise errors.ProgrammerError("Wrong template configuration")
7418
    remote_node = secondary_nodes[0]
7419
    minors = lu.cfg.AllocateDRBDMinor(
7420
      [primary_node, remote_node] * len(disk_info), instance_name)
7421

    
7422
    names = []
7423
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7424
                                               for i in range(disk_count)]):
7425
      names.append(lv_prefix + "_data")
7426
      names.append(lv_prefix + "_meta")
7427
    for idx, disk in enumerate(disk_info):
7428
      disk_index = idx + base_index
7429
      data_vg = disk.get(constants.IDISK_VG, vgname)
7430
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7431
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7432
                                      disk[constants.IDISK_SIZE],
7433
                                      [data_vg, meta_vg],
7434
                                      names[idx * 2:idx * 2 + 2],
7435
                                      "disk/%d" % disk_index,
7436
                                      minors[idx * 2], minors[idx * 2 + 1])
7437
      disk_dev.mode = disk[constants.IDISK_MODE]
7438
      disks.append(disk_dev)
7439
  elif template_name == constants.DT_FILE:
7440
    if len(secondary_nodes) != 0:
7441
      raise errors.ProgrammerError("Wrong template configuration")
7442

    
7443
    opcodes.RequireFileStorage()
7444

    
7445
    for idx, disk in enumerate(disk_info):
7446
      disk_index = idx + base_index
7447
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7448
                              size=disk[constants.IDISK_SIZE],
7449
                              iv_name="disk/%d" % disk_index,
7450
                              logical_id=(file_driver,
7451
                                          "%s/disk%d" % (file_storage_dir,
7452
                                                         disk_index)),
7453
                              mode=disk[constants.IDISK_MODE])
7454
      disks.append(disk_dev)
7455
  elif template_name == constants.DT_SHARED_FILE:
7456
    if len(secondary_nodes) != 0:
7457
      raise errors.ProgrammerError("Wrong template configuration")
7458

    
7459
    opcodes.RequireSharedFileStorage()
7460

    
7461
    for idx, disk in enumerate(disk_info):
7462
      disk_index = idx + base_index
7463
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7464
                              size=disk[constants.IDISK_SIZE],
7465
                              iv_name="disk/%d" % disk_index,
7466
                              logical_id=(file_driver,
7467
                                          "%s/disk%d" % (file_storage_dir,
7468
                                                         disk_index)),
7469
                              mode=disk[constants.IDISK_MODE])
7470
      disks.append(disk_dev)
7471
  elif template_name == constants.DT_BLOCK:
7472
    if len(secondary_nodes) != 0:
7473
      raise errors.ProgrammerError("Wrong template configuration")
7474

    
7475
    for idx, disk in enumerate(disk_info):
7476
      disk_index = idx + base_index
7477
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7478
                              size=disk[constants.IDISK_SIZE],
7479
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7480
                                          disk[constants.IDISK_ADOPT]),
7481
                              iv_name="disk/%d" % disk_index,
7482
                              mode=disk[constants.IDISK_MODE])
7483
      disks.append(disk_dev)
7484

    
7485
  else:
7486
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7487
  return disks
7488

    
7489

    
7490
def _GetInstanceInfoText(instance):
7491
  """Compute that text that should be added to the disk's metadata.
7492

7493
  """
7494
  return "originstname+%s" % instance.name
7495

    
7496

    
7497
def _CalcEta(time_taken, written, total_size):
7498
  """Calculates the ETA based on size written and total size.
7499

7500
  @param time_taken: The time taken so far
7501
  @param written: amount written so far
7502
  @param total_size: The total size of data to be written
7503
  @return: The remaining time in seconds
7504

7505
  """
7506
  avg_time = time_taken / float(written)
7507
  return (total_size - written) * avg_time
7508

    
7509

    
7510
def _WipeDisks(lu, instance):
7511
  """Wipes instance disks.
7512

7513
  @type lu: L{LogicalUnit}
7514
  @param lu: the logical unit on whose behalf we execute
7515
  @type instance: L{objects.Instance}
7516
  @param instance: the instance whose disks we should create
7517
  @return: the success of the wipe
7518

7519
  """
7520
  node = instance.primary_node
7521

    
7522
  for device in instance.disks:
7523
    lu.cfg.SetDiskID(device, node)
7524

    
7525
  logging.info("Pause sync of instance %s disks", instance.name)
7526
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7527

    
7528
  for idx, success in enumerate(result.payload):
7529
    if not success:
7530
      logging.warn("pause-sync of instance %s for disks %d failed",
7531
                   instance.name, idx)
7532

    
7533
  try:
7534
    for idx, device in enumerate(instance.disks):
7535
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7536
      # MAX_WIPE_CHUNK at max
7537
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7538
                            constants.MIN_WIPE_CHUNK_PERCENT)
7539
      # we _must_ make this an int, otherwise rounding errors will
7540
      # occur
7541
      wipe_chunk_size = int(wipe_chunk_size)
7542

    
7543
      lu.LogInfo("* Wiping disk %d", idx)
7544
      logging.info("Wiping disk %d for instance %s, node %s using"
7545
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7546

    
7547
      offset = 0
7548
      size = device.size
7549
      last_output = 0
7550
      start_time = time.time()
7551

    
7552
      while offset < size:
7553
        wipe_size = min(wipe_chunk_size, size - offset)
7554
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7555
                      idx, offset, wipe_size)
7556
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7557
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7558
                     (idx, offset, wipe_size))
7559
        now = time.time()
7560
        offset += wipe_size
7561
        if now - last_output >= 60:
7562
          eta = _CalcEta(now - start_time, offset, size)
7563
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7564
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7565
          last_output = now
7566
  finally:
7567
    logging.info("Resume sync of instance %s disks", instance.name)
7568

    
7569
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7570

    
7571
    for idx, success in enumerate(result.payload):
7572
      if not success:
7573
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7574
                      " look at the status and troubleshoot the issue", idx)
7575
        logging.warn("resume-sync of instance %s for disks %d failed",
7576
                     instance.name, idx)
7577

    
7578

    
7579
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7580
  """Create all disks for an instance.
7581

7582
  This abstracts away some work from AddInstance.
7583

7584
  @type lu: L{LogicalUnit}
7585
  @param lu: the logical unit on whose behalf we execute
7586
  @type instance: L{objects.Instance}
7587
  @param instance: the instance whose disks we should create
7588
  @type to_skip: list
7589
  @param to_skip: list of indices to skip
7590
  @type target_node: string
7591
  @param target_node: if passed, overrides the target node for creation
7592
  @rtype: boolean
7593
  @return: the success of the creation
7594

7595
  """
7596
  info = _GetInstanceInfoText(instance)
7597
  if target_node is None:
7598
    pnode = instance.primary_node
7599
    all_nodes = instance.all_nodes
7600
  else:
7601
    pnode = target_node
7602
    all_nodes = [pnode]
7603

    
7604
  if instance.disk_template in constants.DTS_FILEBASED:
7605
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7606
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7607

    
7608
    result.Raise("Failed to create directory '%s' on"
7609
                 " node %s" % (file_storage_dir, pnode))
7610

    
7611
  # Note: this needs to be kept in sync with adding of disks in
7612
  # LUInstanceSetParams
7613
  for idx, device in enumerate(instance.disks):
7614
    if to_skip and idx in to_skip:
7615
      continue
7616
    logging.info("Creating volume %s for instance %s",
7617
                 device.iv_name, instance.name)
7618
    #HARDCODE
7619
    for node in all_nodes:
7620
      f_create = node == pnode
7621
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7622

    
7623

    
7624
def _RemoveDisks(lu, instance, target_node=None):
7625
  """Remove all disks for an instance.
7626

7627
  This abstracts away some work from `AddInstance()` and
7628
  `RemoveInstance()`. Note that in case some of the devices couldn't
7629
  be removed, the removal will continue with the other ones (compare
7630
  with `_CreateDisks()`).
7631

7632
  @type lu: L{LogicalUnit}
7633
  @param lu: the logical unit on whose behalf we execute
7634
  @type instance: L{objects.Instance}
7635
  @param instance: the instance whose disks we should remove
7636
  @type target_node: string
7637
  @param target_node: used to override the node on which to remove the disks
7638
  @rtype: boolean
7639
  @return: the success of the removal
7640

7641
  """
7642
  logging.info("Removing block devices for instance %s", instance.name)
7643

    
7644
  all_result = True
7645
  for device in instance.disks:
7646
    if target_node:
7647
      edata = [(target_node, device)]
7648
    else:
7649
      edata = device.ComputeNodeTree(instance.primary_node)
7650
    for node, disk in edata:
7651
      lu.cfg.SetDiskID(disk, node)
7652
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7653
      if msg:
7654
        lu.LogWarning("Could not remove block device %s on node %s,"
7655
                      " continuing anyway: %s", device.iv_name, node, msg)
7656
        all_result = False
7657

    
7658
  if instance.disk_template == constants.DT_FILE:
7659
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7660
    if target_node:
7661
      tgt = target_node
7662
    else:
7663
      tgt = instance.primary_node
7664
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7665
    if result.fail_msg:
7666
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7667
                    file_storage_dir, instance.primary_node, result.fail_msg)
7668
      all_result = False
7669

    
7670
  return all_result
7671

    
7672

    
7673
def _ComputeDiskSizePerVG(disk_template, disks):
7674
  """Compute disk size requirements in the volume group
7675

7676
  """
7677
  def _compute(disks, payload):
7678
    """Universal algorithm.
7679

7680
    """
7681
    vgs = {}
7682
    for disk in disks:
7683
      vgs[disk[constants.IDISK_VG]] = \
7684
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7685

    
7686
    return vgs
7687

    
7688
  # Required free disk space as a function of disk and swap space
7689
  req_size_dict = {
7690
    constants.DT_DISKLESS: {},
7691
    constants.DT_PLAIN: _compute(disks, 0),
7692
    # 128 MB are added for drbd metadata for each disk
7693
    constants.DT_DRBD8: _compute(disks, 128),
7694
    constants.DT_FILE: {},
7695
    constants.DT_SHARED_FILE: {},
7696
  }
7697

    
7698
  if disk_template not in req_size_dict:
7699
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7700
                                 " is unknown" %  disk_template)
7701

    
7702
  return req_size_dict[disk_template]
7703

    
7704

    
7705
def _ComputeDiskSize(disk_template, disks):
7706
  """Compute disk size requirements in the volume group
7707

7708
  """
7709
  # Required free disk space as a function of disk and swap space
7710
  req_size_dict = {
7711
    constants.DT_DISKLESS: None,
7712
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7713
    # 128 MB are added for drbd metadata for each disk
7714
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7715
    constants.DT_FILE: None,
7716
    constants.DT_SHARED_FILE: 0,
7717
    constants.DT_BLOCK: 0,
7718
  }
7719

    
7720
  if disk_template not in req_size_dict:
7721
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7722
                                 " is unknown" %  disk_template)
7723

    
7724
  return req_size_dict[disk_template]
7725

    
7726

    
7727
def _FilterVmNodes(lu, nodenames):
7728
  """Filters out non-vm_capable nodes from a list.
7729

7730
  @type lu: L{LogicalUnit}
7731
  @param lu: the logical unit for which we check
7732
  @type nodenames: list
7733
  @param nodenames: the list of nodes on which we should check
7734
  @rtype: list
7735
  @return: the list of vm-capable nodes
7736

7737
  """
7738
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7739
  return [name for name in nodenames if name not in vm_nodes]
7740

    
7741

    
7742
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7743
  """Hypervisor parameter validation.
7744

7745
  This function abstract the hypervisor parameter validation to be
7746
  used in both instance create and instance modify.
7747

7748
  @type lu: L{LogicalUnit}
7749
  @param lu: the logical unit for which we check
7750
  @type nodenames: list
7751
  @param nodenames: the list of nodes on which we should check
7752
  @type hvname: string
7753
  @param hvname: the name of the hypervisor we should use
7754
  @type hvparams: dict
7755
  @param hvparams: the parameters which we need to check
7756
  @raise errors.OpPrereqError: if the parameters are not valid
7757

7758
  """
7759
  nodenames = _FilterVmNodes(lu, nodenames)
7760
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7761
                                                  hvname,
7762
                                                  hvparams)
7763
  for node in nodenames:
7764
    info = hvinfo[node]
7765
    if info.offline:
7766
      continue
7767
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7768

    
7769

    
7770
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7771
  """OS parameters validation.
7772

7773
  @type lu: L{LogicalUnit}
7774
  @param lu: the logical unit for which we check
7775
  @type required: boolean
7776
  @param required: whether the validation should fail if the OS is not
7777
      found
7778
  @type nodenames: list
7779
  @param nodenames: the list of nodes on which we should check
7780
  @type osname: string
7781
  @param osname: the name of the hypervisor we should use
7782
  @type osparams: dict
7783
  @param osparams: the parameters which we need to check
7784
  @raise errors.OpPrereqError: if the parameters are not valid
7785

7786
  """
7787
  nodenames = _FilterVmNodes(lu, nodenames)
7788
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7789
                                   [constants.OS_VALIDATE_PARAMETERS],
7790
                                   osparams)
7791
  for node, nres in result.items():
7792
    # we don't check for offline cases since this should be run only
7793
    # against the master node and/or an instance's nodes
7794
    nres.Raise("OS Parameters validation failed on node %s" % node)
7795
    if not nres.payload:
7796
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7797
                 osname, node)
7798

    
7799

    
7800
class LUInstanceCreate(LogicalUnit):
7801
  """Create an instance.
7802

7803
  """
7804
  HPATH = "instance-add"
7805
  HTYPE = constants.HTYPE_INSTANCE
7806
  REQ_BGL = False
7807

    
7808
  def CheckArguments(self):
7809
    """Check arguments.
7810

7811
    """
7812
    # do not require name_check to ease forward/backward compatibility
7813
    # for tools
7814
    if self.op.no_install and self.op.start:
7815
      self.LogInfo("No-installation mode selected, disabling startup")
7816
      self.op.start = False
7817
    # validate/normalize the instance name
7818
    self.op.instance_name = \
7819
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7820

    
7821
    if self.op.ip_check and not self.op.name_check:
7822
      # TODO: make the ip check more flexible and not depend on the name check
7823
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7824
                                 " check", errors.ECODE_INVAL)
7825

    
7826
    # check nics' parameter names
7827
    for nic in self.op.nics:
7828
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7829

    
7830
    # check disks. parameter names and consistent adopt/no-adopt strategy
7831
    has_adopt = has_no_adopt = False
7832
    for disk in self.op.disks:
7833
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7834
      if constants.IDISK_ADOPT in disk:
7835
        has_adopt = True
7836
      else:
7837
        has_no_adopt = True
7838
    if has_adopt and has_no_adopt:
7839
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7840
                                 errors.ECODE_INVAL)
7841
    if has_adopt:
7842
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7843
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7844
                                   " '%s' disk template" %
7845
                                   self.op.disk_template,
7846
                                   errors.ECODE_INVAL)
7847
      if self.op.iallocator is not None:
7848
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7849
                                   " iallocator script", errors.ECODE_INVAL)
7850
      if self.op.mode == constants.INSTANCE_IMPORT:
7851
        raise errors.OpPrereqError("Disk adoption not allowed for"
7852
                                   " instance import", errors.ECODE_INVAL)
7853
    else:
7854
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7855
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7856
                                   " but no 'adopt' parameter given" %
7857
                                   self.op.disk_template,
7858
                                   errors.ECODE_INVAL)
7859

    
7860
    self.adopt_disks = has_adopt
7861

    
7862
    # instance name verification
7863
    if self.op.name_check:
7864
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7865
      self.op.instance_name = self.hostname1.name
7866
      # used in CheckPrereq for ip ping check
7867
      self.check_ip = self.hostname1.ip
7868
    else:
7869
      self.check_ip = None
7870

    
7871
    # file storage checks
7872
    if (self.op.file_driver and
7873
        not self.op.file_driver in constants.FILE_DRIVER):
7874
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7875
                                 self.op.file_driver, errors.ECODE_INVAL)
7876

    
7877
    if self.op.disk_template == constants.DT_FILE:
7878
      opcodes.RequireFileStorage()
7879
    elif self.op.disk_template == constants.DT_SHARED_FILE:
7880
      opcodes.RequireSharedFileStorage()
7881

    
7882
    ### Node/iallocator related checks
7883
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7884

    
7885
    if self.op.pnode is not None:
7886
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7887
        if self.op.snode is None:
7888
          raise errors.OpPrereqError("The networked disk templates need"
7889
                                     " a mirror node", errors.ECODE_INVAL)
7890
      elif self.op.snode:
7891
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7892
                        " template")
7893
        self.op.snode = None
7894

    
7895
    self._cds = _GetClusterDomainSecret()
7896

    
7897
    if self.op.mode == constants.INSTANCE_IMPORT:
7898
      # On import force_variant must be True, because if we forced it at
7899
      # initial install, our only chance when importing it back is that it
7900
      # works again!
7901
      self.op.force_variant = True
7902

    
7903
      if self.op.no_install:
7904
        self.LogInfo("No-installation mode has no effect during import")
7905

    
7906
    elif self.op.mode == constants.INSTANCE_CREATE:
7907
      if self.op.os_type is None:
7908
        raise errors.OpPrereqError("No guest OS specified",
7909
                                   errors.ECODE_INVAL)
7910
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7911
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7912
                                   " installation" % self.op.os_type,
7913
                                   errors.ECODE_STATE)
7914
      if self.op.disk_template is None:
7915
        raise errors.OpPrereqError("No disk template specified",
7916
                                   errors.ECODE_INVAL)
7917

    
7918
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7919
      # Check handshake to ensure both clusters have the same domain secret
7920
      src_handshake = self.op.source_handshake
7921
      if not src_handshake:
7922
        raise errors.OpPrereqError("Missing source handshake",
7923
                                   errors.ECODE_INVAL)
7924

    
7925
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7926
                                                           src_handshake)
7927
      if errmsg:
7928
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7929
                                   errors.ECODE_INVAL)
7930

    
7931
      # Load and check source CA
7932
      self.source_x509_ca_pem = self.op.source_x509_ca
7933
      if not self.source_x509_ca_pem:
7934
        raise errors.OpPrereqError("Missing source X509 CA",
7935
                                   errors.ECODE_INVAL)
7936

    
7937
      try:
7938
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7939
                                                    self._cds)
7940
      except OpenSSL.crypto.Error, err:
7941
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7942
                                   (err, ), errors.ECODE_INVAL)
7943

    
7944
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7945
      if errcode is not None:
7946
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7947
                                   errors.ECODE_INVAL)
7948

    
7949
      self.source_x509_ca = cert
7950

    
7951
      src_instance_name = self.op.source_instance_name
7952
      if not src_instance_name:
7953
        raise errors.OpPrereqError("Missing source instance name",
7954
                                   errors.ECODE_INVAL)
7955

    
7956
      self.source_instance_name = \
7957
          netutils.GetHostname(name=src_instance_name).name
7958

    
7959
    else:
7960
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7961
                                 self.op.mode, errors.ECODE_INVAL)
7962

    
7963
  def ExpandNames(self):
7964
    """ExpandNames for CreateInstance.
7965

7966
    Figure out the right locks for instance creation.
7967

7968
    """
7969
    self.needed_locks = {}
7970

    
7971
    instance_name = self.op.instance_name
7972
    # this is just a preventive check, but someone might still add this
7973
    # instance in the meantime, and creation will fail at lock-add time
7974
    if instance_name in self.cfg.GetInstanceList():
7975
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7976
                                 instance_name, errors.ECODE_EXISTS)
7977

    
7978
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7979

    
7980
    if self.op.iallocator:
7981
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7982
    else:
7983
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7984
      nodelist = [self.op.pnode]
7985
      if self.op.snode is not None:
7986
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7987
        nodelist.append(self.op.snode)
7988
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7989

    
7990
    # in case of import lock the source node too
7991
    if self.op.mode == constants.INSTANCE_IMPORT:
7992
      src_node = self.op.src_node
7993
      src_path = self.op.src_path
7994

    
7995
      if src_path is None:
7996
        self.op.src_path = src_path = self.op.instance_name
7997

    
7998
      if src_node is None:
7999
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8000
        self.op.src_node = None
8001
        if os.path.isabs(src_path):
8002
          raise errors.OpPrereqError("Importing an instance from an absolute"
8003
                                     " path requires a source node option",
8004
                                     errors.ECODE_INVAL)
8005
      else:
8006
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
8007
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
8008
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
8009
        if not os.path.isabs(src_path):
8010
          self.op.src_path = src_path = \
8011
            utils.PathJoin(constants.EXPORT_DIR, src_path)
8012

    
8013
  def _RunAllocator(self):
8014
    """Run the allocator based on input opcode.
8015

8016
    """
8017
    nics = [n.ToDict() for n in self.nics]
8018
    ial = IAllocator(self.cfg, self.rpc,
8019
                     mode=constants.IALLOCATOR_MODE_ALLOC,
8020
                     name=self.op.instance_name,
8021
                     disk_template=self.op.disk_template,
8022
                     tags=self.op.tags,
8023
                     os=self.op.os_type,
8024
                     vcpus=self.be_full[constants.BE_VCPUS],
8025
                     memory=self.be_full[constants.BE_MEMORY],
8026
                     disks=self.disks,
8027
                     nics=nics,
8028
                     hypervisor=self.op.hypervisor,
8029
                     )
8030

    
8031
    ial.Run(self.op.iallocator)
8032

    
8033
    if not ial.success:
8034
      raise errors.OpPrereqError("Can't compute nodes using"
8035
                                 " iallocator '%s': %s" %
8036
                                 (self.op.iallocator, ial.info),
8037
                                 errors.ECODE_NORES)
8038
    if len(ial.result) != ial.required_nodes:
8039
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8040
                                 " of nodes (%s), required %s" %
8041
                                 (self.op.iallocator, len(ial.result),
8042
                                  ial.required_nodes), errors.ECODE_FAULT)
8043
    self.op.pnode = ial.result[0]
8044
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8045
                 self.op.instance_name, self.op.iallocator,
8046
                 utils.CommaJoin(ial.result))
8047
    if ial.required_nodes == 2:
8048
      self.op.snode = ial.result[1]
8049

    
8050
  def BuildHooksEnv(self):
8051
    """Build hooks env.
8052

8053
    This runs on master, primary and secondary nodes of the instance.
8054

8055
    """
8056
    env = {
8057
      "ADD_MODE": self.op.mode,
8058
      }
8059
    if self.op.mode == constants.INSTANCE_IMPORT:
8060
      env["SRC_NODE"] = self.op.src_node
8061
      env["SRC_PATH"] = self.op.src_path
8062
      env["SRC_IMAGES"] = self.src_images
8063

    
8064
    env.update(_BuildInstanceHookEnv(
8065
      name=self.op.instance_name,
8066
      primary_node=self.op.pnode,
8067
      secondary_nodes=self.secondaries,
8068
      status=self.op.start,
8069
      os_type=self.op.os_type,
8070
      memory=self.be_full[constants.BE_MEMORY],
8071
      vcpus=self.be_full[constants.BE_VCPUS],
8072
      nics=_NICListToTuple(self, self.nics),
8073
      disk_template=self.op.disk_template,
8074
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8075
             for d in self.disks],
8076
      bep=self.be_full,
8077
      hvp=self.hv_full,
8078
      hypervisor_name=self.op.hypervisor,
8079
      tags=self.op.tags,
8080
    ))
8081

    
8082
    return env
8083

    
8084
  def BuildHooksNodes(self):
8085
    """Build hooks nodes.
8086

8087
    """
8088
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8089
    return nl, nl
8090

    
8091
  def _ReadExportInfo(self):
8092
    """Reads the export information from disk.
8093

8094
    It will override the opcode source node and path with the actual
8095
    information, if these two were not specified before.
8096

8097
    @return: the export information
8098

8099
    """
8100
    assert self.op.mode == constants.INSTANCE_IMPORT
8101

    
8102
    src_node = self.op.src_node
8103
    src_path = self.op.src_path
8104

    
8105
    if src_node is None:
8106
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
8107
      exp_list = self.rpc.call_export_list(locked_nodes)
8108
      found = False
8109
      for node in exp_list:
8110
        if exp_list[node].fail_msg:
8111
          continue
8112
        if src_path in exp_list[node].payload:
8113
          found = True
8114
          self.op.src_node = src_node = node
8115
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8116
                                                       src_path)
8117
          break
8118
      if not found:
8119
        raise errors.OpPrereqError("No export found for relative path %s" %
8120
                                    src_path, errors.ECODE_INVAL)
8121

    
8122
    _CheckNodeOnline(self, src_node)
8123
    result = self.rpc.call_export_info(src_node, src_path)
8124
    result.Raise("No export or invalid export found in dir %s" % src_path)
8125

    
8126
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8127
    if not export_info.has_section(constants.INISECT_EXP):
8128
      raise errors.ProgrammerError("Corrupted export config",
8129
                                   errors.ECODE_ENVIRON)
8130

    
8131
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8132
    if (int(ei_version) != constants.EXPORT_VERSION):
8133
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8134
                                 (ei_version, constants.EXPORT_VERSION),
8135
                                 errors.ECODE_ENVIRON)
8136
    return export_info
8137

    
8138
  def _ReadExportParams(self, einfo):
8139
    """Use export parameters as defaults.
8140

8141
    In case the opcode doesn't specify (as in override) some instance
8142
    parameters, then try to use them from the export information, if
8143
    that declares them.
8144

8145
    """
8146
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8147

    
8148
    if self.op.disk_template is None:
8149
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8150
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8151
                                          "disk_template")
8152
      else:
8153
        raise errors.OpPrereqError("No disk template specified and the export"
8154
                                   " is missing the disk_template information",
8155
                                   errors.ECODE_INVAL)
8156

    
8157
    if not self.op.disks:
8158
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
8159
        disks = []
8160
        # TODO: import the disk iv_name too
8161
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8162
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8163
          disks.append({constants.IDISK_SIZE: disk_sz})
8164
        self.op.disks = disks
8165
      else:
8166
        raise errors.OpPrereqError("No disk info specified and the export"
8167
                                   " is missing the disk information",
8168
                                   errors.ECODE_INVAL)
8169

    
8170
    if (not self.op.nics and
8171
        einfo.has_option(constants.INISECT_INS, "nic_count")):
8172
      nics = []
8173
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8174
        ndict = {}
8175
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8176
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8177
          ndict[name] = v
8178
        nics.append(ndict)
8179
      self.op.nics = nics
8180

    
8181
    if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
8182
      self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
8183

    
8184
    if (self.op.hypervisor is None and
8185
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
8186
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8187

    
8188
    if einfo.has_section(constants.INISECT_HYP):
8189
      # use the export parameters but do not override the ones
8190
      # specified by the user
8191
      for name, value in einfo.items(constants.INISECT_HYP):
8192
        if name not in self.op.hvparams:
8193
          self.op.hvparams[name] = value
8194

    
8195
    if einfo.has_section(constants.INISECT_BEP):
8196
      # use the parameters, without overriding
8197
      for name, value in einfo.items(constants.INISECT_BEP):
8198
        if name not in self.op.beparams:
8199
          self.op.beparams[name] = value
8200
    else:
8201
      # try to read the parameters old style, from the main section
8202
      for name in constants.BES_PARAMETERS:
8203
        if (name not in self.op.beparams and
8204
            einfo.has_option(constants.INISECT_INS, name)):
8205
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8206

    
8207
    if einfo.has_section(constants.INISECT_OSP):
8208
      # use the parameters, without overriding
8209
      for name, value in einfo.items(constants.INISECT_OSP):
8210
        if name not in self.op.osparams:
8211
          self.op.osparams[name] = value
8212

    
8213
  def _RevertToDefaults(self, cluster):
8214
    """Revert the instance parameters to the default values.
8215

8216
    """
8217
    # hvparams
8218
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8219
    for name in self.op.hvparams.keys():
8220
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8221
        del self.op.hvparams[name]
8222
    # beparams
8223
    be_defs = cluster.SimpleFillBE({})
8224
    for name in self.op.beparams.keys():
8225
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8226
        del self.op.beparams[name]
8227
    # nic params
8228
    nic_defs = cluster.SimpleFillNIC({})
8229
    for nic in self.op.nics:
8230
      for name in constants.NICS_PARAMETERS:
8231
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8232
          del nic[name]
8233
    # osparams
8234
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8235
    for name in self.op.osparams.keys():
8236
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8237
        del self.op.osparams[name]
8238

    
8239
  def _CalculateFileStorageDir(self):
8240
    """Calculate final instance file storage dir.
8241

8242
    """
8243
    # file storage dir calculation/check
8244
    self.instance_file_storage_dir = None
8245
    if self.op.disk_template in constants.DTS_FILEBASED:
8246
      # build the full file storage dir path
8247
      joinargs = []
8248

    
8249
      if self.op.disk_template == constants.DT_SHARED_FILE:
8250
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8251
      else:
8252
        get_fsd_fn = self.cfg.GetFileStorageDir
8253

    
8254
      cfg_storagedir = get_fsd_fn()
8255
      if not cfg_storagedir:
8256
        raise errors.OpPrereqError("Cluster file storage dir not defined")
8257
      joinargs.append(cfg_storagedir)
8258

    
8259
      if self.op.file_storage_dir is not None:
8260
        joinargs.append(self.op.file_storage_dir)
8261

    
8262
      joinargs.append(self.op.instance_name)
8263

    
8264
      # pylint: disable-msg=W0142
8265
      self.instance_file_storage_dir = utils.PathJoin(*joinargs)
8266

    
8267
  def CheckPrereq(self):
8268
    """Check prerequisites.
8269

8270
    """
8271
    self._CalculateFileStorageDir()
8272

    
8273
    if self.op.mode == constants.INSTANCE_IMPORT:
8274
      export_info = self._ReadExportInfo()
8275
      self._ReadExportParams(export_info)
8276

    
8277
    if (not self.cfg.GetVGName() and
8278
        self.op.disk_template not in constants.DTS_NOT_LVM):
8279
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8280
                                 " instances", errors.ECODE_STATE)
8281

    
8282
    if self.op.hypervisor is None:
8283
      self.op.hypervisor = self.cfg.GetHypervisorType()
8284

    
8285
    cluster = self.cfg.GetClusterInfo()
8286
    enabled_hvs = cluster.enabled_hypervisors
8287
    if self.op.hypervisor not in enabled_hvs:
8288
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8289
                                 " cluster (%s)" % (self.op.hypervisor,
8290
                                  ",".join(enabled_hvs)),
8291
                                 errors.ECODE_STATE)
8292

    
8293
    # Check tag validity
8294
    for tag in self.op.tags:
8295
      objects.TaggableObject.ValidateTag(tag)
8296

    
8297
    # check hypervisor parameter syntax (locally)
8298
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8299
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8300
                                      self.op.hvparams)
8301
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8302
    hv_type.CheckParameterSyntax(filled_hvp)
8303
    self.hv_full = filled_hvp
8304
    # check that we don't specify global parameters on an instance
8305
    _CheckGlobalHvParams(self.op.hvparams)
8306

    
8307
    # fill and remember the beparams dict
8308
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8309
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8310

    
8311
    # build os parameters
8312
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8313

    
8314
    # now that hvp/bep are in final format, let's reset to defaults,
8315
    # if told to do so
8316
    if self.op.identify_defaults:
8317
      self._RevertToDefaults(cluster)
8318

    
8319
    # NIC buildup
8320
    self.nics = []
8321
    for idx, nic in enumerate(self.op.nics):
8322
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8323
      nic_mode = nic_mode_req
8324
      if nic_mode is None:
8325
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8326

    
8327
      # in routed mode, for the first nic, the default ip is 'auto'
8328
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8329
        default_ip_mode = constants.VALUE_AUTO
8330
      else:
8331
        default_ip_mode = constants.VALUE_NONE
8332

    
8333
      # ip validity checks
8334
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8335
      if ip is None or ip.lower() == constants.VALUE_NONE:
8336
        nic_ip = None
8337
      elif ip.lower() == constants.VALUE_AUTO:
8338
        if not self.op.name_check:
8339
          raise errors.OpPrereqError("IP address set to auto but name checks"
8340
                                     " have been skipped",
8341
                                     errors.ECODE_INVAL)
8342
        nic_ip = self.hostname1.ip
8343
      else:
8344
        if not netutils.IPAddress.IsValid(ip):
8345
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8346
                                     errors.ECODE_INVAL)
8347
        nic_ip = ip
8348

    
8349
      # TODO: check the ip address for uniqueness
8350
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8351
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8352
                                   errors.ECODE_INVAL)
8353

    
8354
      # MAC address verification
8355
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8356
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8357
        mac = utils.NormalizeAndValidateMac(mac)
8358

    
8359
        try:
8360
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8361
        except errors.ReservationError:
8362
          raise errors.OpPrereqError("MAC address %s already in use"
8363
                                     " in cluster" % mac,
8364
                                     errors.ECODE_NOTUNIQUE)
8365

    
8366
      #  Build nic parameters
8367
      link = nic.get(constants.INIC_LINK, None)
8368
      nicparams = {}
8369
      if nic_mode_req:
8370
        nicparams[constants.NIC_MODE] = nic_mode_req
8371
      if link:
8372
        nicparams[constants.NIC_LINK] = link
8373

    
8374
      check_params = cluster.SimpleFillNIC(nicparams)
8375
      objects.NIC.CheckParameterSyntax(check_params)
8376
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8377

    
8378
    # disk checks/pre-build
8379
    default_vg = self.cfg.GetVGName()
8380
    self.disks = []
8381
    for disk in self.op.disks:
8382
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8383
      if mode not in constants.DISK_ACCESS_SET:
8384
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8385
                                   mode, errors.ECODE_INVAL)
8386
      size = disk.get(constants.IDISK_SIZE, None)
8387
      if size is None:
8388
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8389
      try:
8390
        size = int(size)
8391
      except (TypeError, ValueError):
8392
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8393
                                   errors.ECODE_INVAL)
8394

    
8395
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8396
      new_disk = {
8397
        constants.IDISK_SIZE: size,
8398
        constants.IDISK_MODE: mode,
8399
        constants.IDISK_VG: data_vg,
8400
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8401
        }
8402
      if constants.IDISK_ADOPT in disk:
8403
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8404
      self.disks.append(new_disk)
8405

    
8406
    if self.op.mode == constants.INSTANCE_IMPORT:
8407

    
8408
      # Check that the new instance doesn't have less disks than the export
8409
      instance_disks = len(self.disks)
8410
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8411
      if instance_disks < export_disks:
8412
        raise errors.OpPrereqError("Not enough disks to import."
8413
                                   " (instance: %d, export: %d)" %
8414
                                   (instance_disks, export_disks),
8415
                                   errors.ECODE_INVAL)
8416

    
8417
      disk_images = []
8418
      for idx in range(export_disks):
8419
        option = 'disk%d_dump' % idx
8420
        if export_info.has_option(constants.INISECT_INS, option):
8421
          # FIXME: are the old os-es, disk sizes, etc. useful?
8422
          export_name = export_info.get(constants.INISECT_INS, option)
8423
          image = utils.PathJoin(self.op.src_path, export_name)
8424
          disk_images.append(image)
8425
        else:
8426
          disk_images.append(False)
8427

    
8428
      self.src_images = disk_images
8429

    
8430
      old_name = export_info.get(constants.INISECT_INS, 'name')
8431
      try:
8432
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8433
      except (TypeError, ValueError), err:
8434
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8435
                                   " an integer: %s" % str(err),
8436
                                   errors.ECODE_STATE)
8437
      if self.op.instance_name == old_name:
8438
        for idx, nic in enumerate(self.nics):
8439
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8440
            nic_mac_ini = 'nic%d_mac' % idx
8441
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8442

    
8443
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8444

    
8445
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8446
    if self.op.ip_check:
8447
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8448
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8449
                                   (self.check_ip, self.op.instance_name),
8450
                                   errors.ECODE_NOTUNIQUE)
8451

    
8452
    #### mac address generation
8453
    # By generating here the mac address both the allocator and the hooks get
8454
    # the real final mac address rather than the 'auto' or 'generate' value.
8455
    # There is a race condition between the generation and the instance object
8456
    # creation, which means that we know the mac is valid now, but we're not
8457
    # sure it will be when we actually add the instance. If things go bad
8458
    # adding the instance will abort because of a duplicate mac, and the
8459
    # creation job will fail.
8460
    for nic in self.nics:
8461
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8462
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8463

    
8464
    #### allocator run
8465

    
8466
    if self.op.iallocator is not None:
8467
      self._RunAllocator()
8468

    
8469
    #### node related checks
8470

    
8471
    # check primary node
8472
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8473
    assert self.pnode is not None, \
8474
      "Cannot retrieve locked node %s" % self.op.pnode
8475
    if pnode.offline:
8476
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8477
                                 pnode.name, errors.ECODE_STATE)
8478
    if pnode.drained:
8479
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8480
                                 pnode.name, errors.ECODE_STATE)
8481
    if not pnode.vm_capable:
8482
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8483
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8484

    
8485
    self.secondaries = []
8486

    
8487
    # mirror node verification
8488
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8489
      if self.op.snode == pnode.name:
8490
        raise errors.OpPrereqError("The secondary node cannot be the"
8491
                                   " primary node", errors.ECODE_INVAL)
8492
      _CheckNodeOnline(self, self.op.snode)
8493
      _CheckNodeNotDrained(self, self.op.snode)
8494
      _CheckNodeVmCapable(self, self.op.snode)
8495
      self.secondaries.append(self.op.snode)
8496

    
8497
    nodenames = [pnode.name] + self.secondaries
8498

    
8499
    if not self.adopt_disks:
8500
      # Check lv size requirements, if not adopting
8501
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8502
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8503

    
8504
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8505
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8506
                                disk[constants.IDISK_ADOPT])
8507
                     for disk in self.disks])
8508
      if len(all_lvs) != len(self.disks):
8509
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8510
                                   errors.ECODE_INVAL)
8511
      for lv_name in all_lvs:
8512
        try:
8513
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8514
          # to ReserveLV uses the same syntax
8515
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8516
        except errors.ReservationError:
8517
          raise errors.OpPrereqError("LV named %s used by another instance" %
8518
                                     lv_name, errors.ECODE_NOTUNIQUE)
8519

    
8520
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8521
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8522

    
8523
      node_lvs = self.rpc.call_lv_list([pnode.name],
8524
                                       vg_names.payload.keys())[pnode.name]
8525
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8526
      node_lvs = node_lvs.payload
8527

    
8528
      delta = all_lvs.difference(node_lvs.keys())
8529
      if delta:
8530
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8531
                                   utils.CommaJoin(delta),
8532
                                   errors.ECODE_INVAL)
8533
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8534
      if online_lvs:
8535
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8536
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8537
                                   errors.ECODE_STATE)
8538
      # update the size of disk based on what is found
8539
      for dsk in self.disks:
8540
        dsk[constants.IDISK_SIZE] = \
8541
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8542
                                        dsk[constants.IDISK_ADOPT])][0]))
8543

    
8544
    elif self.op.disk_template == constants.DT_BLOCK:
8545
      # Normalize and de-duplicate device paths
8546
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8547
                       for disk in self.disks])
8548
      if len(all_disks) != len(self.disks):
8549
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8550
                                   errors.ECODE_INVAL)
8551
      baddisks = [d for d in all_disks
8552
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8553
      if baddisks:
8554
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8555
                                   " cannot be adopted" %
8556
                                   (", ".join(baddisks),
8557
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8558
                                   errors.ECODE_INVAL)
8559

    
8560
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8561
                                            list(all_disks))[pnode.name]
8562
      node_disks.Raise("Cannot get block device information from node %s" %
8563
                       pnode.name)
8564
      node_disks = node_disks.payload
8565
      delta = all_disks.difference(node_disks.keys())
8566
      if delta:
8567
        raise errors.OpPrereqError("Missing block device(s): %s" %
8568
                                   utils.CommaJoin(delta),
8569
                                   errors.ECODE_INVAL)
8570
      for dsk in self.disks:
8571
        dsk[constants.IDISK_SIZE] = \
8572
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8573

    
8574
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8575

    
8576
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8577
    # check OS parameters (remotely)
8578
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8579

    
8580
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8581

    
8582
    # memory check on primary node
8583
    if self.op.start:
8584
      _CheckNodeFreeMemory(self, self.pnode.name,
8585
                           "creating instance %s" % self.op.instance_name,
8586
                           self.be_full[constants.BE_MEMORY],
8587
                           self.op.hypervisor)
8588

    
8589
    self.dry_run_result = list(nodenames)
8590

    
8591
  def Exec(self, feedback_fn):
8592
    """Create and add the instance to the cluster.
8593

8594
    """
8595
    instance = self.op.instance_name
8596
    pnode_name = self.pnode.name
8597

    
8598
    ht_kind = self.op.hypervisor
8599
    if ht_kind in constants.HTS_REQ_PORT:
8600
      network_port = self.cfg.AllocatePort()
8601
    else:
8602
      network_port = None
8603

    
8604
    disks = _GenerateDiskTemplate(self,
8605
                                  self.op.disk_template,
8606
                                  instance, pnode_name,
8607
                                  self.secondaries,
8608
                                  self.disks,
8609
                                  self.instance_file_storage_dir,
8610
                                  self.op.file_driver,
8611
                                  0,
8612
                                  feedback_fn)
8613

    
8614
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8615
                            primary_node=pnode_name,
8616
                            nics=self.nics, disks=disks,
8617
                            disk_template=self.op.disk_template,
8618
                            admin_up=False,
8619
                            network_port=network_port,
8620
                            beparams=self.op.beparams,
8621
                            hvparams=self.op.hvparams,
8622
                            hypervisor=self.op.hypervisor,
8623
                            osparams=self.op.osparams,
8624
                            )
8625

    
8626
    if self.op.tags:
8627
      for tag in self.op.tags:
8628
        iobj.AddTag(tag)
8629

    
8630
    if self.adopt_disks:
8631
      if self.op.disk_template == constants.DT_PLAIN:
8632
        # rename LVs to the newly-generated names; we need to construct
8633
        # 'fake' LV disks with the old data, plus the new unique_id
8634
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8635
        rename_to = []
8636
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8637
          rename_to.append(t_dsk.logical_id)
8638
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8639
          self.cfg.SetDiskID(t_dsk, pnode_name)
8640
        result = self.rpc.call_blockdev_rename(pnode_name,
8641
                                               zip(tmp_disks, rename_to))
8642
        result.Raise("Failed to rename adoped LVs")
8643
    else:
8644
      feedback_fn("* creating instance disks...")
8645
      try:
8646
        _CreateDisks(self, iobj)
8647
      except errors.OpExecError:
8648
        self.LogWarning("Device creation failed, reverting...")
8649
        try:
8650
          _RemoveDisks(self, iobj)
8651
        finally:
8652
          self.cfg.ReleaseDRBDMinors(instance)
8653
          raise
8654

    
8655
    feedback_fn("adding instance %s to cluster config" % instance)
8656

    
8657
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8658

    
8659
    # Declare that we don't want to remove the instance lock anymore, as we've
8660
    # added the instance to the config
8661
    del self.remove_locks[locking.LEVEL_INSTANCE]
8662

    
8663
    if self.op.mode == constants.INSTANCE_IMPORT:
8664
      # Release unused nodes
8665
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8666
    else:
8667
      # Release all nodes
8668
      _ReleaseLocks(self, locking.LEVEL_NODE)
8669

    
8670
    disk_abort = False
8671
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8672
      feedback_fn("* wiping instance disks...")
8673
      try:
8674
        _WipeDisks(self, iobj)
8675
      except errors.OpExecError, err:
8676
        logging.exception("Wiping disks failed")
8677
        self.LogWarning("Wiping instance disks failed (%s)", err)
8678
        disk_abort = True
8679

    
8680
    if disk_abort:
8681
      # Something is already wrong with the disks, don't do anything else
8682
      pass
8683
    elif self.op.wait_for_sync:
8684
      disk_abort = not _WaitForSync(self, iobj)
8685
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8686
      # make sure the disks are not degraded (still sync-ing is ok)
8687
      time.sleep(15)
8688
      feedback_fn("* checking mirrors status")
8689
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8690
    else:
8691
      disk_abort = False
8692

    
8693
    if disk_abort:
8694
      _RemoveDisks(self, iobj)
8695
      self.cfg.RemoveInstance(iobj.name)
8696
      # Make sure the instance lock gets removed
8697
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8698
      raise errors.OpExecError("There are some degraded disks for"
8699
                               " this instance")
8700

    
8701
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8702
      if self.op.mode == constants.INSTANCE_CREATE:
8703
        if not self.op.no_install:
8704
          feedback_fn("* running the instance OS create scripts...")
8705
          # FIXME: pass debug option from opcode to backend
8706
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8707
                                                 self.op.debug_level)
8708
          result.Raise("Could not add os for instance %s"
8709
                       " on node %s" % (instance, pnode_name))
8710

    
8711
      elif self.op.mode == constants.INSTANCE_IMPORT:
8712
        feedback_fn("* running the instance OS import scripts...")
8713

    
8714
        transfers = []
8715

    
8716
        for idx, image in enumerate(self.src_images):
8717
          if not image:
8718
            continue
8719

    
8720
          # FIXME: pass debug option from opcode to backend
8721
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8722
                                             constants.IEIO_FILE, (image, ),
8723
                                             constants.IEIO_SCRIPT,
8724
                                             (iobj.disks[idx], idx),
8725
                                             None)
8726
          transfers.append(dt)
8727

    
8728
        import_result = \
8729
          masterd.instance.TransferInstanceData(self, feedback_fn,
8730
                                                self.op.src_node, pnode_name,
8731
                                                self.pnode.secondary_ip,
8732
                                                iobj, transfers)
8733
        if not compat.all(import_result):
8734
          self.LogWarning("Some disks for instance %s on node %s were not"
8735
                          " imported successfully" % (instance, pnode_name))
8736

    
8737
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8738
        feedback_fn("* preparing remote import...")
8739
        # The source cluster will stop the instance before attempting to make a
8740
        # connection. In some cases stopping an instance can take a long time,
8741
        # hence the shutdown timeout is added to the connection timeout.
8742
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8743
                           self.op.source_shutdown_timeout)
8744
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8745

    
8746
        assert iobj.primary_node == self.pnode.name
8747
        disk_results = \
8748
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8749
                                        self.source_x509_ca,
8750
                                        self._cds, timeouts)
8751
        if not compat.all(disk_results):
8752
          # TODO: Should the instance still be started, even if some disks
8753
          # failed to import (valid for local imports, too)?
8754
          self.LogWarning("Some disks for instance %s on node %s were not"
8755
                          " imported successfully" % (instance, pnode_name))
8756

    
8757
        # Run rename script on newly imported instance
8758
        assert iobj.name == instance
8759
        feedback_fn("Running rename script for %s" % instance)
8760
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8761
                                                   self.source_instance_name,
8762
                                                   self.op.debug_level)
8763
        if result.fail_msg:
8764
          self.LogWarning("Failed to run rename script for %s on node"
8765
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8766

    
8767
      else:
8768
        # also checked in the prereq part
8769
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8770
                                     % self.op.mode)
8771

    
8772
    if self.op.start:
8773
      iobj.admin_up = True
8774
      self.cfg.Update(iobj, feedback_fn)
8775
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8776
      feedback_fn("* starting instance...")
8777
      result = self.rpc.call_instance_start(pnode_name, iobj,
8778
                                            None, None, False)
8779
      result.Raise("Could not start instance")
8780

    
8781
    return list(iobj.all_nodes)
8782

    
8783

    
8784
class LUInstanceConsole(NoHooksLU):
8785
  """Connect to an instance's console.
8786

8787
  This is somewhat special in that it returns the command line that
8788
  you need to run on the master node in order to connect to the
8789
  console.
8790

8791
  """
8792
  REQ_BGL = False
8793

    
8794
  def ExpandNames(self):
8795
    self._ExpandAndLockInstance()
8796

    
8797
  def CheckPrereq(self):
8798
    """Check prerequisites.
8799

8800
    This checks that the instance is in the cluster.
8801

8802
    """
8803
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8804
    assert self.instance is not None, \
8805
      "Cannot retrieve locked instance %s" % self.op.instance_name
8806
    _CheckNodeOnline(self, self.instance.primary_node)
8807

    
8808
  def Exec(self, feedback_fn):
8809
    """Connect to the console of an instance
8810

8811
    """
8812
    instance = self.instance
8813
    node = instance.primary_node
8814

    
8815
    node_insts = self.rpc.call_instance_list([node],
8816
                                             [instance.hypervisor])[node]
8817
    node_insts.Raise("Can't get node information from %s" % node)
8818

    
8819
    if instance.name not in node_insts.payload:
8820
      if instance.admin_up:
8821
        state = constants.INSTST_ERRORDOWN
8822
      else:
8823
        state = constants.INSTST_ADMINDOWN
8824
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8825
                               (instance.name, state))
8826

    
8827
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8828

    
8829
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8830

    
8831

    
8832
def _GetInstanceConsole(cluster, instance):
8833
  """Returns console information for an instance.
8834

8835
  @type cluster: L{objects.Cluster}
8836
  @type instance: L{objects.Instance}
8837
  @rtype: dict
8838

8839
  """
8840
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8841
  # beparams and hvparams are passed separately, to avoid editing the
8842
  # instance and then saving the defaults in the instance itself.
8843
  hvparams = cluster.FillHV(instance)
8844
  beparams = cluster.FillBE(instance)
8845
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8846

    
8847
  assert console.instance == instance.name
8848
  assert console.Validate()
8849

    
8850
  return console.ToDict()
8851

    
8852

    
8853
class LUInstanceReplaceDisks(LogicalUnit):
8854
  """Replace the disks of an instance.
8855

8856
  """
8857
  HPATH = "mirrors-replace"
8858
  HTYPE = constants.HTYPE_INSTANCE
8859
  REQ_BGL = False
8860

    
8861
  def CheckArguments(self):
8862
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8863
                                  self.op.iallocator)
8864

    
8865
  def ExpandNames(self):
8866
    self._ExpandAndLockInstance()
8867

    
8868
    assert locking.LEVEL_NODE not in self.needed_locks
8869
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8870

    
8871
    assert self.op.iallocator is None or self.op.remote_node is None, \
8872
      "Conflicting options"
8873

    
8874
    if self.op.remote_node is not None:
8875
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8876

    
8877
      # Warning: do not remove the locking of the new secondary here
8878
      # unless DRBD8.AddChildren is changed to work in parallel;
8879
      # currently it doesn't since parallel invocations of
8880
      # FindUnusedMinor will conflict
8881
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8882
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8883
    else:
8884
      self.needed_locks[locking.LEVEL_NODE] = []
8885
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8886

    
8887
      if self.op.iallocator is not None:
8888
        # iallocator will select a new node in the same group
8889
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8890

    
8891
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8892
                                   self.op.iallocator, self.op.remote_node,
8893
                                   self.op.disks, False, self.op.early_release)
8894

    
8895
    self.tasklets = [self.replacer]
8896

    
8897
  def DeclareLocks(self, level):
8898
    if level == locking.LEVEL_NODEGROUP:
8899
      assert self.op.remote_node is None
8900
      assert self.op.iallocator is not None
8901
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8902

    
8903
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8904
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8905
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8906

    
8907
    elif level == locking.LEVEL_NODE:
8908
      if self.op.iallocator is not None:
8909
        assert self.op.remote_node is None
8910
        assert not self.needed_locks[locking.LEVEL_NODE]
8911

    
8912
        # Lock member nodes of all locked groups
8913
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8914
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8915
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8916
      else:
8917
        self._LockInstancesNodes()
8918

    
8919
  def BuildHooksEnv(self):
8920
    """Build hooks env.
8921

8922
    This runs on the master, the primary and all the secondaries.
8923

8924
    """
8925
    instance = self.replacer.instance
8926
    env = {
8927
      "MODE": self.op.mode,
8928
      "NEW_SECONDARY": self.op.remote_node,
8929
      "OLD_SECONDARY": instance.secondary_nodes[0],
8930
      }
8931
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8932
    return env
8933

    
8934
  def BuildHooksNodes(self):
8935
    """Build hooks nodes.
8936

8937
    """
8938
    instance = self.replacer.instance
8939
    nl = [
8940
      self.cfg.GetMasterNode(),
8941
      instance.primary_node,
8942
      ]
8943
    if self.op.remote_node is not None:
8944
      nl.append(self.op.remote_node)
8945
    return nl, nl
8946

    
8947
  def CheckPrereq(self):
8948
    """Check prerequisites.
8949

8950
    """
8951
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8952
            self.op.iallocator is None)
8953

    
8954
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8955
    if owned_groups:
8956
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8957
      if owned_groups != groups:
8958
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8959
                                 " since lock was acquired, current list is %r,"
8960
                                 " used to be '%s'" %
8961
                                 (self.op.instance_name,
8962
                                  utils.CommaJoin(groups),
8963
                                  utils.CommaJoin(owned_groups)))
8964

    
8965
    return LogicalUnit.CheckPrereq(self)
8966

    
8967

    
8968
class TLReplaceDisks(Tasklet):
8969
  """Replaces disks for an instance.
8970

8971
  Note: Locking is not within the scope of this class.
8972

8973
  """
8974
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8975
               disks, delay_iallocator, early_release):
8976
    """Initializes this class.
8977

8978
    """
8979
    Tasklet.__init__(self, lu)
8980

    
8981
    # Parameters
8982
    self.instance_name = instance_name
8983
    self.mode = mode
8984
    self.iallocator_name = iallocator_name
8985
    self.remote_node = remote_node
8986
    self.disks = disks
8987
    self.delay_iallocator = delay_iallocator
8988
    self.early_release = early_release
8989

    
8990
    # Runtime data
8991
    self.instance = None
8992
    self.new_node = None
8993
    self.target_node = None
8994
    self.other_node = None
8995
    self.remote_node_info = None
8996
    self.node_secondary_ip = None
8997

    
8998
  @staticmethod
8999
  def CheckArguments(mode, remote_node, iallocator):
9000
    """Helper function for users of this class.
9001

9002
    """
9003
    # check for valid parameter combination
9004
    if mode == constants.REPLACE_DISK_CHG:
9005
      if remote_node is None and iallocator is None:
9006
        raise errors.OpPrereqError("When changing the secondary either an"
9007
                                   " iallocator script must be used or the"
9008
                                   " new node given", errors.ECODE_INVAL)
9009

    
9010
      if remote_node is not None and iallocator is not None:
9011
        raise errors.OpPrereqError("Give either the iallocator or the new"
9012
                                   " secondary, not both", errors.ECODE_INVAL)
9013

    
9014
    elif remote_node is not None or iallocator is not None:
9015
      # Not replacing the secondary
9016
      raise errors.OpPrereqError("The iallocator and new node options can"
9017
                                 " only be used when changing the"
9018
                                 " secondary node", errors.ECODE_INVAL)
9019

    
9020
  @staticmethod
9021
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
9022
    """Compute a new secondary node using an IAllocator.
9023

9024
    """
9025
    ial = IAllocator(lu.cfg, lu.rpc,
9026
                     mode=constants.IALLOCATOR_MODE_RELOC,
9027
                     name=instance_name,
9028
                     relocate_from=relocate_from)
9029

    
9030
    ial.Run(iallocator_name)
9031

    
9032
    if not ial.success:
9033
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
9034
                                 " %s" % (iallocator_name, ial.info),
9035
                                 errors.ECODE_NORES)
9036

    
9037
    if len(ial.result) != ial.required_nodes:
9038
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9039
                                 " of nodes (%s), required %s" %
9040
                                 (iallocator_name,
9041
                                  len(ial.result), ial.required_nodes),
9042
                                 errors.ECODE_FAULT)
9043

    
9044
    remote_node_name = ial.result[0]
9045

    
9046
    lu.LogInfo("Selected new secondary for instance '%s': %s",
9047
               instance_name, remote_node_name)
9048

    
9049
    return remote_node_name
9050

    
9051
  def _FindFaultyDisks(self, node_name):
9052
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9053
                                    node_name, True)
9054

    
9055
  def _CheckDisksActivated(self, instance):
9056
    """Checks if the instance disks are activated.
9057

9058
    @param instance: The instance to check disks
9059
    @return: True if they are activated, False otherwise
9060

9061
    """
9062
    nodes = instance.all_nodes
9063

    
9064
    for idx, dev in enumerate(instance.disks):
9065
      for node in nodes:
9066
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9067
        self.cfg.SetDiskID(dev, node)
9068

    
9069
        result = self.rpc.call_blockdev_find(node, dev)
9070

    
9071
        if result.offline:
9072
          continue
9073
        elif result.fail_msg or not result.payload:
9074
          return False
9075

    
9076
    return True
9077

    
9078
  def CheckPrereq(self):
9079
    """Check prerequisites.
9080

9081
    This checks that the instance is in the cluster.
9082

9083
    """
9084
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9085
    assert instance is not None, \
9086
      "Cannot retrieve locked instance %s" % self.instance_name
9087

    
9088
    if instance.disk_template != constants.DT_DRBD8:
9089
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9090
                                 " instances", errors.ECODE_INVAL)
9091

    
9092
    if len(instance.secondary_nodes) != 1:
9093
      raise errors.OpPrereqError("The instance has a strange layout,"
9094
                                 " expected one secondary but found %d" %
9095
                                 len(instance.secondary_nodes),
9096
                                 errors.ECODE_FAULT)
9097

    
9098
    if not self.delay_iallocator:
9099
      self._CheckPrereq2()
9100

    
9101
  def _CheckPrereq2(self):
9102
    """Check prerequisites, second part.
9103

9104
    This function should always be part of CheckPrereq. It was separated and is
9105
    now called from Exec because during node evacuation iallocator was only
9106
    called with an unmodified cluster model, not taking planned changes into
9107
    account.
9108

9109
    """
9110
    instance = self.instance
9111
    secondary_node = instance.secondary_nodes[0]
9112

    
9113
    if self.iallocator_name is None:
9114
      remote_node = self.remote_node
9115
    else:
9116
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
9117
                                       instance.name, instance.secondary_nodes)
9118

    
9119
    if remote_node is None:
9120
      self.remote_node_info = None
9121
    else:
9122
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
9123
             "Remote node '%s' is not locked" % remote_node
9124

    
9125
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9126
      assert self.remote_node_info is not None, \
9127
        "Cannot retrieve locked node %s" % remote_node
9128

    
9129
    if remote_node == self.instance.primary_node:
9130
      raise errors.OpPrereqError("The specified node is the primary node of"
9131
                                 " the instance", errors.ECODE_INVAL)
9132

    
9133
    if remote_node == secondary_node:
9134
      raise errors.OpPrereqError("The specified node is already the"
9135
                                 " secondary node of the instance",
9136
                                 errors.ECODE_INVAL)
9137

    
9138
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9139
                                    constants.REPLACE_DISK_CHG):
9140
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
9141
                                 errors.ECODE_INVAL)
9142

    
9143
    if self.mode == constants.REPLACE_DISK_AUTO:
9144
      if not self._CheckDisksActivated(instance):
9145
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
9146
                                   " first" % self.instance_name,
9147
                                   errors.ECODE_STATE)
9148
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
9149
      faulty_secondary = self._FindFaultyDisks(secondary_node)
9150

    
9151
      if faulty_primary and faulty_secondary:
9152
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9153
                                   " one node and can not be repaired"
9154
                                   " automatically" % self.instance_name,
9155
                                   errors.ECODE_STATE)
9156

    
9157
      if faulty_primary:
9158
        self.disks = faulty_primary
9159
        self.target_node = instance.primary_node
9160
        self.other_node = secondary_node
9161
        check_nodes = [self.target_node, self.other_node]
9162
      elif faulty_secondary:
9163
        self.disks = faulty_secondary
9164
        self.target_node = secondary_node
9165
        self.other_node = instance.primary_node
9166
        check_nodes = [self.target_node, self.other_node]
9167
      else:
9168
        self.disks = []
9169
        check_nodes = []
9170

    
9171
    else:
9172
      # Non-automatic modes
9173
      if self.mode == constants.REPLACE_DISK_PRI:
9174
        self.target_node = instance.primary_node
9175
        self.other_node = secondary_node
9176
        check_nodes = [self.target_node, self.other_node]
9177

    
9178
      elif self.mode == constants.REPLACE_DISK_SEC:
9179
        self.target_node = secondary_node
9180
        self.other_node = instance.primary_node
9181
        check_nodes = [self.target_node, self.other_node]
9182

    
9183
      elif self.mode == constants.REPLACE_DISK_CHG:
9184
        self.new_node = remote_node
9185
        self.other_node = instance.primary_node
9186
        self.target_node = secondary_node
9187
        check_nodes = [self.new_node, self.other_node]
9188

    
9189
        _CheckNodeNotDrained(self.lu, remote_node)
9190
        _CheckNodeVmCapable(self.lu, remote_node)
9191

    
9192
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
9193
        assert old_node_info is not None
9194
        if old_node_info.offline and not self.early_release:
9195
          # doesn't make sense to delay the release
9196
          self.early_release = True
9197
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9198
                          " early-release mode", secondary_node)
9199

    
9200
      else:
9201
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9202
                                     self.mode)
9203

    
9204
      # If not specified all disks should be replaced
9205
      if not self.disks:
9206
        self.disks = range(len(self.instance.disks))
9207

    
9208
    for node in check_nodes:
9209
      _CheckNodeOnline(self.lu, node)
9210

    
9211
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
9212
                                                          self.other_node,
9213
                                                          self.target_node]
9214
                              if node_name is not None)
9215

    
9216
    # Release unneeded node locks
9217
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9218

    
9219
    # Release any owned node group
9220
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9221
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9222

    
9223
    # Check whether disks are valid
9224
    for disk_idx in self.disks:
9225
      instance.FindDisk(disk_idx)
9226

    
9227
    # Get secondary node IP addresses
9228
    self.node_secondary_ip = \
9229
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
9230
           for node_name in touched_nodes)
9231

    
9232
  def Exec(self, feedback_fn):
9233
    """Execute disk replacement.
9234

9235
    This dispatches the disk replacement to the appropriate handler.
9236

9237
    """
9238
    if self.delay_iallocator:
9239
      self._CheckPrereq2()
9240

    
9241
    if __debug__:
9242
      # Verify owned locks before starting operation
9243
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9244
      assert set(owned_locks) == set(self.node_secondary_ip), \
9245
          ("Incorrect node locks, owning %s, expected %s" %
9246
           (owned_locks, self.node_secondary_ip.keys()))
9247

    
9248
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9249
      assert list(owned_locks) == [self.instance_name], \
9250
          "Instance '%s' not locked" % self.instance_name
9251

    
9252
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9253
          "Should not own any node group lock at this point"
9254

    
9255
    if not self.disks:
9256
      feedback_fn("No disks need replacement")
9257
      return
9258

    
9259
    feedback_fn("Replacing disk(s) %s for %s" %
9260
                (utils.CommaJoin(self.disks), self.instance.name))
9261

    
9262
    activate_disks = (not self.instance.admin_up)
9263

    
9264
    # Activate the instance disks if we're replacing them on a down instance
9265
    if activate_disks:
9266
      _StartInstanceDisks(self.lu, self.instance, True)
9267

    
9268
    try:
9269
      # Should we replace the secondary node?
9270
      if self.new_node is not None:
9271
        fn = self._ExecDrbd8Secondary
9272
      else:
9273
        fn = self._ExecDrbd8DiskOnly
9274

    
9275
      result = fn(feedback_fn)
9276
    finally:
9277
      # Deactivate the instance disks if we're replacing them on a
9278
      # down instance
9279
      if activate_disks:
9280
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9281

    
9282
    if __debug__:
9283
      # Verify owned locks
9284
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9285
      nodes = frozenset(self.node_secondary_ip)
9286
      assert ((self.early_release and not owned_locks) or
9287
              (not self.early_release and not (set(owned_locks) - nodes))), \
9288
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9289
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9290

    
9291
    return result
9292

    
9293
  def _CheckVolumeGroup(self, nodes):
9294
    self.lu.LogInfo("Checking volume groups")
9295

    
9296
    vgname = self.cfg.GetVGName()
9297

    
9298
    # Make sure volume group exists on all involved nodes
9299
    results = self.rpc.call_vg_list(nodes)
9300
    if not results:
9301
      raise errors.OpExecError("Can't list volume groups on the nodes")
9302

    
9303
    for node in nodes:
9304
      res = results[node]
9305
      res.Raise("Error checking node %s" % node)
9306
      if vgname not in res.payload:
9307
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9308
                                 (vgname, node))
9309

    
9310
  def _CheckDisksExistence(self, nodes):
9311
    # Check disk existence
9312
    for idx, dev in enumerate(self.instance.disks):
9313
      if idx not in self.disks:
9314
        continue
9315

    
9316
      for node in nodes:
9317
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9318
        self.cfg.SetDiskID(dev, node)
9319

    
9320
        result = self.rpc.call_blockdev_find(node, dev)
9321

    
9322
        msg = result.fail_msg
9323
        if msg or not result.payload:
9324
          if not msg:
9325
            msg = "disk not found"
9326
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9327
                                   (idx, node, msg))
9328

    
9329
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9330
    for idx, dev in enumerate(self.instance.disks):
9331
      if idx not in self.disks:
9332
        continue
9333

    
9334
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9335
                      (idx, node_name))
9336

    
9337
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9338
                                   ldisk=ldisk):
9339
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9340
                                 " replace disks for instance %s" %
9341
                                 (node_name, self.instance.name))
9342

    
9343
  def _CreateNewStorage(self, node_name):
9344
    iv_names = {}
9345

    
9346
    for idx, dev in enumerate(self.instance.disks):
9347
      if idx not in self.disks:
9348
        continue
9349

    
9350
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
9351

    
9352
      self.cfg.SetDiskID(dev, node_name)
9353

    
9354
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9355
      names = _GenerateUniqueNames(self.lu, lv_names)
9356

    
9357
      vg_data = dev.children[0].logical_id[0]
9358
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9359
                             logical_id=(vg_data, names[0]))
9360
      vg_meta = dev.children[1].logical_id[0]
9361
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9362
                             logical_id=(vg_meta, names[1]))
9363

    
9364
      new_lvs = [lv_data, lv_meta]
9365
      old_lvs = dev.children
9366
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9367

    
9368
      # we pass force_create=True to force the LVM creation
9369
      for new_lv in new_lvs:
9370
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9371
                        _GetInstanceInfoText(self.instance), False)
9372

    
9373
    return iv_names
9374

    
9375
  def _CheckDevices(self, node_name, iv_names):
9376
    for name, (dev, _, _) in iv_names.iteritems():
9377
      self.cfg.SetDiskID(dev, node_name)
9378

    
9379
      result = self.rpc.call_blockdev_find(node_name, dev)
9380

    
9381
      msg = result.fail_msg
9382
      if msg or not result.payload:
9383
        if not msg:
9384
          msg = "disk not found"
9385
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9386
                                 (name, msg))
9387

    
9388
      if result.payload.is_degraded:
9389
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9390

    
9391
  def _RemoveOldStorage(self, node_name, iv_names):
9392
    for name, (_, old_lvs, _) in iv_names.iteritems():
9393
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9394

    
9395
      for lv in old_lvs:
9396
        self.cfg.SetDiskID(lv, node_name)
9397

    
9398
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9399
        if msg:
9400
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9401
                             hint="remove unused LVs manually")
9402

    
9403
  def _ExecDrbd8DiskOnly(self, feedback_fn):
9404
    """Replace a disk on the primary or secondary for DRBD 8.
9405

9406
    The algorithm for replace is quite complicated:
9407

9408
      1. for each disk to be replaced:
9409

9410
        1. create new LVs on the target node with unique names
9411
        1. detach old LVs from the drbd device
9412
        1. rename old LVs to name_replaced.<time_t>
9413
        1. rename new LVs to old LVs
9414
        1. attach the new LVs (with the old names now) to the drbd device
9415

9416
      1. wait for sync across all devices
9417

9418
      1. for each modified disk:
9419

9420
        1. remove old LVs (which have the name name_replaces.<time_t>)
9421

9422
    Failures are not very well handled.
9423

9424
    """
9425
    steps_total = 6
9426

    
9427
    # Step: check device activation
9428
    self.lu.LogStep(1, steps_total, "Check device existence")
9429
    self._CheckDisksExistence([self.other_node, self.target_node])
9430
    self._CheckVolumeGroup([self.target_node, self.other_node])
9431

    
9432
    # Step: check other node consistency
9433
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9434
    self._CheckDisksConsistency(self.other_node,
9435
                                self.other_node == self.instance.primary_node,
9436
                                False)
9437

    
9438
    # Step: create new storage
9439
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9440
    iv_names = self._CreateNewStorage(self.target_node)
9441

    
9442
    # Step: for each lv, detach+rename*2+attach
9443
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9444
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9445
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9446

    
9447
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9448
                                                     old_lvs)
9449
      result.Raise("Can't detach drbd from local storage on node"
9450
                   " %s for device %s" % (self.target_node, dev.iv_name))
9451
      #dev.children = []
9452
      #cfg.Update(instance)
9453

    
9454
      # ok, we created the new LVs, so now we know we have the needed
9455
      # storage; as such, we proceed on the target node to rename
9456
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9457
      # using the assumption that logical_id == physical_id (which in
9458
      # turn is the unique_id on that node)
9459

    
9460
      # FIXME(iustin): use a better name for the replaced LVs
9461
      temp_suffix = int(time.time())
9462
      ren_fn = lambda d, suff: (d.physical_id[0],
9463
                                d.physical_id[1] + "_replaced-%s" % suff)
9464

    
9465
      # Build the rename list based on what LVs exist on the node
9466
      rename_old_to_new = []
9467
      for to_ren in old_lvs:
9468
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9469
        if not result.fail_msg and result.payload:
9470
          # device exists
9471
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9472

    
9473
      self.lu.LogInfo("Renaming the old LVs on the target node")
9474
      result = self.rpc.call_blockdev_rename(self.target_node,
9475
                                             rename_old_to_new)
9476
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9477

    
9478
      # Now we rename the new LVs to the old LVs
9479
      self.lu.LogInfo("Renaming the new LVs on the target node")
9480
      rename_new_to_old = [(new, old.physical_id)
9481
                           for old, new in zip(old_lvs, new_lvs)]
9482
      result = self.rpc.call_blockdev_rename(self.target_node,
9483
                                             rename_new_to_old)
9484
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9485

    
9486
      for old, new in zip(old_lvs, new_lvs):
9487
        new.logical_id = old.logical_id
9488
        self.cfg.SetDiskID(new, self.target_node)
9489

    
9490
      for disk in old_lvs:
9491
        disk.logical_id = ren_fn(disk, temp_suffix)
9492
        self.cfg.SetDiskID(disk, self.target_node)
9493

    
9494
      # Now that the new lvs have the old name, we can add them to the device
9495
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9496
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9497
                                                  new_lvs)
9498
      msg = result.fail_msg
9499
      if msg:
9500
        for new_lv in new_lvs:
9501
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9502
                                               new_lv).fail_msg
9503
          if msg2:
9504
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9505
                               hint=("cleanup manually the unused logical"
9506
                                     "volumes"))
9507
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9508

    
9509
      dev.children = new_lvs
9510

    
9511
      self.cfg.Update(self.instance, feedback_fn)
9512

    
9513
    cstep = 5
9514
    if self.early_release:
9515
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9516
      cstep += 1
9517
      self._RemoveOldStorage(self.target_node, iv_names)
9518
      # WARNING: we release both node locks here, do not do other RPCs
9519
      # than WaitForSync to the primary node
9520
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9521
                    names=[self.target_node, self.other_node])
9522

    
9523
    # Wait for sync
9524
    # This can fail as the old devices are degraded and _WaitForSync
9525
    # does a combined result over all disks, so we don't check its return value
9526
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9527
    cstep += 1
9528
    _WaitForSync(self.lu, self.instance)
9529

    
9530
    # Check all devices manually
9531
    self._CheckDevices(self.instance.primary_node, iv_names)
9532

    
9533
    # Step: remove old storage
9534
    if not self.early_release:
9535
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9536
      cstep += 1
9537
      self._RemoveOldStorage(self.target_node, iv_names)
9538

    
9539
  def _ExecDrbd8Secondary(self, feedback_fn):
9540
    """Replace the secondary node for DRBD 8.
9541

9542
    The algorithm for replace is quite complicated:
9543
      - for all disks of the instance:
9544
        - create new LVs on the new node with same names
9545
        - shutdown the drbd device on the old secondary
9546
        - disconnect the drbd network on the primary
9547
        - create the drbd device on the new secondary
9548
        - network attach the drbd on the primary, using an artifice:
9549
          the drbd code for Attach() will connect to the network if it
9550
          finds a device which is connected to the good local disks but
9551
          not network enabled
9552
      - wait for sync across all devices
9553
      - remove all disks from the old secondary
9554

9555
    Failures are not very well handled.
9556

9557
    """
9558
    steps_total = 6
9559

    
9560
    # Step: check device activation
9561
    self.lu.LogStep(1, steps_total, "Check device existence")
9562
    self._CheckDisksExistence([self.instance.primary_node])
9563
    self._CheckVolumeGroup([self.instance.primary_node])
9564

    
9565
    # Step: check other node consistency
9566
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9567
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9568

    
9569
    # Step: create new storage
9570
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9571
    for idx, dev in enumerate(self.instance.disks):
9572
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9573
                      (self.new_node, idx))
9574
      # we pass force_create=True to force LVM creation
9575
      for new_lv in dev.children:
9576
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9577
                        _GetInstanceInfoText(self.instance), False)
9578

    
9579
    # Step 4: dbrd minors and drbd setups changes
9580
    # after this, we must manually remove the drbd minors on both the
9581
    # error and the success paths
9582
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9583
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9584
                                         for dev in self.instance.disks],
9585
                                        self.instance.name)
9586
    logging.debug("Allocated minors %r", minors)
9587

    
9588
    iv_names = {}
9589
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9590
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9591
                      (self.new_node, idx))
9592
      # create new devices on new_node; note that we create two IDs:
9593
      # one without port, so the drbd will be activated without
9594
      # networking information on the new node at this stage, and one
9595
      # with network, for the latter activation in step 4
9596
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9597
      if self.instance.primary_node == o_node1:
9598
        p_minor = o_minor1
9599
      else:
9600
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9601
        p_minor = o_minor2
9602

    
9603
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9604
                      p_minor, new_minor, o_secret)
9605
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9606
                    p_minor, new_minor, o_secret)
9607

    
9608
      iv_names[idx] = (dev, dev.children, new_net_id)
9609
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9610
                    new_net_id)
9611
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9612
                              logical_id=new_alone_id,
9613
                              children=dev.children,
9614
                              size=dev.size)
9615
      try:
9616
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9617
                              _GetInstanceInfoText(self.instance), False)
9618
      except errors.GenericError:
9619
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9620
        raise
9621

    
9622
    # We have new devices, shutdown the drbd on the old secondary
9623
    for idx, dev in enumerate(self.instance.disks):
9624
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9625
      self.cfg.SetDiskID(dev, self.target_node)
9626
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9627
      if msg:
9628
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9629
                           "node: %s" % (idx, msg),
9630
                           hint=("Please cleanup this device manually as"
9631
                                 " soon as possible"))
9632

    
9633
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9634
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9635
                                               self.node_secondary_ip,
9636
                                               self.instance.disks)\
9637
                                              [self.instance.primary_node]
9638

    
9639
    msg = result.fail_msg
9640
    if msg:
9641
      # detaches didn't succeed (unlikely)
9642
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9643
      raise errors.OpExecError("Can't detach the disks from the network on"
9644
                               " old node: %s" % (msg,))
9645

    
9646
    # if we managed to detach at least one, we update all the disks of
9647
    # the instance to point to the new secondary
9648
    self.lu.LogInfo("Updating instance configuration")
9649
    for dev, _, new_logical_id in iv_names.itervalues():
9650
      dev.logical_id = new_logical_id
9651
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9652

    
9653
    self.cfg.Update(self.instance, feedback_fn)
9654

    
9655
    # and now perform the drbd attach
9656
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9657
                    " (standalone => connected)")
9658
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9659
                                            self.new_node],
9660
                                           self.node_secondary_ip,
9661
                                           self.instance.disks,
9662
                                           self.instance.name,
9663
                                           False)
9664
    for to_node, to_result in result.items():
9665
      msg = to_result.fail_msg
9666
      if msg:
9667
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9668
                           to_node, msg,
9669
                           hint=("please do a gnt-instance info to see the"
9670
                                 " status of disks"))
9671
    cstep = 5
9672
    if self.early_release:
9673
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9674
      cstep += 1
9675
      self._RemoveOldStorage(self.target_node, iv_names)
9676
      # WARNING: we release all node locks here, do not do other RPCs
9677
      # than WaitForSync to the primary node
9678
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9679
                    names=[self.instance.primary_node,
9680
                           self.target_node,
9681
                           self.new_node])
9682

    
9683
    # Wait for sync
9684
    # This can fail as the old devices are degraded and _WaitForSync
9685
    # does a combined result over all disks, so we don't check its return value
9686
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9687
    cstep += 1
9688
    _WaitForSync(self.lu, self.instance)
9689

    
9690
    # Check all devices manually
9691
    self._CheckDevices(self.instance.primary_node, iv_names)
9692

    
9693
    # Step: remove old storage
9694
    if not self.early_release:
9695
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9696
      self._RemoveOldStorage(self.target_node, iv_names)
9697

    
9698

    
9699
class LURepairNodeStorage(NoHooksLU):
9700
  """Repairs the volume group on a node.
9701

9702
  """
9703
  REQ_BGL = False
9704

    
9705
  def CheckArguments(self):
9706
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9707

    
9708
    storage_type = self.op.storage_type
9709

    
9710
    if (constants.SO_FIX_CONSISTENCY not in
9711
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9712
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9713
                                 " repaired" % storage_type,
9714
                                 errors.ECODE_INVAL)
9715

    
9716
  def ExpandNames(self):
9717
    self.needed_locks = {
9718
      locking.LEVEL_NODE: [self.op.node_name],
9719
      }
9720

    
9721
  def _CheckFaultyDisks(self, instance, node_name):
9722
    """Ensure faulty disks abort the opcode or at least warn."""
9723
    try:
9724
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9725
                                  node_name, True):
9726
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9727
                                   " node '%s'" % (instance.name, node_name),
9728
                                   errors.ECODE_STATE)
9729
    except errors.OpPrereqError, err:
9730
      if self.op.ignore_consistency:
9731
        self.proc.LogWarning(str(err.args[0]))
9732
      else:
9733
        raise
9734

    
9735
  def CheckPrereq(self):
9736
    """Check prerequisites.
9737

9738
    """
9739
    # Check whether any instance on this node has faulty disks
9740
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9741
      if not inst.admin_up:
9742
        continue
9743
      check_nodes = set(inst.all_nodes)
9744
      check_nodes.discard(self.op.node_name)
9745
      for inst_node_name in check_nodes:
9746
        self._CheckFaultyDisks(inst, inst_node_name)
9747

    
9748
  def Exec(self, feedback_fn):
9749
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9750
                (self.op.name, self.op.node_name))
9751

    
9752
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9753
    result = self.rpc.call_storage_execute(self.op.node_name,
9754
                                           self.op.storage_type, st_args,
9755
                                           self.op.name,
9756
                                           constants.SO_FIX_CONSISTENCY)
9757
    result.Raise("Failed to repair storage unit '%s' on %s" %
9758
                 (self.op.name, self.op.node_name))
9759

    
9760

    
9761
class LUNodeEvacuate(NoHooksLU):
9762
  """Evacuates instances off a list of nodes.
9763

9764
  """
9765
  REQ_BGL = False
9766

    
9767
  def CheckArguments(self):
9768
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9769

    
9770
  def ExpandNames(self):
9771
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9772

    
9773
    if self.op.remote_node is not None:
9774
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9775
      assert self.op.remote_node
9776

    
9777
      if self.op.remote_node == self.op.node_name:
9778
        raise errors.OpPrereqError("Can not use evacuated node as a new"
9779
                                   " secondary node", errors.ECODE_INVAL)
9780

    
9781
      if self.op.mode != constants.IALLOCATOR_NEVAC_SEC:
9782
        raise errors.OpPrereqError("Without the use of an iallocator only"
9783
                                   " secondary instances can be evacuated",
9784
                                   errors.ECODE_INVAL)
9785

    
9786
    # Declare locks
9787
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9788
    self.needed_locks = {
9789
      locking.LEVEL_INSTANCE: [],
9790
      locking.LEVEL_NODEGROUP: [],
9791
      locking.LEVEL_NODE: [],
9792
      }
9793

    
9794
    if self.op.remote_node is None:
9795
      # Iallocator will choose any node(s) in the same group
9796
      group_nodes = self.cfg.GetNodeGroupMembersByNodes([self.op.node_name])
9797
    else:
9798
      group_nodes = frozenset([self.op.remote_node])
9799

    
9800
    # Determine nodes to be locked
9801
    self.lock_nodes = set([self.op.node_name]) | group_nodes
9802

    
9803
  def _DetermineInstances(self):
9804
    """Builds list of instances to operate on.
9805

9806
    """
9807
    assert self.op.mode in constants.IALLOCATOR_NEVAC_MODES
9808

    
9809
    if self.op.mode == constants.IALLOCATOR_NEVAC_PRI:
9810
      # Primary instances only
9811
      inst_fn = _GetNodePrimaryInstances
9812
      assert self.op.remote_node is None, \
9813
        "Evacuating primary instances requires iallocator"
9814
    elif self.op.mode == constants.IALLOCATOR_NEVAC_SEC:
9815
      # Secondary instances only
9816
      inst_fn = _GetNodeSecondaryInstances
9817
    else:
9818
      # All instances
9819
      assert self.op.mode == constants.IALLOCATOR_NEVAC_ALL
9820
      inst_fn = _GetNodeInstances
9821

    
9822
    return inst_fn(self.cfg, self.op.node_name)
9823

    
9824
  def DeclareLocks(self, level):
9825
    if level == locking.LEVEL_INSTANCE:
9826
      # Lock instances optimistically, needs verification once node and group
9827
      # locks have been acquired
9828
      self.needed_locks[locking.LEVEL_INSTANCE] = \
9829
        set(i.name for i in self._DetermineInstances())
9830

    
9831
    elif level == locking.LEVEL_NODEGROUP:
9832
      # Lock node groups optimistically, needs verification once nodes have
9833
      # been acquired
9834
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
9835
        self.cfg.GetNodeGroupsFromNodes(self.lock_nodes)
9836

    
9837
    elif level == locking.LEVEL_NODE:
9838
      self.needed_locks[locking.LEVEL_NODE] = self.lock_nodes
9839

    
9840
  def CheckPrereq(self):
9841
    # Verify locks
9842
    owned_instances = self.glm.list_owned(locking.LEVEL_INSTANCE)
9843
    owned_nodes = self.glm.list_owned(locking.LEVEL_NODE)
9844
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
9845

    
9846
    assert owned_nodes == self.lock_nodes
9847

    
9848
    wanted_groups = self.cfg.GetNodeGroupsFromNodes(owned_nodes)
9849
    if owned_groups != wanted_groups:
9850
      raise errors.OpExecError("Node groups changed since locks were acquired,"
9851
                               " current groups are '%s', used to be '%s'" %
9852
                               (utils.CommaJoin(wanted_groups),
9853
                                utils.CommaJoin(owned_groups)))
9854

    
9855
    # Determine affected instances
9856
    self.instances = self._DetermineInstances()
9857
    self.instance_names = [i.name for i in self.instances]
9858

    
9859
    if set(self.instance_names) != owned_instances:
9860
      raise errors.OpExecError("Instances on node '%s' changed since locks"
9861
                               " were acquired, current instances are '%s',"
9862
                               " used to be '%s'" %
9863
                               (self.op.node_name,
9864
                                utils.CommaJoin(self.instance_names),
9865
                                utils.CommaJoin(owned_instances)))
9866

    
9867
    if self.instance_names:
9868
      self.LogInfo("Evacuating instances from node '%s': %s",
9869
                   self.op.node_name,
9870
                   utils.CommaJoin(utils.NiceSort(self.instance_names)))
9871
    else:
9872
      self.LogInfo("No instances to evacuate from node '%s'",
9873
                   self.op.node_name)
9874

    
9875
    if self.op.remote_node is not None:
9876
      for i in self.instances:
9877
        if i.primary_node == self.op.remote_node:
9878
          raise errors.OpPrereqError("Node %s is the primary node of"
9879
                                     " instance %s, cannot use it as"
9880
                                     " secondary" %
9881
                                     (self.op.remote_node, i.name),
9882
                                     errors.ECODE_INVAL)
9883

    
9884
  def Exec(self, feedback_fn):
9885
    assert (self.op.iallocator is not None) ^ (self.op.remote_node is not None)
9886

    
9887
    if not self.instance_names:
9888
      # No instances to evacuate
9889
      jobs = []
9890

    
9891
    elif self.op.iallocator is not None:
9892
      # TODO: Implement relocation to other group
9893
      ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_NODE_EVAC,
9894
                       evac_mode=self.op.mode,
9895
                       instances=list(self.instance_names))
9896

    
9897
      ial.Run(self.op.iallocator)
9898

    
9899
      if not ial.success:
9900
        raise errors.OpPrereqError("Can't compute node evacuation using"
9901
                                   " iallocator '%s': %s" %
9902
                                   (self.op.iallocator, ial.info),
9903
                                   errors.ECODE_NORES)
9904

    
9905
      jobs = [[opcodes.OpCode.LoadOpCode(state) for state in jobset]
9906
              for jobset in ial.result]
9907

    
9908
      # Set "early_release" flag on opcodes where available
9909
      early_release = self.op.early_release
9910
      for op in itertools.chain(*jobs): # pylint: disable-msg=W0142
9911
        try:
9912
          op.early_release = early_release
9913
        except AttributeError:
9914
          assert not isinstance(op, opcodes.OpInstanceReplaceDisks)
9915

    
9916
    elif self.op.remote_node is not None:
9917
      assert self.op.mode == constants.IALLOCATOR_NEVAC_SEC
9918
      jobs = [
9919
        [opcodes.OpInstanceReplaceDisks(instance_name=instance_name,
9920
                                        remote_node=self.op.remote_node,
9921
                                        disks=[],
9922
                                        mode=constants.REPLACE_DISK_CHG,
9923
                                        early_release=self.op.early_release)]
9924
        for instance_name in self.instance_names
9925
        ]
9926

    
9927
    else:
9928
      raise errors.ProgrammerError("No iallocator or remote node")
9929

    
9930
    return ResultWithJobs(jobs)
9931

    
9932

    
9933
class LUInstanceGrowDisk(LogicalUnit):
9934
  """Grow a disk of an instance.
9935

9936
  """
9937
  HPATH = "disk-grow"
9938
  HTYPE = constants.HTYPE_INSTANCE
9939
  REQ_BGL = False
9940

    
9941
  def ExpandNames(self):
9942
    self._ExpandAndLockInstance()
9943
    self.needed_locks[locking.LEVEL_NODE] = []
9944
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9945

    
9946
  def DeclareLocks(self, level):
9947
    if level == locking.LEVEL_NODE:
9948
      self._LockInstancesNodes()
9949

    
9950
  def BuildHooksEnv(self):
9951
    """Build hooks env.
9952

9953
    This runs on the master, the primary and all the secondaries.
9954

9955
    """
9956
    env = {
9957
      "DISK": self.op.disk,
9958
      "AMOUNT": self.op.amount,
9959
      }
9960
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9961
    return env
9962

    
9963
  def BuildHooksNodes(self):
9964
    """Build hooks nodes.
9965

9966
    """
9967
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9968
    return (nl, nl)
9969

    
9970
  def CheckPrereq(self):
9971
    """Check prerequisites.
9972

9973
    This checks that the instance is in the cluster.
9974

9975
    """
9976
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9977
    assert instance is not None, \
9978
      "Cannot retrieve locked instance %s" % self.op.instance_name
9979
    nodenames = list(instance.all_nodes)
9980
    for node in nodenames:
9981
      _CheckNodeOnline(self, node)
9982

    
9983
    self.instance = instance
9984

    
9985
    if instance.disk_template not in constants.DTS_GROWABLE:
9986
      raise errors.OpPrereqError("Instance's disk layout does not support"
9987
                                 " growing", errors.ECODE_INVAL)
9988

    
9989
    self.disk = instance.FindDisk(self.op.disk)
9990

    
9991
    if instance.disk_template not in (constants.DT_FILE,
9992
                                      constants.DT_SHARED_FILE):
9993
      # TODO: check the free disk space for file, when that feature will be
9994
      # supported
9995
      _CheckNodesFreeDiskPerVG(self, nodenames,
9996
                               self.disk.ComputeGrowth(self.op.amount))
9997

    
9998
  def Exec(self, feedback_fn):
9999
    """Execute disk grow.
10000

10001
    """
10002
    instance = self.instance
10003
    disk = self.disk
10004

    
10005
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
10006
    if not disks_ok:
10007
      raise errors.OpExecError("Cannot activate block device to grow")
10008

    
10009
    # First run all grow ops in dry-run mode
10010
    for node in instance.all_nodes:
10011
      self.cfg.SetDiskID(disk, node)
10012
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
10013
      result.Raise("Grow request failed to node %s" % node)
10014

    
10015
    # We know that (as far as we can test) operations across different
10016
    # nodes will succeed, time to run it for real
10017
    for node in instance.all_nodes:
10018
      self.cfg.SetDiskID(disk, node)
10019
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
10020
      result.Raise("Grow request failed to node %s" % node)
10021

    
10022
      # TODO: Rewrite code to work properly
10023
      # DRBD goes into sync mode for a short amount of time after executing the
10024
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
10025
      # calling "resize" in sync mode fails. Sleeping for a short amount of
10026
      # time is a work-around.
10027
      time.sleep(5)
10028

    
10029
    disk.RecordGrow(self.op.amount)
10030
    self.cfg.Update(instance, feedback_fn)
10031
    if self.op.wait_for_sync:
10032
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
10033
      if disk_abort:
10034
        self.proc.LogWarning("Disk sync-ing has not returned a good"
10035
                             " status; please check the instance")
10036
      if not instance.admin_up:
10037
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
10038
    elif not instance.admin_up:
10039
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
10040
                           " not supposed to be running because no wait for"
10041
                           " sync mode was requested")
10042

    
10043

    
10044
class LUInstanceQueryData(NoHooksLU):
10045
  """Query runtime instance data.
10046

10047
  """
10048
  REQ_BGL = False
10049

    
10050
  def ExpandNames(self):
10051
    self.needed_locks = {}
10052

    
10053
    # Use locking if requested or when non-static information is wanted
10054
    if not (self.op.static or self.op.use_locking):
10055
      self.LogWarning("Non-static data requested, locks need to be acquired")
10056
      self.op.use_locking = True
10057

    
10058
    if self.op.instances or not self.op.use_locking:
10059
      # Expand instance names right here
10060
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
10061
    else:
10062
      # Will use acquired locks
10063
      self.wanted_names = None
10064

    
10065
    if self.op.use_locking:
10066
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10067

    
10068
      if self.wanted_names is None:
10069
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
10070
      else:
10071
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
10072

    
10073
      self.needed_locks[locking.LEVEL_NODE] = []
10074
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10075
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10076

    
10077
  def DeclareLocks(self, level):
10078
    if self.op.use_locking and level == locking.LEVEL_NODE:
10079
      self._LockInstancesNodes()
10080

    
10081
  def CheckPrereq(self):
10082
    """Check prerequisites.
10083

10084
    This only checks the optional instance list against the existing names.
10085

10086
    """
10087
    if self.wanted_names is None:
10088
      assert self.op.use_locking, "Locking was not used"
10089
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
10090

    
10091
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
10092
                             for name in self.wanted_names]
10093

    
10094
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
10095
    """Returns the status of a block device
10096

10097
    """
10098
    if self.op.static or not node:
10099
      return None
10100

    
10101
    self.cfg.SetDiskID(dev, node)
10102

    
10103
    result = self.rpc.call_blockdev_find(node, dev)
10104
    if result.offline:
10105
      return None
10106

    
10107
    result.Raise("Can't compute disk status for %s" % instance_name)
10108

    
10109
    status = result.payload
10110
    if status is None:
10111
      return None
10112

    
10113
    return (status.dev_path, status.major, status.minor,
10114
            status.sync_percent, status.estimated_time,
10115
            status.is_degraded, status.ldisk_status)
10116

    
10117
  def _ComputeDiskStatus(self, instance, snode, dev):
10118
    """Compute block device status.
10119

10120
    """
10121
    if dev.dev_type in constants.LDS_DRBD:
10122
      # we change the snode then (otherwise we use the one passed in)
10123
      if dev.logical_id[0] == instance.primary_node:
10124
        snode = dev.logical_id[1]
10125
      else:
10126
        snode = dev.logical_id[0]
10127

    
10128
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
10129
                                              instance.name, dev)
10130
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
10131

    
10132
    if dev.children:
10133
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
10134
                      for child in dev.children]
10135
    else:
10136
      dev_children = []
10137

    
10138
    return {
10139
      "iv_name": dev.iv_name,
10140
      "dev_type": dev.dev_type,
10141
      "logical_id": dev.logical_id,
10142
      "physical_id": dev.physical_id,
10143
      "pstatus": dev_pstatus,
10144
      "sstatus": dev_sstatus,
10145
      "children": dev_children,
10146
      "mode": dev.mode,
10147
      "size": dev.size,
10148
      }
10149

    
10150
  def Exec(self, feedback_fn):
10151
    """Gather and return data"""
10152
    result = {}
10153

    
10154
    cluster = self.cfg.GetClusterInfo()
10155

    
10156
    for instance in self.wanted_instances:
10157
      if not self.op.static:
10158
        remote_info = self.rpc.call_instance_info(instance.primary_node,
10159
                                                  instance.name,
10160
                                                  instance.hypervisor)
10161
        remote_info.Raise("Error checking node %s" % instance.primary_node)
10162
        remote_info = remote_info.payload
10163
        if remote_info and "state" in remote_info:
10164
          remote_state = "up"
10165
        else:
10166
          remote_state = "down"
10167
      else:
10168
        remote_state = None
10169
      if instance.admin_up:
10170
        config_state = "up"
10171
      else:
10172
        config_state = "down"
10173

    
10174
      disks = [self._ComputeDiskStatus(instance, None, device)
10175
               for device in instance.disks]
10176

    
10177
      result[instance.name] = {
10178
        "name": instance.name,
10179
        "config_state": config_state,
10180
        "run_state": remote_state,
10181
        "pnode": instance.primary_node,
10182
        "snodes": instance.secondary_nodes,
10183
        "os": instance.os,
10184
        # this happens to be the same format used for hooks
10185
        "nics": _NICListToTuple(self, instance.nics),
10186
        "disk_template": instance.disk_template,
10187
        "disks": disks,
10188
        "hypervisor": instance.hypervisor,
10189
        "network_port": instance.network_port,
10190
        "hv_instance": instance.hvparams,
10191
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
10192
        "be_instance": instance.beparams,
10193
        "be_actual": cluster.FillBE(instance),
10194
        "os_instance": instance.osparams,
10195
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
10196
        "serial_no": instance.serial_no,
10197
        "mtime": instance.mtime,
10198
        "ctime": instance.ctime,
10199
        "uuid": instance.uuid,
10200
        }
10201

    
10202
    return result
10203

    
10204

    
10205
class LUInstanceSetParams(LogicalUnit):
10206
  """Modifies an instances's parameters.
10207

10208
  """
10209
  HPATH = "instance-modify"
10210
  HTYPE = constants.HTYPE_INSTANCE
10211
  REQ_BGL = False
10212

    
10213
  def CheckArguments(self):
10214
    if not (self.op.nics or self.op.disks or self.op.disk_template or
10215
            self.op.hvparams or self.op.beparams or self.op.os_name):
10216
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
10217

    
10218
    if self.op.hvparams:
10219
      _CheckGlobalHvParams(self.op.hvparams)
10220

    
10221
    # Disk validation
10222
    disk_addremove = 0
10223
    for disk_op, disk_dict in self.op.disks:
10224
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
10225
      if disk_op == constants.DDM_REMOVE:
10226
        disk_addremove += 1
10227
        continue
10228
      elif disk_op == constants.DDM_ADD:
10229
        disk_addremove += 1
10230
      else:
10231
        if not isinstance(disk_op, int):
10232
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
10233
        if not isinstance(disk_dict, dict):
10234
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
10235
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10236

    
10237
      if disk_op == constants.DDM_ADD:
10238
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
10239
        if mode not in constants.DISK_ACCESS_SET:
10240
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
10241
                                     errors.ECODE_INVAL)
10242
        size = disk_dict.get(constants.IDISK_SIZE, None)
10243
        if size is None:
10244
          raise errors.OpPrereqError("Required disk parameter size missing",
10245
                                     errors.ECODE_INVAL)
10246
        try:
10247
          size = int(size)
10248
        except (TypeError, ValueError), err:
10249
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10250
                                     str(err), errors.ECODE_INVAL)
10251
        disk_dict[constants.IDISK_SIZE] = size
10252
      else:
10253
        # modification of disk
10254
        if constants.IDISK_SIZE in disk_dict:
10255
          raise errors.OpPrereqError("Disk size change not possible, use"
10256
                                     " grow-disk", errors.ECODE_INVAL)
10257

    
10258
    if disk_addremove > 1:
10259
      raise errors.OpPrereqError("Only one disk add or remove operation"
10260
                                 " supported at a time", errors.ECODE_INVAL)
10261

    
10262
    if self.op.disks and self.op.disk_template is not None:
10263
      raise errors.OpPrereqError("Disk template conversion and other disk"
10264
                                 " changes not supported at the same time",
10265
                                 errors.ECODE_INVAL)
10266

    
10267
    if (self.op.disk_template and
10268
        self.op.disk_template in constants.DTS_INT_MIRROR and
10269
        self.op.remote_node is None):
10270
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
10271
                                 " one requires specifying a secondary node",
10272
                                 errors.ECODE_INVAL)
10273

    
10274
    # NIC validation
10275
    nic_addremove = 0
10276
    for nic_op, nic_dict in self.op.nics:
10277
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10278
      if nic_op == constants.DDM_REMOVE:
10279
        nic_addremove += 1
10280
        continue
10281
      elif nic_op == constants.DDM_ADD:
10282
        nic_addremove += 1
10283
      else:
10284
        if not isinstance(nic_op, int):
10285
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10286
        if not isinstance(nic_dict, dict):
10287
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10288
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10289

    
10290
      # nic_dict should be a dict
10291
      nic_ip = nic_dict.get(constants.INIC_IP, None)
10292
      if nic_ip is not None:
10293
        if nic_ip.lower() == constants.VALUE_NONE:
10294
          nic_dict[constants.INIC_IP] = None
10295
        else:
10296
          if not netutils.IPAddress.IsValid(nic_ip):
10297
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10298
                                       errors.ECODE_INVAL)
10299

    
10300
      nic_bridge = nic_dict.get('bridge', None)
10301
      nic_link = nic_dict.get(constants.INIC_LINK, None)
10302
      if nic_bridge and nic_link:
10303
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10304
                                   " at the same time", errors.ECODE_INVAL)
10305
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10306
        nic_dict['bridge'] = None
10307
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10308
        nic_dict[constants.INIC_LINK] = None
10309

    
10310
      if nic_op == constants.DDM_ADD:
10311
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
10312
        if nic_mac is None:
10313
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10314

    
10315
      if constants.INIC_MAC in nic_dict:
10316
        nic_mac = nic_dict[constants.INIC_MAC]
10317
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10318
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10319

    
10320
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10321
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10322
                                     " modifying an existing nic",
10323
                                     errors.ECODE_INVAL)
10324

    
10325
    if nic_addremove > 1:
10326
      raise errors.OpPrereqError("Only one NIC add or remove operation"
10327
                                 " supported at a time", errors.ECODE_INVAL)
10328

    
10329
  def ExpandNames(self):
10330
    self._ExpandAndLockInstance()
10331
    self.needed_locks[locking.LEVEL_NODE] = []
10332
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10333

    
10334
  def DeclareLocks(self, level):
10335
    if level == locking.LEVEL_NODE:
10336
      self._LockInstancesNodes()
10337
      if self.op.disk_template and self.op.remote_node:
10338
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10339
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10340

    
10341
  def BuildHooksEnv(self):
10342
    """Build hooks env.
10343

10344
    This runs on the master, primary and secondaries.
10345

10346
    """
10347
    args = dict()
10348
    if constants.BE_MEMORY in self.be_new:
10349
      args['memory'] = self.be_new[constants.BE_MEMORY]
10350
    if constants.BE_VCPUS in self.be_new:
10351
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
10352
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10353
    # information at all.
10354
    if self.op.nics:
10355
      args['nics'] = []
10356
      nic_override = dict(self.op.nics)
10357
      for idx, nic in enumerate(self.instance.nics):
10358
        if idx in nic_override:
10359
          this_nic_override = nic_override[idx]
10360
        else:
10361
          this_nic_override = {}
10362
        if constants.INIC_IP in this_nic_override:
10363
          ip = this_nic_override[constants.INIC_IP]
10364
        else:
10365
          ip = nic.ip
10366
        if constants.INIC_MAC in this_nic_override:
10367
          mac = this_nic_override[constants.INIC_MAC]
10368
        else:
10369
          mac = nic.mac
10370
        if idx in self.nic_pnew:
10371
          nicparams = self.nic_pnew[idx]
10372
        else:
10373
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10374
        mode = nicparams[constants.NIC_MODE]
10375
        link = nicparams[constants.NIC_LINK]
10376
        args['nics'].append((ip, mac, mode, link))
10377
      if constants.DDM_ADD in nic_override:
10378
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10379
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10380
        nicparams = self.nic_pnew[constants.DDM_ADD]
10381
        mode = nicparams[constants.NIC_MODE]
10382
        link = nicparams[constants.NIC_LINK]
10383
        args['nics'].append((ip, mac, mode, link))
10384
      elif constants.DDM_REMOVE in nic_override:
10385
        del args['nics'][-1]
10386

    
10387
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10388
    if self.op.disk_template:
10389
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10390

    
10391
    return env
10392

    
10393
  def BuildHooksNodes(self):
10394
    """Build hooks nodes.
10395

10396
    """
10397
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10398
    return (nl, nl)
10399

    
10400
  def CheckPrereq(self):
10401
    """Check prerequisites.
10402

10403
    This only checks the instance list against the existing names.
10404

10405
    """
10406
    # checking the new params on the primary/secondary nodes
10407

    
10408
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10409
    cluster = self.cluster = self.cfg.GetClusterInfo()
10410
    assert self.instance is not None, \
10411
      "Cannot retrieve locked instance %s" % self.op.instance_name
10412
    pnode = instance.primary_node
10413
    nodelist = list(instance.all_nodes)
10414

    
10415
    # OS change
10416
    if self.op.os_name and not self.op.force:
10417
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10418
                      self.op.force_variant)
10419
      instance_os = self.op.os_name
10420
    else:
10421
      instance_os = instance.os
10422

    
10423
    if self.op.disk_template:
10424
      if instance.disk_template == self.op.disk_template:
10425
        raise errors.OpPrereqError("Instance already has disk template %s" %
10426
                                   instance.disk_template, errors.ECODE_INVAL)
10427

    
10428
      if (instance.disk_template,
10429
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10430
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10431
                                   " %s to %s" % (instance.disk_template,
10432
                                                  self.op.disk_template),
10433
                                   errors.ECODE_INVAL)
10434
      _CheckInstanceDown(self, instance, "cannot change disk template")
10435
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10436
        if self.op.remote_node == pnode:
10437
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10438
                                     " as the primary node of the instance" %
10439
                                     self.op.remote_node, errors.ECODE_STATE)
10440
        _CheckNodeOnline(self, self.op.remote_node)
10441
        _CheckNodeNotDrained(self, self.op.remote_node)
10442
        # FIXME: here we assume that the old instance type is DT_PLAIN
10443
        assert instance.disk_template == constants.DT_PLAIN
10444
        disks = [{constants.IDISK_SIZE: d.size,
10445
                  constants.IDISK_VG: d.logical_id[0]}
10446
                 for d in instance.disks]
10447
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10448
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10449

    
10450
    # hvparams processing
10451
    if self.op.hvparams:
10452
      hv_type = instance.hypervisor
10453
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10454
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10455
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10456

    
10457
      # local check
10458
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10459
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10460
      self.hv_new = hv_new # the new actual values
10461
      self.hv_inst = i_hvdict # the new dict (without defaults)
10462
    else:
10463
      self.hv_new = self.hv_inst = {}
10464

    
10465
    # beparams processing
10466
    if self.op.beparams:
10467
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10468
                                   use_none=True)
10469
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10470
      be_new = cluster.SimpleFillBE(i_bedict)
10471
      self.be_new = be_new # the new actual values
10472
      self.be_inst = i_bedict # the new dict (without defaults)
10473
    else:
10474
      self.be_new = self.be_inst = {}
10475
    be_old = cluster.FillBE(instance)
10476

    
10477
    # osparams processing
10478
    if self.op.osparams:
10479
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10480
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10481
      self.os_inst = i_osdict # the new dict (without defaults)
10482
    else:
10483
      self.os_inst = {}
10484

    
10485
    self.warn = []
10486

    
10487
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10488
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10489
      mem_check_list = [pnode]
10490
      if be_new[constants.BE_AUTO_BALANCE]:
10491
        # either we changed auto_balance to yes or it was from before
10492
        mem_check_list.extend(instance.secondary_nodes)
10493
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10494
                                                  instance.hypervisor)
10495
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10496
                                         instance.hypervisor)
10497
      pninfo = nodeinfo[pnode]
10498
      msg = pninfo.fail_msg
10499
      if msg:
10500
        # Assume the primary node is unreachable and go ahead
10501
        self.warn.append("Can't get info from primary node %s: %s" %
10502
                         (pnode,  msg))
10503
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10504
        self.warn.append("Node data from primary node %s doesn't contain"
10505
                         " free memory information" % pnode)
10506
      elif instance_info.fail_msg:
10507
        self.warn.append("Can't get instance runtime information: %s" %
10508
                        instance_info.fail_msg)
10509
      else:
10510
        if instance_info.payload:
10511
          current_mem = int(instance_info.payload['memory'])
10512
        else:
10513
          # Assume instance not running
10514
          # (there is a slight race condition here, but it's not very probable,
10515
          # and we have no other way to check)
10516
          current_mem = 0
10517
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10518
                    pninfo.payload['memory_free'])
10519
        if miss_mem > 0:
10520
          raise errors.OpPrereqError("This change will prevent the instance"
10521
                                     " from starting, due to %d MB of memory"
10522
                                     " missing on its primary node" % miss_mem,
10523
                                     errors.ECODE_NORES)
10524

    
10525
      if be_new[constants.BE_AUTO_BALANCE]:
10526
        for node, nres in nodeinfo.items():
10527
          if node not in instance.secondary_nodes:
10528
            continue
10529
          nres.Raise("Can't get info from secondary node %s" % node,
10530
                     prereq=True, ecode=errors.ECODE_STATE)
10531
          if not isinstance(nres.payload.get('memory_free', None), int):
10532
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10533
                                       " memory information" % node,
10534
                                       errors.ECODE_STATE)
10535
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10536
            raise errors.OpPrereqError("This change will prevent the instance"
10537
                                       " from failover to its secondary node"
10538
                                       " %s, due to not enough memory" % node,
10539
                                       errors.ECODE_STATE)
10540

    
10541
    # NIC processing
10542
    self.nic_pnew = {}
10543
    self.nic_pinst = {}
10544
    for nic_op, nic_dict in self.op.nics:
10545
      if nic_op == constants.DDM_REMOVE:
10546
        if not instance.nics:
10547
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10548
                                     errors.ECODE_INVAL)
10549
        continue
10550
      if nic_op != constants.DDM_ADD:
10551
        # an existing nic
10552
        if not instance.nics:
10553
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10554
                                     " no NICs" % nic_op,
10555
                                     errors.ECODE_INVAL)
10556
        if nic_op < 0 or nic_op >= len(instance.nics):
10557
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10558
                                     " are 0 to %d" %
10559
                                     (nic_op, len(instance.nics) - 1),
10560
                                     errors.ECODE_INVAL)
10561
        old_nic_params = instance.nics[nic_op].nicparams
10562
        old_nic_ip = instance.nics[nic_op].ip
10563
      else:
10564
        old_nic_params = {}
10565
        old_nic_ip = None
10566

    
10567
      update_params_dict = dict([(key, nic_dict[key])
10568
                                 for key in constants.NICS_PARAMETERS
10569
                                 if key in nic_dict])
10570

    
10571
      if 'bridge' in nic_dict:
10572
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10573

    
10574
      new_nic_params = _GetUpdatedParams(old_nic_params,
10575
                                         update_params_dict)
10576
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10577
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10578
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10579
      self.nic_pinst[nic_op] = new_nic_params
10580
      self.nic_pnew[nic_op] = new_filled_nic_params
10581
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10582

    
10583
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10584
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10585
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10586
        if msg:
10587
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10588
          if self.op.force:
10589
            self.warn.append(msg)
10590
          else:
10591
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10592
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10593
        if constants.INIC_IP in nic_dict:
10594
          nic_ip = nic_dict[constants.INIC_IP]
10595
        else:
10596
          nic_ip = old_nic_ip
10597
        if nic_ip is None:
10598
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10599
                                     ' on a routed nic', errors.ECODE_INVAL)
10600
      if constants.INIC_MAC in nic_dict:
10601
        nic_mac = nic_dict[constants.INIC_MAC]
10602
        if nic_mac is None:
10603
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10604
                                     errors.ECODE_INVAL)
10605
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10606
          # otherwise generate the mac
10607
          nic_dict[constants.INIC_MAC] = \
10608
            self.cfg.GenerateMAC(self.proc.GetECId())
10609
        else:
10610
          # or validate/reserve the current one
10611
          try:
10612
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10613
          except errors.ReservationError:
10614
            raise errors.OpPrereqError("MAC address %s already in use"
10615
                                       " in cluster" % nic_mac,
10616
                                       errors.ECODE_NOTUNIQUE)
10617

    
10618
    # DISK processing
10619
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10620
      raise errors.OpPrereqError("Disk operations not supported for"
10621
                                 " diskless instances",
10622
                                 errors.ECODE_INVAL)
10623
    for disk_op, _ in self.op.disks:
10624
      if disk_op == constants.DDM_REMOVE:
10625
        if len(instance.disks) == 1:
10626
          raise errors.OpPrereqError("Cannot remove the last disk of"
10627
                                     " an instance", errors.ECODE_INVAL)
10628
        _CheckInstanceDown(self, instance, "cannot remove disks")
10629

    
10630
      if (disk_op == constants.DDM_ADD and
10631
          len(instance.disks) >= constants.MAX_DISKS):
10632
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10633
                                   " add more" % constants.MAX_DISKS,
10634
                                   errors.ECODE_STATE)
10635
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10636
        # an existing disk
10637
        if disk_op < 0 or disk_op >= len(instance.disks):
10638
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10639
                                     " are 0 to %d" %
10640
                                     (disk_op, len(instance.disks)),
10641
                                     errors.ECODE_INVAL)
10642

    
10643
    return
10644

    
10645
  def _ConvertPlainToDrbd(self, feedback_fn):
10646
    """Converts an instance from plain to drbd.
10647

10648
    """
10649
    feedback_fn("Converting template to drbd")
10650
    instance = self.instance
10651
    pnode = instance.primary_node
10652
    snode = self.op.remote_node
10653

    
10654
    # create a fake disk info for _GenerateDiskTemplate
10655
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10656
                  constants.IDISK_VG: d.logical_id[0]}
10657
                 for d in instance.disks]
10658
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10659
                                      instance.name, pnode, [snode],
10660
                                      disk_info, None, None, 0, feedback_fn)
10661
    info = _GetInstanceInfoText(instance)
10662
    feedback_fn("Creating aditional volumes...")
10663
    # first, create the missing data and meta devices
10664
    for disk in new_disks:
10665
      # unfortunately this is... not too nice
10666
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10667
                            info, True)
10668
      for child in disk.children:
10669
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10670
    # at this stage, all new LVs have been created, we can rename the
10671
    # old ones
10672
    feedback_fn("Renaming original volumes...")
10673
    rename_list = [(o, n.children[0].logical_id)
10674
                   for (o, n) in zip(instance.disks, new_disks)]
10675
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10676
    result.Raise("Failed to rename original LVs")
10677

    
10678
    feedback_fn("Initializing DRBD devices...")
10679
    # all child devices are in place, we can now create the DRBD devices
10680
    for disk in new_disks:
10681
      for node in [pnode, snode]:
10682
        f_create = node == pnode
10683
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10684

    
10685
    # at this point, the instance has been modified
10686
    instance.disk_template = constants.DT_DRBD8
10687
    instance.disks = new_disks
10688
    self.cfg.Update(instance, feedback_fn)
10689

    
10690
    # disks are created, waiting for sync
10691
    disk_abort = not _WaitForSync(self, instance,
10692
                                  oneshot=not self.op.wait_for_sync)
10693
    if disk_abort:
10694
      raise errors.OpExecError("There are some degraded disks for"
10695
                               " this instance, please cleanup manually")
10696

    
10697
  def _ConvertDrbdToPlain(self, feedback_fn):
10698
    """Converts an instance from drbd to plain.
10699

10700
    """
10701
    instance = self.instance
10702
    assert len(instance.secondary_nodes) == 1
10703
    pnode = instance.primary_node
10704
    snode = instance.secondary_nodes[0]
10705
    feedback_fn("Converting template to plain")
10706

    
10707
    old_disks = instance.disks
10708
    new_disks = [d.children[0] for d in old_disks]
10709

    
10710
    # copy over size and mode
10711
    for parent, child in zip(old_disks, new_disks):
10712
      child.size = parent.size
10713
      child.mode = parent.mode
10714

    
10715
    # update instance structure
10716
    instance.disks = new_disks
10717
    instance.disk_template = constants.DT_PLAIN
10718
    self.cfg.Update(instance, feedback_fn)
10719

    
10720
    feedback_fn("Removing volumes on the secondary node...")
10721
    for disk in old_disks:
10722
      self.cfg.SetDiskID(disk, snode)
10723
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10724
      if msg:
10725
        self.LogWarning("Could not remove block device %s on node %s,"
10726
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10727

    
10728
    feedback_fn("Removing unneeded volumes on the primary node...")
10729
    for idx, disk in enumerate(old_disks):
10730
      meta = disk.children[1]
10731
      self.cfg.SetDiskID(meta, pnode)
10732
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10733
      if msg:
10734
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10735
                        " continuing anyway: %s", idx, pnode, msg)
10736

    
10737
  def Exec(self, feedback_fn):
10738
    """Modifies an instance.
10739

10740
    All parameters take effect only at the next restart of the instance.
10741

10742
    """
10743
    # Process here the warnings from CheckPrereq, as we don't have a
10744
    # feedback_fn there.
10745
    for warn in self.warn:
10746
      feedback_fn("WARNING: %s" % warn)
10747

    
10748
    result = []
10749
    instance = self.instance
10750
    # disk changes
10751
    for disk_op, disk_dict in self.op.disks:
10752
      if disk_op == constants.DDM_REMOVE:
10753
        # remove the last disk
10754
        device = instance.disks.pop()
10755
        device_idx = len(instance.disks)
10756
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10757
          self.cfg.SetDiskID(disk, node)
10758
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10759
          if msg:
10760
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10761
                            " continuing anyway", device_idx, node, msg)
10762
        result.append(("disk/%d" % device_idx, "remove"))
10763
      elif disk_op == constants.DDM_ADD:
10764
        # add a new disk
10765
        if instance.disk_template in (constants.DT_FILE,
10766
                                        constants.DT_SHARED_FILE):
10767
          file_driver, file_path = instance.disks[0].logical_id
10768
          file_path = os.path.dirname(file_path)
10769
        else:
10770
          file_driver = file_path = None
10771
        disk_idx_base = len(instance.disks)
10772
        new_disk = _GenerateDiskTemplate(self,
10773
                                         instance.disk_template,
10774
                                         instance.name, instance.primary_node,
10775
                                         instance.secondary_nodes,
10776
                                         [disk_dict],
10777
                                         file_path,
10778
                                         file_driver,
10779
                                         disk_idx_base, feedback_fn)[0]
10780
        instance.disks.append(new_disk)
10781
        info = _GetInstanceInfoText(instance)
10782

    
10783
        logging.info("Creating volume %s for instance %s",
10784
                     new_disk.iv_name, instance.name)
10785
        # Note: this needs to be kept in sync with _CreateDisks
10786
        #HARDCODE
10787
        for node in instance.all_nodes:
10788
          f_create = node == instance.primary_node
10789
          try:
10790
            _CreateBlockDev(self, node, instance, new_disk,
10791
                            f_create, info, f_create)
10792
          except errors.OpExecError, err:
10793
            self.LogWarning("Failed to create volume %s (%s) on"
10794
                            " node %s: %s",
10795
                            new_disk.iv_name, new_disk, node, err)
10796
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10797
                       (new_disk.size, new_disk.mode)))
10798
      else:
10799
        # change a given disk
10800
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10801
        result.append(("disk.mode/%d" % disk_op,
10802
                       disk_dict[constants.IDISK_MODE]))
10803

    
10804
    if self.op.disk_template:
10805
      r_shut = _ShutdownInstanceDisks(self, instance)
10806
      if not r_shut:
10807
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10808
                                 " proceed with disk template conversion")
10809
      mode = (instance.disk_template, self.op.disk_template)
10810
      try:
10811
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10812
      except:
10813
        self.cfg.ReleaseDRBDMinors(instance.name)
10814
        raise
10815
      result.append(("disk_template", self.op.disk_template))
10816

    
10817
    # NIC changes
10818
    for nic_op, nic_dict in self.op.nics:
10819
      if nic_op == constants.DDM_REMOVE:
10820
        # remove the last nic
10821
        del instance.nics[-1]
10822
        result.append(("nic.%d" % len(instance.nics), "remove"))
10823
      elif nic_op == constants.DDM_ADD:
10824
        # mac and bridge should be set, by now
10825
        mac = nic_dict[constants.INIC_MAC]
10826
        ip = nic_dict.get(constants.INIC_IP, None)
10827
        nicparams = self.nic_pinst[constants.DDM_ADD]
10828
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10829
        instance.nics.append(new_nic)
10830
        result.append(("nic.%d" % (len(instance.nics) - 1),
10831
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10832
                       (new_nic.mac, new_nic.ip,
10833
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10834
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10835
                       )))
10836
      else:
10837
        for key in (constants.INIC_MAC, constants.INIC_IP):
10838
          if key in nic_dict:
10839
            setattr(instance.nics[nic_op], key, nic_dict[key])
10840
        if nic_op in self.nic_pinst:
10841
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10842
        for key, val in nic_dict.iteritems():
10843
          result.append(("nic.%s/%d" % (key, nic_op), val))
10844

    
10845
    # hvparams changes
10846
    if self.op.hvparams:
10847
      instance.hvparams = self.hv_inst
10848
      for key, val in self.op.hvparams.iteritems():
10849
        result.append(("hv/%s" % key, val))
10850

    
10851
    # beparams changes
10852
    if self.op.beparams:
10853
      instance.beparams = self.be_inst
10854
      for key, val in self.op.beparams.iteritems():
10855
        result.append(("be/%s" % key, val))
10856

    
10857
    # OS change
10858
    if self.op.os_name:
10859
      instance.os = self.op.os_name
10860

    
10861
    # osparams changes
10862
    if self.op.osparams:
10863
      instance.osparams = self.os_inst
10864
      for key, val in self.op.osparams.iteritems():
10865
        result.append(("os/%s" % key, val))
10866

    
10867
    self.cfg.Update(instance, feedback_fn)
10868

    
10869
    return result
10870

    
10871
  _DISK_CONVERSIONS = {
10872
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10873
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10874
    }
10875

    
10876

    
10877
class LUBackupQuery(NoHooksLU):
10878
  """Query the exports list
10879

10880
  """
10881
  REQ_BGL = False
10882

    
10883
  def ExpandNames(self):
10884
    self.needed_locks = {}
10885
    self.share_locks[locking.LEVEL_NODE] = 1
10886
    if not self.op.nodes:
10887
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10888
    else:
10889
      self.needed_locks[locking.LEVEL_NODE] = \
10890
        _GetWantedNodes(self, self.op.nodes)
10891

    
10892
  def Exec(self, feedback_fn):
10893
    """Compute the list of all the exported system images.
10894

10895
    @rtype: dict
10896
    @return: a dictionary with the structure node->(export-list)
10897
        where export-list is a list of the instances exported on
10898
        that node.
10899

10900
    """
10901
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10902
    rpcresult = self.rpc.call_export_list(self.nodes)
10903
    result = {}
10904
    for node in rpcresult:
10905
      if rpcresult[node].fail_msg:
10906
        result[node] = False
10907
      else:
10908
        result[node] = rpcresult[node].payload
10909

    
10910
    return result
10911

    
10912

    
10913
class LUBackupPrepare(NoHooksLU):
10914
  """Prepares an instance for an export and returns useful information.
10915

10916
  """
10917
  REQ_BGL = False
10918

    
10919
  def ExpandNames(self):
10920
    self._ExpandAndLockInstance()
10921

    
10922
  def CheckPrereq(self):
10923
    """Check prerequisites.
10924

10925
    """
10926
    instance_name = self.op.instance_name
10927

    
10928
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10929
    assert self.instance is not None, \
10930
          "Cannot retrieve locked instance %s" % self.op.instance_name
10931
    _CheckNodeOnline(self, self.instance.primary_node)
10932

    
10933
    self._cds = _GetClusterDomainSecret()
10934

    
10935
  def Exec(self, feedback_fn):
10936
    """Prepares an instance for an export.
10937

10938
    """
10939
    instance = self.instance
10940

    
10941
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10942
      salt = utils.GenerateSecret(8)
10943

    
10944
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10945
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10946
                                              constants.RIE_CERT_VALIDITY)
10947
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10948

    
10949
      (name, cert_pem) = result.payload
10950

    
10951
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10952
                                             cert_pem)
10953

    
10954
      return {
10955
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10956
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10957
                          salt),
10958
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10959
        }
10960

    
10961
    return None
10962

    
10963

    
10964
class LUBackupExport(LogicalUnit):
10965
  """Export an instance to an image in the cluster.
10966

10967
  """
10968
  HPATH = "instance-export"
10969
  HTYPE = constants.HTYPE_INSTANCE
10970
  REQ_BGL = False
10971

    
10972
  def CheckArguments(self):
10973
    """Check the arguments.
10974

10975
    """
10976
    self.x509_key_name = self.op.x509_key_name
10977
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10978

    
10979
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10980
      if not self.x509_key_name:
10981
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10982
                                   errors.ECODE_INVAL)
10983

    
10984
      if not self.dest_x509_ca_pem:
10985
        raise errors.OpPrereqError("Missing destination X509 CA",
10986
                                   errors.ECODE_INVAL)
10987

    
10988
  def ExpandNames(self):
10989
    self._ExpandAndLockInstance()
10990

    
10991
    # Lock all nodes for local exports
10992
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10993
      # FIXME: lock only instance primary and destination node
10994
      #
10995
      # Sad but true, for now we have do lock all nodes, as we don't know where
10996
      # the previous export might be, and in this LU we search for it and
10997
      # remove it from its current node. In the future we could fix this by:
10998
      #  - making a tasklet to search (share-lock all), then create the
10999
      #    new one, then one to remove, after
11000
      #  - removing the removal operation altogether
11001
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11002

    
11003
  def DeclareLocks(self, level):
11004
    """Last minute lock declaration."""
11005
    # All nodes are locked anyway, so nothing to do here.
11006

    
11007
  def BuildHooksEnv(self):
11008
    """Build hooks env.
11009

11010
    This will run on the master, primary node and target node.
11011

11012
    """
11013
    env = {
11014
      "EXPORT_MODE": self.op.mode,
11015
      "EXPORT_NODE": self.op.target_node,
11016
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
11017
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
11018
      # TODO: Generic function for boolean env variables
11019
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
11020
      }
11021

    
11022
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
11023

    
11024
    return env
11025

    
11026
  def BuildHooksNodes(self):
11027
    """Build hooks nodes.
11028

11029
    """
11030
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
11031

    
11032
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11033
      nl.append(self.op.target_node)
11034

    
11035
    return (nl, nl)
11036

    
11037
  def CheckPrereq(self):
11038
    """Check prerequisites.
11039

11040
    This checks that the instance and node names are valid.
11041

11042
    """
11043
    instance_name = self.op.instance_name
11044

    
11045
    self.instance = self.cfg.GetInstanceInfo(instance_name)
11046
    assert self.instance is not None, \
11047
          "Cannot retrieve locked instance %s" % self.op.instance_name
11048
    _CheckNodeOnline(self, self.instance.primary_node)
11049

    
11050
    if (self.op.remove_instance and self.instance.admin_up and
11051
        not self.op.shutdown):
11052
      raise errors.OpPrereqError("Can not remove instance without shutting it"
11053
                                 " down before")
11054

    
11055
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11056
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
11057
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
11058
      assert self.dst_node is not None
11059

    
11060
      _CheckNodeOnline(self, self.dst_node.name)
11061
      _CheckNodeNotDrained(self, self.dst_node.name)
11062

    
11063
      self._cds = None
11064
      self.dest_disk_info = None
11065
      self.dest_x509_ca = None
11066

    
11067
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11068
      self.dst_node = None
11069

    
11070
      if len(self.op.target_node) != len(self.instance.disks):
11071
        raise errors.OpPrereqError(("Received destination information for %s"
11072
                                    " disks, but instance %s has %s disks") %
11073
                                   (len(self.op.target_node), instance_name,
11074
                                    len(self.instance.disks)),
11075
                                   errors.ECODE_INVAL)
11076

    
11077
      cds = _GetClusterDomainSecret()
11078

    
11079
      # Check X509 key name
11080
      try:
11081
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
11082
      except (TypeError, ValueError), err:
11083
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
11084

    
11085
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
11086
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
11087
                                   errors.ECODE_INVAL)
11088

    
11089
      # Load and verify CA
11090
      try:
11091
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
11092
      except OpenSSL.crypto.Error, err:
11093
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
11094
                                   (err, ), errors.ECODE_INVAL)
11095

    
11096
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
11097
      if errcode is not None:
11098
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
11099
                                   (msg, ), errors.ECODE_INVAL)
11100

    
11101
      self.dest_x509_ca = cert
11102

    
11103
      # Verify target information
11104
      disk_info = []
11105
      for idx, disk_data in enumerate(self.op.target_node):
11106
        try:
11107
          (host, port, magic) = \
11108
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
11109
        except errors.GenericError, err:
11110
          raise errors.OpPrereqError("Target info for disk %s: %s" %
11111
                                     (idx, err), errors.ECODE_INVAL)
11112

    
11113
        disk_info.append((host, port, magic))
11114

    
11115
      assert len(disk_info) == len(self.op.target_node)
11116
      self.dest_disk_info = disk_info
11117

    
11118
    else:
11119
      raise errors.ProgrammerError("Unhandled export mode %r" %
11120
                                   self.op.mode)
11121

    
11122
    # instance disk type verification
11123
    # TODO: Implement export support for file-based disks
11124
    for disk in self.instance.disks:
11125
      if disk.dev_type == constants.LD_FILE:
11126
        raise errors.OpPrereqError("Export not supported for instances with"
11127
                                   " file-based disks", errors.ECODE_INVAL)
11128

    
11129
  def _CleanupExports(self, feedback_fn):
11130
    """Removes exports of current instance from all other nodes.
11131

11132
    If an instance in a cluster with nodes A..D was exported to node C, its
11133
    exports will be removed from the nodes A, B and D.
11134

11135
    """
11136
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
11137

    
11138
    nodelist = self.cfg.GetNodeList()
11139
    nodelist.remove(self.dst_node.name)
11140

    
11141
    # on one-node clusters nodelist will be empty after the removal
11142
    # if we proceed the backup would be removed because OpBackupQuery
11143
    # substitutes an empty list with the full cluster node list.
11144
    iname = self.instance.name
11145
    if nodelist:
11146
      feedback_fn("Removing old exports for instance %s" % iname)
11147
      exportlist = self.rpc.call_export_list(nodelist)
11148
      for node in exportlist:
11149
        if exportlist[node].fail_msg:
11150
          continue
11151
        if iname in exportlist[node].payload:
11152
          msg = self.rpc.call_export_remove(node, iname).fail_msg
11153
          if msg:
11154
            self.LogWarning("Could not remove older export for instance %s"
11155
                            " on node %s: %s", iname, node, msg)
11156

    
11157
  def Exec(self, feedback_fn):
11158
    """Export an instance to an image in the cluster.
11159

11160
    """
11161
    assert self.op.mode in constants.EXPORT_MODES
11162

    
11163
    instance = self.instance
11164
    src_node = instance.primary_node
11165

    
11166
    if self.op.shutdown:
11167
      # shutdown the instance, but not the disks
11168
      feedback_fn("Shutting down instance %s" % instance.name)
11169
      result = self.rpc.call_instance_shutdown(src_node, instance,
11170
                                               self.op.shutdown_timeout)
11171
      # TODO: Maybe ignore failures if ignore_remove_failures is set
11172
      result.Raise("Could not shutdown instance %s on"
11173
                   " node %s" % (instance.name, src_node))
11174

    
11175
    # set the disks ID correctly since call_instance_start needs the
11176
    # correct drbd minor to create the symlinks
11177
    for disk in instance.disks:
11178
      self.cfg.SetDiskID(disk, src_node)
11179

    
11180
    activate_disks = (not instance.admin_up)
11181

    
11182
    if activate_disks:
11183
      # Activate the instance disks if we'exporting a stopped instance
11184
      feedback_fn("Activating disks for %s" % instance.name)
11185
      _StartInstanceDisks(self, instance, None)
11186

    
11187
    try:
11188
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
11189
                                                     instance)
11190

    
11191
      helper.CreateSnapshots()
11192
      try:
11193
        if (self.op.shutdown and instance.admin_up and
11194
            not self.op.remove_instance):
11195
          assert not activate_disks
11196
          feedback_fn("Starting instance %s" % instance.name)
11197
          result = self.rpc.call_instance_start(src_node, instance,
11198
                                                None, None, False)
11199
          msg = result.fail_msg
11200
          if msg:
11201
            feedback_fn("Failed to start instance: %s" % msg)
11202
            _ShutdownInstanceDisks(self, instance)
11203
            raise errors.OpExecError("Could not start instance: %s" % msg)
11204

    
11205
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
11206
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
11207
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11208
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
11209
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
11210

    
11211
          (key_name, _, _) = self.x509_key_name
11212

    
11213
          dest_ca_pem = \
11214
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
11215
                                            self.dest_x509_ca)
11216

    
11217
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
11218
                                                     key_name, dest_ca_pem,
11219
                                                     timeouts)
11220
      finally:
11221
        helper.Cleanup()
11222

    
11223
      # Check for backwards compatibility
11224
      assert len(dresults) == len(instance.disks)
11225
      assert compat.all(isinstance(i, bool) for i in dresults), \
11226
             "Not all results are boolean: %r" % dresults
11227

    
11228
    finally:
11229
      if activate_disks:
11230
        feedback_fn("Deactivating disks for %s" % instance.name)
11231
        _ShutdownInstanceDisks(self, instance)
11232

    
11233
    if not (compat.all(dresults) and fin_resu):
11234
      failures = []
11235
      if not fin_resu:
11236
        failures.append("export finalization")
11237
      if not compat.all(dresults):
11238
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
11239
                               if not dsk)
11240
        failures.append("disk export: disk(s) %s" % fdsk)
11241

    
11242
      raise errors.OpExecError("Export failed, errors in %s" %
11243
                               utils.CommaJoin(failures))
11244

    
11245
    # At this point, the export was successful, we can cleanup/finish
11246

    
11247
    # Remove instance if requested
11248
    if self.op.remove_instance:
11249
      feedback_fn("Removing instance %s" % instance.name)
11250
      _RemoveInstance(self, feedback_fn, instance,
11251
                      self.op.ignore_remove_failures)
11252

    
11253
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11254
      self._CleanupExports(feedback_fn)
11255

    
11256
    return fin_resu, dresults
11257

    
11258

    
11259
class LUBackupRemove(NoHooksLU):
11260
  """Remove exports related to the named instance.
11261

11262
  """
11263
  REQ_BGL = False
11264

    
11265
  def ExpandNames(self):
11266
    self.needed_locks = {}
11267
    # We need all nodes to be locked in order for RemoveExport to work, but we
11268
    # don't need to lock the instance itself, as nothing will happen to it (and
11269
    # we can remove exports also for a removed instance)
11270
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11271

    
11272
  def Exec(self, feedback_fn):
11273
    """Remove any export.
11274

11275
    """
11276
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11277
    # If the instance was not found we'll try with the name that was passed in.
11278
    # This will only work if it was an FQDN, though.
11279
    fqdn_warn = False
11280
    if not instance_name:
11281
      fqdn_warn = True
11282
      instance_name = self.op.instance_name
11283

    
11284
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
11285
    exportlist = self.rpc.call_export_list(locked_nodes)
11286
    found = False
11287
    for node in exportlist:
11288
      msg = exportlist[node].fail_msg
11289
      if msg:
11290
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11291
        continue
11292
      if instance_name in exportlist[node].payload:
11293
        found = True
11294
        result = self.rpc.call_export_remove(node, instance_name)
11295
        msg = result.fail_msg
11296
        if msg:
11297
          logging.error("Could not remove export for instance %s"
11298
                        " on node %s: %s", instance_name, node, msg)
11299

    
11300
    if fqdn_warn and not found:
11301
      feedback_fn("Export not found. If trying to remove an export belonging"
11302
                  " to a deleted instance please use its Fully Qualified"
11303
                  " Domain Name.")
11304

    
11305

    
11306
class LUGroupAdd(LogicalUnit):
11307
  """Logical unit for creating node groups.
11308

11309
  """
11310
  HPATH = "group-add"
11311
  HTYPE = constants.HTYPE_GROUP
11312
  REQ_BGL = False
11313

    
11314
  def ExpandNames(self):
11315
    # We need the new group's UUID here so that we can create and acquire the
11316
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11317
    # that it should not check whether the UUID exists in the configuration.
11318
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11319
    self.needed_locks = {}
11320
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11321

    
11322
  def CheckPrereq(self):
11323
    """Check prerequisites.
11324

11325
    This checks that the given group name is not an existing node group
11326
    already.
11327

11328
    """
11329
    try:
11330
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11331
    except errors.OpPrereqError:
11332
      pass
11333
    else:
11334
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11335
                                 " node group (UUID: %s)" %
11336
                                 (self.op.group_name, existing_uuid),
11337
                                 errors.ECODE_EXISTS)
11338

    
11339
    if self.op.ndparams:
11340
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11341

    
11342
  def BuildHooksEnv(self):
11343
    """Build hooks env.
11344

11345
    """
11346
    return {
11347
      "GROUP_NAME": self.op.group_name,
11348
      }
11349

    
11350
  def BuildHooksNodes(self):
11351
    """Build hooks nodes.
11352

11353
    """
11354
    mn = self.cfg.GetMasterNode()
11355
    return ([mn], [mn])
11356

    
11357
  def Exec(self, feedback_fn):
11358
    """Add the node group to the cluster.
11359

11360
    """
11361
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11362
                                  uuid=self.group_uuid,
11363
                                  alloc_policy=self.op.alloc_policy,
11364
                                  ndparams=self.op.ndparams)
11365

    
11366
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11367
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11368

    
11369

    
11370
class LUGroupAssignNodes(NoHooksLU):
11371
  """Logical unit for assigning nodes to groups.
11372

11373
  """
11374
  REQ_BGL = False
11375

    
11376
  def ExpandNames(self):
11377
    # These raise errors.OpPrereqError on their own:
11378
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11379
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11380

    
11381
    # We want to lock all the affected nodes and groups. We have readily
11382
    # available the list of nodes, and the *destination* group. To gather the
11383
    # list of "source" groups, we need to fetch node information later on.
11384
    self.needed_locks = {
11385
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11386
      locking.LEVEL_NODE: self.op.nodes,
11387
      }
11388

    
11389
  def DeclareLocks(self, level):
11390
    if level == locking.LEVEL_NODEGROUP:
11391
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11392

    
11393
      # Try to get all affected nodes' groups without having the group or node
11394
      # lock yet. Needs verification later in the code flow.
11395
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11396

    
11397
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11398

    
11399
  def CheckPrereq(self):
11400
    """Check prerequisites.
11401

11402
    """
11403
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11404
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11405
            frozenset(self.op.nodes))
11406

    
11407
    expected_locks = (set([self.group_uuid]) |
11408
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11409
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11410
    if actual_locks != expected_locks:
11411
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11412
                               " current groups are '%s', used to be '%s'" %
11413
                               (utils.CommaJoin(expected_locks),
11414
                                utils.CommaJoin(actual_locks)))
11415

    
11416
    self.node_data = self.cfg.GetAllNodesInfo()
11417
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11418
    instance_data = self.cfg.GetAllInstancesInfo()
11419

    
11420
    if self.group is None:
11421
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11422
                               (self.op.group_name, self.group_uuid))
11423

    
11424
    (new_splits, previous_splits) = \
11425
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11426
                                             for node in self.op.nodes],
11427
                                            self.node_data, instance_data)
11428

    
11429
    if new_splits:
11430
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11431

    
11432
      if not self.op.force:
11433
        raise errors.OpExecError("The following instances get split by this"
11434
                                 " change and --force was not given: %s" %
11435
                                 fmt_new_splits)
11436
      else:
11437
        self.LogWarning("This operation will split the following instances: %s",
11438
                        fmt_new_splits)
11439

    
11440
        if previous_splits:
11441
          self.LogWarning("In addition, these already-split instances continue"
11442
                          " to be split across groups: %s",
11443
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11444

    
11445
  def Exec(self, feedback_fn):
11446
    """Assign nodes to a new group.
11447

11448
    """
11449
    for node in self.op.nodes:
11450
      self.node_data[node].group = self.group_uuid
11451

    
11452
    # FIXME: Depends on side-effects of modifying the result of
11453
    # C{cfg.GetAllNodesInfo}
11454

    
11455
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11456

    
11457
  @staticmethod
11458
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11459
    """Check for split instances after a node assignment.
11460

11461
    This method considers a series of node assignments as an atomic operation,
11462
    and returns information about split instances after applying the set of
11463
    changes.
11464

11465
    In particular, it returns information about newly split instances, and
11466
    instances that were already split, and remain so after the change.
11467

11468
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11469
    considered.
11470

11471
    @type changes: list of (node_name, new_group_uuid) pairs.
11472
    @param changes: list of node assignments to consider.
11473
    @param node_data: a dict with data for all nodes
11474
    @param instance_data: a dict with all instances to consider
11475
    @rtype: a two-tuple
11476
    @return: a list of instances that were previously okay and result split as a
11477
      consequence of this change, and a list of instances that were previously
11478
      split and this change does not fix.
11479

11480
    """
11481
    changed_nodes = dict((node, group) for node, group in changes
11482
                         if node_data[node].group != group)
11483

    
11484
    all_split_instances = set()
11485
    previously_split_instances = set()
11486

    
11487
    def InstanceNodes(instance):
11488
      return [instance.primary_node] + list(instance.secondary_nodes)
11489

    
11490
    for inst in instance_data.values():
11491
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11492
        continue
11493

    
11494
      instance_nodes = InstanceNodes(inst)
11495

    
11496
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11497
        previously_split_instances.add(inst.name)
11498

    
11499
      if len(set(changed_nodes.get(node, node_data[node].group)
11500
                 for node in instance_nodes)) > 1:
11501
        all_split_instances.add(inst.name)
11502

    
11503
    return (list(all_split_instances - previously_split_instances),
11504
            list(previously_split_instances & all_split_instances))
11505

    
11506

    
11507
class _GroupQuery(_QueryBase):
11508
  FIELDS = query.GROUP_FIELDS
11509

    
11510
  def ExpandNames(self, lu):
11511
    lu.needed_locks = {}
11512

    
11513
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11514
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11515

    
11516
    if not self.names:
11517
      self.wanted = [name_to_uuid[name]
11518
                     for name in utils.NiceSort(name_to_uuid.keys())]
11519
    else:
11520
      # Accept names to be either names or UUIDs.
11521
      missing = []
11522
      self.wanted = []
11523
      all_uuid = frozenset(self._all_groups.keys())
11524

    
11525
      for name in self.names:
11526
        if name in all_uuid:
11527
          self.wanted.append(name)
11528
        elif name in name_to_uuid:
11529
          self.wanted.append(name_to_uuid[name])
11530
        else:
11531
          missing.append(name)
11532

    
11533
      if missing:
11534
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11535
                                   utils.CommaJoin(missing),
11536
                                   errors.ECODE_NOENT)
11537

    
11538
  def DeclareLocks(self, lu, level):
11539
    pass
11540

    
11541
  def _GetQueryData(self, lu):
11542
    """Computes the list of node groups and their attributes.
11543

11544
    """
11545
    do_nodes = query.GQ_NODE in self.requested_data
11546
    do_instances = query.GQ_INST in self.requested_data
11547

    
11548
    group_to_nodes = None
11549
    group_to_instances = None
11550

    
11551
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11552
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11553
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11554
    # instance->node. Hence, we will need to process nodes even if we only need
11555
    # instance information.
11556
    if do_nodes or do_instances:
11557
      all_nodes = lu.cfg.GetAllNodesInfo()
11558
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11559
      node_to_group = {}
11560

    
11561
      for node in all_nodes.values():
11562
        if node.group in group_to_nodes:
11563
          group_to_nodes[node.group].append(node.name)
11564
          node_to_group[node.name] = node.group
11565

    
11566
      if do_instances:
11567
        all_instances = lu.cfg.GetAllInstancesInfo()
11568
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11569

    
11570
        for instance in all_instances.values():
11571
          node = instance.primary_node
11572
          if node in node_to_group:
11573
            group_to_instances[node_to_group[node]].append(instance.name)
11574

    
11575
        if not do_nodes:
11576
          # Do not pass on node information if it was not requested.
11577
          group_to_nodes = None
11578

    
11579
    return query.GroupQueryData([self._all_groups[uuid]
11580
                                 for uuid in self.wanted],
11581
                                group_to_nodes, group_to_instances)
11582

    
11583

    
11584
class LUGroupQuery(NoHooksLU):
11585
  """Logical unit for querying node groups.
11586

11587
  """
11588
  REQ_BGL = False
11589

    
11590
  def CheckArguments(self):
11591
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11592
                          self.op.output_fields, False)
11593

    
11594
  def ExpandNames(self):
11595
    self.gq.ExpandNames(self)
11596

    
11597
  def Exec(self, feedback_fn):
11598
    return self.gq.OldStyleQuery(self)
11599

    
11600

    
11601
class LUGroupSetParams(LogicalUnit):
11602
  """Modifies the parameters of a node group.
11603

11604
  """
11605
  HPATH = "group-modify"
11606
  HTYPE = constants.HTYPE_GROUP
11607
  REQ_BGL = False
11608

    
11609
  def CheckArguments(self):
11610
    all_changes = [
11611
      self.op.ndparams,
11612
      self.op.alloc_policy,
11613
      ]
11614

    
11615
    if all_changes.count(None) == len(all_changes):
11616
      raise errors.OpPrereqError("Please pass at least one modification",
11617
                                 errors.ECODE_INVAL)
11618

    
11619
  def ExpandNames(self):
11620
    # This raises errors.OpPrereqError on its own:
11621
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11622

    
11623
    self.needed_locks = {
11624
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11625
      }
11626

    
11627
  def CheckPrereq(self):
11628
    """Check prerequisites.
11629

11630
    """
11631
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11632

    
11633
    if self.group is None:
11634
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11635
                               (self.op.group_name, self.group_uuid))
11636

    
11637
    if self.op.ndparams:
11638
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11639
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11640
      self.new_ndparams = new_ndparams
11641

    
11642
  def BuildHooksEnv(self):
11643
    """Build hooks env.
11644

11645
    """
11646
    return {
11647
      "GROUP_NAME": self.op.group_name,
11648
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11649
      }
11650

    
11651
  def BuildHooksNodes(self):
11652
    """Build hooks nodes.
11653

11654
    """
11655
    mn = self.cfg.GetMasterNode()
11656
    return ([mn], [mn])
11657

    
11658
  def Exec(self, feedback_fn):
11659
    """Modifies the node group.
11660

11661
    """
11662
    result = []
11663

    
11664
    if self.op.ndparams:
11665
      self.group.ndparams = self.new_ndparams
11666
      result.append(("ndparams", str(self.group.ndparams)))
11667

    
11668
    if self.op.alloc_policy:
11669
      self.group.alloc_policy = self.op.alloc_policy
11670

    
11671
    self.cfg.Update(self.group, feedback_fn)
11672
    return result
11673

    
11674

    
11675

    
11676
class LUGroupRemove(LogicalUnit):
11677
  HPATH = "group-remove"
11678
  HTYPE = constants.HTYPE_GROUP
11679
  REQ_BGL = False
11680

    
11681
  def ExpandNames(self):
11682
    # This will raises errors.OpPrereqError on its own:
11683
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11684
    self.needed_locks = {
11685
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11686
      }
11687

    
11688
  def CheckPrereq(self):
11689
    """Check prerequisites.
11690

11691
    This checks that the given group name exists as a node group, that is
11692
    empty (i.e., contains no nodes), and that is not the last group of the
11693
    cluster.
11694

11695
    """
11696
    # Verify that the group is empty.
11697
    group_nodes = [node.name
11698
                   for node in self.cfg.GetAllNodesInfo().values()
11699
                   if node.group == self.group_uuid]
11700

    
11701
    if group_nodes:
11702
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11703
                                 " nodes: %s" %
11704
                                 (self.op.group_name,
11705
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11706
                                 errors.ECODE_STATE)
11707

    
11708
    # Verify the cluster would not be left group-less.
11709
    if len(self.cfg.GetNodeGroupList()) == 1:
11710
      raise errors.OpPrereqError("Group '%s' is the only group,"
11711
                                 " cannot be removed" %
11712
                                 self.op.group_name,
11713
                                 errors.ECODE_STATE)
11714

    
11715
  def BuildHooksEnv(self):
11716
    """Build hooks env.
11717

11718
    """
11719
    return {
11720
      "GROUP_NAME": self.op.group_name,
11721
      }
11722

    
11723
  def BuildHooksNodes(self):
11724
    """Build hooks nodes.
11725

11726
    """
11727
    mn = self.cfg.GetMasterNode()
11728
    return ([mn], [mn])
11729

    
11730
  def Exec(self, feedback_fn):
11731
    """Remove the node group.
11732

11733
    """
11734
    try:
11735
      self.cfg.RemoveNodeGroup(self.group_uuid)
11736
    except errors.ConfigurationError:
11737
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11738
                               (self.op.group_name, self.group_uuid))
11739

    
11740
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11741

    
11742

    
11743
class LUGroupRename(LogicalUnit):
11744
  HPATH = "group-rename"
11745
  HTYPE = constants.HTYPE_GROUP
11746
  REQ_BGL = False
11747

    
11748
  def ExpandNames(self):
11749
    # This raises errors.OpPrereqError on its own:
11750
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11751

    
11752
    self.needed_locks = {
11753
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11754
      }
11755

    
11756
  def CheckPrereq(self):
11757
    """Check prerequisites.
11758

11759
    Ensures requested new name is not yet used.
11760

11761
    """
11762
    try:
11763
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11764
    except errors.OpPrereqError:
11765
      pass
11766
    else:
11767
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11768
                                 " node group (UUID: %s)" %
11769
                                 (self.op.new_name, new_name_uuid),
11770
                                 errors.ECODE_EXISTS)
11771

    
11772
  def BuildHooksEnv(self):
11773
    """Build hooks env.
11774

11775
    """
11776
    return {
11777
      "OLD_NAME": self.op.group_name,
11778
      "NEW_NAME": self.op.new_name,
11779
      }
11780

    
11781
  def BuildHooksNodes(self):
11782
    """Build hooks nodes.
11783

11784
    """
11785
    mn = self.cfg.GetMasterNode()
11786

    
11787
    all_nodes = self.cfg.GetAllNodesInfo()
11788
    all_nodes.pop(mn, None)
11789

    
11790
    run_nodes = [mn]
11791
    run_nodes.extend(node.name for node in all_nodes.values()
11792
                     if node.group == self.group_uuid)
11793

    
11794
    return (run_nodes, run_nodes)
11795

    
11796
  def Exec(self, feedback_fn):
11797
    """Rename the node group.
11798

11799
    """
11800
    group = self.cfg.GetNodeGroup(self.group_uuid)
11801

    
11802
    if group is None:
11803
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11804
                               (self.op.group_name, self.group_uuid))
11805

    
11806
    group.name = self.op.new_name
11807
    self.cfg.Update(group, feedback_fn)
11808

    
11809
    return self.op.new_name
11810

    
11811

    
11812
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11813
  """Generic tags LU.
11814

11815
  This is an abstract class which is the parent of all the other tags LUs.
11816

11817
  """
11818
  def ExpandNames(self):
11819
    self.group_uuid = None
11820
    self.needed_locks = {}
11821
    if self.op.kind == constants.TAG_NODE:
11822
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11823
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11824
    elif self.op.kind == constants.TAG_INSTANCE:
11825
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11826
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11827
    elif self.op.kind == constants.TAG_NODEGROUP:
11828
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
11829

    
11830
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11831
    # not possible to acquire the BGL based on opcode parameters)
11832

    
11833
  def CheckPrereq(self):
11834
    """Check prerequisites.
11835

11836
    """
11837
    if self.op.kind == constants.TAG_CLUSTER:
11838
      self.target = self.cfg.GetClusterInfo()
11839
    elif self.op.kind == constants.TAG_NODE:
11840
      self.target = self.cfg.GetNodeInfo(self.op.name)
11841
    elif self.op.kind == constants.TAG_INSTANCE:
11842
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11843
    elif self.op.kind == constants.TAG_NODEGROUP:
11844
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
11845
    else:
11846
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11847
                                 str(self.op.kind), errors.ECODE_INVAL)
11848

    
11849

    
11850
class LUTagsGet(TagsLU):
11851
  """Returns the tags of a given object.
11852

11853
  """
11854
  REQ_BGL = False
11855

    
11856
  def ExpandNames(self):
11857
    TagsLU.ExpandNames(self)
11858

    
11859
    # Share locks as this is only a read operation
11860
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11861

    
11862
  def Exec(self, feedback_fn):
11863
    """Returns the tag list.
11864

11865
    """
11866
    return list(self.target.GetTags())
11867

    
11868

    
11869
class LUTagsSearch(NoHooksLU):
11870
  """Searches the tags for a given pattern.
11871

11872
  """
11873
  REQ_BGL = False
11874

    
11875
  def ExpandNames(self):
11876
    self.needed_locks = {}
11877

    
11878
  def CheckPrereq(self):
11879
    """Check prerequisites.
11880

11881
    This checks the pattern passed for validity by compiling it.
11882

11883
    """
11884
    try:
11885
      self.re = re.compile(self.op.pattern)
11886
    except re.error, err:
11887
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11888
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11889

    
11890
  def Exec(self, feedback_fn):
11891
    """Returns the tag list.
11892

11893
    """
11894
    cfg = self.cfg
11895
    tgts = [("/cluster", cfg.GetClusterInfo())]
11896
    ilist = cfg.GetAllInstancesInfo().values()
11897
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11898
    nlist = cfg.GetAllNodesInfo().values()
11899
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11900
    tgts.extend(("/nodegroup/%s" % n.name, n)
11901
                for n in cfg.GetAllNodeGroupsInfo().values())
11902
    results = []
11903
    for path, target in tgts:
11904
      for tag in target.GetTags():
11905
        if self.re.search(tag):
11906
          results.append((path, tag))
11907
    return results
11908

    
11909

    
11910
class LUTagsSet(TagsLU):
11911
  """Sets a tag on a given object.
11912

11913
  """
11914
  REQ_BGL = False
11915

    
11916
  def CheckPrereq(self):
11917
    """Check prerequisites.
11918

11919
    This checks the type and length of the tag name and value.
11920

11921
    """
11922
    TagsLU.CheckPrereq(self)
11923
    for tag in self.op.tags:
11924
      objects.TaggableObject.ValidateTag(tag)
11925

    
11926
  def Exec(self, feedback_fn):
11927
    """Sets the tag.
11928

11929
    """
11930
    try:
11931
      for tag in self.op.tags:
11932
        self.target.AddTag(tag)
11933
    except errors.TagError, err:
11934
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11935
    self.cfg.Update(self.target, feedback_fn)
11936

    
11937

    
11938
class LUTagsDel(TagsLU):
11939
  """Delete a list of tags from a given object.
11940

11941
  """
11942
  REQ_BGL = False
11943

    
11944
  def CheckPrereq(self):
11945
    """Check prerequisites.
11946

11947
    This checks that we have the given tag.
11948

11949
    """
11950
    TagsLU.CheckPrereq(self)
11951
    for tag in self.op.tags:
11952
      objects.TaggableObject.ValidateTag(tag)
11953
    del_tags = frozenset(self.op.tags)
11954
    cur_tags = self.target.GetTags()
11955

    
11956
    diff_tags = del_tags - cur_tags
11957
    if diff_tags:
11958
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11959
      raise errors.OpPrereqError("Tag(s) %s not found" %
11960
                                 (utils.CommaJoin(diff_names), ),
11961
                                 errors.ECODE_NOENT)
11962

    
11963
  def Exec(self, feedback_fn):
11964
    """Remove the tag from the object.
11965

11966
    """
11967
    for tag in self.op.tags:
11968
      self.target.RemoveTag(tag)
11969
    self.cfg.Update(self.target, feedback_fn)
11970

    
11971

    
11972
class LUTestDelay(NoHooksLU):
11973
  """Sleep for a specified amount of time.
11974

11975
  This LU sleeps on the master and/or nodes for a specified amount of
11976
  time.
11977

11978
  """
11979
  REQ_BGL = False
11980

    
11981
  def ExpandNames(self):
11982
    """Expand names and set required locks.
11983

11984
    This expands the node list, if any.
11985

11986
    """
11987
    self.needed_locks = {}
11988
    if self.op.on_nodes:
11989
      # _GetWantedNodes can be used here, but is not always appropriate to use
11990
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11991
      # more information.
11992
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11993
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11994

    
11995
  def _TestDelay(self):
11996
    """Do the actual sleep.
11997

11998
    """
11999
    if self.op.on_master:
12000
      if not utils.TestDelay(self.op.duration):
12001
        raise errors.OpExecError("Error during master delay test")
12002
    if self.op.on_nodes:
12003
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
12004
      for node, node_result in result.items():
12005
        node_result.Raise("Failure during rpc call to node %s" % node)
12006

    
12007
  def Exec(self, feedback_fn):
12008
    """Execute the test delay opcode, with the wanted repetitions.
12009

12010
    """
12011
    if self.op.repeat == 0:
12012
      self._TestDelay()
12013
    else:
12014
      top_value = self.op.repeat - 1
12015
      for i in range(self.op.repeat):
12016
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
12017
        self._TestDelay()
12018

    
12019

    
12020
class LUTestJqueue(NoHooksLU):
12021
  """Utility LU to test some aspects of the job queue.
12022

12023
  """
12024
  REQ_BGL = False
12025

    
12026
  # Must be lower than default timeout for WaitForJobChange to see whether it
12027
  # notices changed jobs
12028
  _CLIENT_CONNECT_TIMEOUT = 20.0
12029
  _CLIENT_CONFIRM_TIMEOUT = 60.0
12030

    
12031
  @classmethod
12032
  def _NotifyUsingSocket(cls, cb, errcls):
12033
    """Opens a Unix socket and waits for another program to connect.
12034

12035
    @type cb: callable
12036
    @param cb: Callback to send socket name to client
12037
    @type errcls: class
12038
    @param errcls: Exception class to use for errors
12039

12040
    """
12041
    # Using a temporary directory as there's no easy way to create temporary
12042
    # sockets without writing a custom loop around tempfile.mktemp and
12043
    # socket.bind
12044
    tmpdir = tempfile.mkdtemp()
12045
    try:
12046
      tmpsock = utils.PathJoin(tmpdir, "sock")
12047

    
12048
      logging.debug("Creating temporary socket at %s", tmpsock)
12049
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
12050
      try:
12051
        sock.bind(tmpsock)
12052
        sock.listen(1)
12053

    
12054
        # Send details to client
12055
        cb(tmpsock)
12056

    
12057
        # Wait for client to connect before continuing
12058
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
12059
        try:
12060
          (conn, _) = sock.accept()
12061
        except socket.error, err:
12062
          raise errcls("Client didn't connect in time (%s)" % err)
12063
      finally:
12064
        sock.close()
12065
    finally:
12066
      # Remove as soon as client is connected
12067
      shutil.rmtree(tmpdir)
12068

    
12069
    # Wait for client to close
12070
    try:
12071
      try:
12072
        # pylint: disable-msg=E1101
12073
        # Instance of '_socketobject' has no ... member
12074
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
12075
        conn.recv(1)
12076
      except socket.error, err:
12077
        raise errcls("Client failed to confirm notification (%s)" % err)
12078
    finally:
12079
      conn.close()
12080

    
12081
  def _SendNotification(self, test, arg, sockname):
12082
    """Sends a notification to the client.
12083

12084
    @type test: string
12085
    @param test: Test name
12086
    @param arg: Test argument (depends on test)
12087
    @type sockname: string
12088
    @param sockname: Socket path
12089

12090
    """
12091
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
12092

    
12093
  def _Notify(self, prereq, test, arg):
12094
    """Notifies the client of a test.
12095

12096
    @type prereq: bool
12097
    @param prereq: Whether this is a prereq-phase test
12098
    @type test: string
12099
    @param test: Test name
12100
    @param arg: Test argument (depends on test)
12101

12102
    """
12103
    if prereq:
12104
      errcls = errors.OpPrereqError
12105
    else:
12106
      errcls = errors.OpExecError
12107

    
12108
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
12109
                                                  test, arg),
12110
                                   errcls)
12111

    
12112
  def CheckArguments(self):
12113
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
12114
    self.expandnames_calls = 0
12115

    
12116
  def ExpandNames(self):
12117
    checkargs_calls = getattr(self, "checkargs_calls", 0)
12118
    if checkargs_calls < 1:
12119
      raise errors.ProgrammerError("CheckArguments was not called")
12120

    
12121
    self.expandnames_calls += 1
12122

    
12123
    if self.op.notify_waitlock:
12124
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
12125

    
12126
    self.LogInfo("Expanding names")
12127

    
12128
    # Get lock on master node (just to get a lock, not for a particular reason)
12129
    self.needed_locks = {
12130
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
12131
      }
12132

    
12133
  def Exec(self, feedback_fn):
12134
    if self.expandnames_calls < 1:
12135
      raise errors.ProgrammerError("ExpandNames was not called")
12136

    
12137
    if self.op.notify_exec:
12138
      self._Notify(False, constants.JQT_EXEC, None)
12139

    
12140
    self.LogInfo("Executing")
12141

    
12142
    if self.op.log_messages:
12143
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
12144
      for idx, msg in enumerate(self.op.log_messages):
12145
        self.LogInfo("Sending log message %s", idx + 1)
12146
        feedback_fn(constants.JQT_MSGPREFIX + msg)
12147
        # Report how many test messages have been sent
12148
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
12149

    
12150
    if self.op.fail:
12151
      raise errors.OpExecError("Opcode failure was requested")
12152

    
12153
    return True
12154

    
12155

    
12156
class IAllocator(object):
12157
  """IAllocator framework.
12158

12159
  An IAllocator instance has three sets of attributes:
12160
    - cfg that is needed to query the cluster
12161
    - input data (all members of the _KEYS class attribute are required)
12162
    - four buffer attributes (in|out_data|text), that represent the
12163
      input (to the external script) in text and data structure format,
12164
      and the output from it, again in two formats
12165
    - the result variables from the script (success, info, nodes) for
12166
      easy usage
12167

12168
  """
12169
  # pylint: disable-msg=R0902
12170
  # lots of instance attributes
12171

    
12172
  def __init__(self, cfg, rpc, mode, **kwargs):
12173
    self.cfg = cfg
12174
    self.rpc = rpc
12175
    # init buffer variables
12176
    self.in_text = self.out_text = self.in_data = self.out_data = None
12177
    # init all input fields so that pylint is happy
12178
    self.mode = mode
12179
    self.memory = self.disks = self.disk_template = None
12180
    self.os = self.tags = self.nics = self.vcpus = None
12181
    self.hypervisor = None
12182
    self.relocate_from = None
12183
    self.name = None
12184
    self.evac_nodes = None
12185
    self.instances = None
12186
    self.evac_mode = None
12187
    self.target_groups = []
12188
    # computed fields
12189
    self.required_nodes = None
12190
    # init result fields
12191
    self.success = self.info = self.result = None
12192

    
12193
    try:
12194
      (fn, keydata, self._result_check) = self._MODE_DATA[self.mode]
12195
    except KeyError:
12196
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
12197
                                   " IAllocator" % self.mode)
12198

    
12199
    keyset = [n for (n, _) in keydata]
12200

    
12201
    for key in kwargs:
12202
      if key not in keyset:
12203
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
12204
                                     " IAllocator" % key)
12205
      setattr(self, key, kwargs[key])
12206

    
12207
    for key in keyset:
12208
      if key not in kwargs:
12209
        raise errors.ProgrammerError("Missing input parameter '%s' to"
12210
                                     " IAllocator" % key)
12211
    self._BuildInputData(compat.partial(fn, self), keydata)
12212

    
12213
  def _ComputeClusterData(self):
12214
    """Compute the generic allocator input data.
12215

12216
    This is the data that is independent of the actual operation.
12217

12218
    """
12219
    cfg = self.cfg
12220
    cluster_info = cfg.GetClusterInfo()
12221
    # cluster data
12222
    data = {
12223
      "version": constants.IALLOCATOR_VERSION,
12224
      "cluster_name": cfg.GetClusterName(),
12225
      "cluster_tags": list(cluster_info.GetTags()),
12226
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
12227
      # we don't have job IDs
12228
      }
12229
    ninfo = cfg.GetAllNodesInfo()
12230
    iinfo = cfg.GetAllInstancesInfo().values()
12231
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
12232

    
12233
    # node data
12234
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
12235

    
12236
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
12237
      hypervisor_name = self.hypervisor
12238
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
12239
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
12240
    else:
12241
      hypervisor_name = cluster_info.enabled_hypervisors[0]
12242

    
12243
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
12244
                                        hypervisor_name)
12245
    node_iinfo = \
12246
      self.rpc.call_all_instances_info(node_list,
12247
                                       cluster_info.enabled_hypervisors)
12248

    
12249
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
12250

    
12251
    config_ndata = self._ComputeBasicNodeData(ninfo)
12252
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12253
                                                 i_list, config_ndata)
12254
    assert len(data["nodes"]) == len(ninfo), \
12255
        "Incomplete node data computed"
12256

    
12257
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12258

    
12259
    self.in_data = data
12260

    
12261
  @staticmethod
12262
  def _ComputeNodeGroupData(cfg):
12263
    """Compute node groups data.
12264

12265
    """
12266
    ng = dict((guuid, {
12267
      "name": gdata.name,
12268
      "alloc_policy": gdata.alloc_policy,
12269
      })
12270
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12271

    
12272
    return ng
12273

    
12274
  @staticmethod
12275
  def _ComputeBasicNodeData(node_cfg):
12276
    """Compute global node data.
12277

12278
    @rtype: dict
12279
    @returns: a dict of name: (node dict, node config)
12280

12281
    """
12282
    # fill in static (config-based) values
12283
    node_results = dict((ninfo.name, {
12284
      "tags": list(ninfo.GetTags()),
12285
      "primary_ip": ninfo.primary_ip,
12286
      "secondary_ip": ninfo.secondary_ip,
12287
      "offline": ninfo.offline,
12288
      "drained": ninfo.drained,
12289
      "master_candidate": ninfo.master_candidate,
12290
      "group": ninfo.group,
12291
      "master_capable": ninfo.master_capable,
12292
      "vm_capable": ninfo.vm_capable,
12293
      })
12294
      for ninfo in node_cfg.values())
12295

    
12296
    return node_results
12297

    
12298
  @staticmethod
12299
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
12300
                              node_results):
12301
    """Compute global node data.
12302

12303
    @param node_results: the basic node structures as filled from the config
12304

12305
    """
12306
    # make a copy of the current dict
12307
    node_results = dict(node_results)
12308
    for nname, nresult in node_data.items():
12309
      assert nname in node_results, "Missing basic data for node %s" % nname
12310
      ninfo = node_cfg[nname]
12311

    
12312
      if not (ninfo.offline or ninfo.drained):
12313
        nresult.Raise("Can't get data for node %s" % nname)
12314
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
12315
                                nname)
12316
        remote_info = nresult.payload
12317

    
12318
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
12319
                     'vg_size', 'vg_free', 'cpu_total']:
12320
          if attr not in remote_info:
12321
            raise errors.OpExecError("Node '%s' didn't return attribute"
12322
                                     " '%s'" % (nname, attr))
12323
          if not isinstance(remote_info[attr], int):
12324
            raise errors.OpExecError("Node '%s' returned invalid value"
12325
                                     " for '%s': %s" %
12326
                                     (nname, attr, remote_info[attr]))
12327
        # compute memory used by primary instances
12328
        i_p_mem = i_p_up_mem = 0
12329
        for iinfo, beinfo in i_list:
12330
          if iinfo.primary_node == nname:
12331
            i_p_mem += beinfo[constants.BE_MEMORY]
12332
            if iinfo.name not in node_iinfo[nname].payload:
12333
              i_used_mem = 0
12334
            else:
12335
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
12336
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
12337
            remote_info['memory_free'] -= max(0, i_mem_diff)
12338

    
12339
            if iinfo.admin_up:
12340
              i_p_up_mem += beinfo[constants.BE_MEMORY]
12341

    
12342
        # compute memory used by instances
12343
        pnr_dyn = {
12344
          "total_memory": remote_info['memory_total'],
12345
          "reserved_memory": remote_info['memory_dom0'],
12346
          "free_memory": remote_info['memory_free'],
12347
          "total_disk": remote_info['vg_size'],
12348
          "free_disk": remote_info['vg_free'],
12349
          "total_cpus": remote_info['cpu_total'],
12350
          "i_pri_memory": i_p_mem,
12351
          "i_pri_up_memory": i_p_up_mem,
12352
          }
12353
        pnr_dyn.update(node_results[nname])
12354
        node_results[nname] = pnr_dyn
12355

    
12356
    return node_results
12357

    
12358
  @staticmethod
12359
  def _ComputeInstanceData(cluster_info, i_list):
12360
    """Compute global instance data.
12361

12362
    """
12363
    instance_data = {}
12364
    for iinfo, beinfo in i_list:
12365
      nic_data = []
12366
      for nic in iinfo.nics:
12367
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
12368
        nic_dict = {
12369
          "mac": nic.mac,
12370
          "ip": nic.ip,
12371
          "mode": filled_params[constants.NIC_MODE],
12372
          "link": filled_params[constants.NIC_LINK],
12373
          }
12374
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
12375
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
12376
        nic_data.append(nic_dict)
12377
      pir = {
12378
        "tags": list(iinfo.GetTags()),
12379
        "admin_up": iinfo.admin_up,
12380
        "vcpus": beinfo[constants.BE_VCPUS],
12381
        "memory": beinfo[constants.BE_MEMORY],
12382
        "os": iinfo.os,
12383
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12384
        "nics": nic_data,
12385
        "disks": [{constants.IDISK_SIZE: dsk.size,
12386
                   constants.IDISK_MODE: dsk.mode}
12387
                  for dsk in iinfo.disks],
12388
        "disk_template": iinfo.disk_template,
12389
        "hypervisor": iinfo.hypervisor,
12390
        }
12391
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12392
                                                 pir["disks"])
12393
      instance_data[iinfo.name] = pir
12394

    
12395
    return instance_data
12396

    
12397
  def _AddNewInstance(self):
12398
    """Add new instance data to allocator structure.
12399

12400
    This in combination with _AllocatorGetClusterData will create the
12401
    correct structure needed as input for the allocator.
12402

12403
    The checks for the completeness of the opcode must have already been
12404
    done.
12405

12406
    """
12407
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12408

    
12409
    if self.disk_template in constants.DTS_INT_MIRROR:
12410
      self.required_nodes = 2
12411
    else:
12412
      self.required_nodes = 1
12413

    
12414
    request = {
12415
      "name": self.name,
12416
      "disk_template": self.disk_template,
12417
      "tags": self.tags,
12418
      "os": self.os,
12419
      "vcpus": self.vcpus,
12420
      "memory": self.memory,
12421
      "disks": self.disks,
12422
      "disk_space_total": disk_space,
12423
      "nics": self.nics,
12424
      "required_nodes": self.required_nodes,
12425
      "hypervisor": self.hypervisor,
12426
      }
12427

    
12428
    return request
12429

    
12430
  def _AddRelocateInstance(self):
12431
    """Add relocate instance data to allocator structure.
12432

12433
    This in combination with _IAllocatorGetClusterData will create the
12434
    correct structure needed as input for the allocator.
12435

12436
    The checks for the completeness of the opcode must have already been
12437
    done.
12438

12439
    """
12440
    instance = self.cfg.GetInstanceInfo(self.name)
12441
    if instance is None:
12442
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12443
                                   " IAllocator" % self.name)
12444

    
12445
    if instance.disk_template not in constants.DTS_MIRRORED:
12446
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12447
                                 errors.ECODE_INVAL)
12448

    
12449
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12450
        len(instance.secondary_nodes) != 1:
12451
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12452
                                 errors.ECODE_STATE)
12453

    
12454
    self.required_nodes = 1
12455
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12456
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12457

    
12458
    request = {
12459
      "name": self.name,
12460
      "disk_space_total": disk_space,
12461
      "required_nodes": self.required_nodes,
12462
      "relocate_from": self.relocate_from,
12463
      }
12464
    return request
12465

    
12466
  def _AddEvacuateNodes(self):
12467
    """Add evacuate nodes data to allocator structure.
12468

12469
    """
12470
    request = {
12471
      "evac_nodes": self.evac_nodes
12472
      }
12473
    return request
12474

    
12475
  def _AddNodeEvacuate(self):
12476
    """Get data for node-evacuate requests.
12477

12478
    """
12479
    return {
12480
      "instances": self.instances,
12481
      "evac_mode": self.evac_mode,
12482
      }
12483

    
12484
  def _AddChangeGroup(self):
12485
    """Get data for node-evacuate requests.
12486

12487
    """
12488
    return {
12489
      "instances": self.instances,
12490
      "target_groups": self.target_groups,
12491
      }
12492

    
12493
  def _BuildInputData(self, fn, keydata):
12494
    """Build input data structures.
12495

12496
    """
12497
    self._ComputeClusterData()
12498

    
12499
    request = fn()
12500
    request["type"] = self.mode
12501
    for keyname, keytype in keydata:
12502
      if keyname not in request:
12503
        raise errors.ProgrammerError("Request parameter %s is missing" %
12504
                                     keyname)
12505
      val = request[keyname]
12506
      if not keytype(val):
12507
        raise errors.ProgrammerError("Request parameter %s doesn't pass"
12508
                                     " validation, value %s, expected"
12509
                                     " type %s" % (keyname, val, keytype))
12510
    self.in_data["request"] = request
12511

    
12512
    self.in_text = serializer.Dump(self.in_data)
12513

    
12514
  _STRING_LIST = ht.TListOf(ht.TString)
12515
  _JOBSET_LIST = ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12516
     # pylint: disable-msg=E1101
12517
     # Class '...' has no 'OP_ID' member
12518
     "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12519
                          opcodes.OpInstanceMigrate.OP_ID,
12520
                          opcodes.OpInstanceReplaceDisks.OP_ID])
12521
     })))
12522
  _MODE_DATA = {
12523
    constants.IALLOCATOR_MODE_ALLOC:
12524
      (_AddNewInstance,
12525
       [
12526
        ("name", ht.TString),
12527
        ("memory", ht.TInt),
12528
        ("disks", ht.TListOf(ht.TDict)),
12529
        ("disk_template", ht.TString),
12530
        ("os", ht.TString),
12531
        ("tags", _STRING_LIST),
12532
        ("nics", ht.TListOf(ht.TDict)),
12533
        ("vcpus", ht.TInt),
12534
        ("hypervisor", ht.TString),
12535
        ], ht.TList),
12536
    constants.IALLOCATOR_MODE_RELOC:
12537
      (_AddRelocateInstance,
12538
       [("name", ht.TString), ("relocate_from", _STRING_LIST)],
12539
       ht.TList),
12540
    constants.IALLOCATOR_MODE_MEVAC:
12541
      (_AddEvacuateNodes, [("evac_nodes", _STRING_LIST)],
12542
       ht.TListOf(ht.TAnd(ht.TIsLength(2), _STRING_LIST))),
12543
     constants.IALLOCATOR_MODE_NODE_EVAC:
12544
      (_AddNodeEvacuate, [
12545
        ("instances", _STRING_LIST),
12546
        ("evac_mode", ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)),
12547
        ], _JOBSET_LIST),
12548
     constants.IALLOCATOR_MODE_CHG_GROUP:
12549
      (_AddChangeGroup, [
12550
        ("instances", _STRING_LIST),
12551
        ("target_groups", _STRING_LIST),
12552
        ], _JOBSET_LIST),
12553
    }
12554

    
12555
  def Run(self, name, validate=True, call_fn=None):
12556
    """Run an instance allocator and return the results.
12557

12558
    """
12559
    if call_fn is None:
12560
      call_fn = self.rpc.call_iallocator_runner
12561

    
12562
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12563
    result.Raise("Failure while running the iallocator script")
12564

    
12565
    self.out_text = result.payload
12566
    if validate:
12567
      self._ValidateResult()
12568

    
12569
  def _ValidateResult(self):
12570
    """Process the allocator results.
12571

12572
    This will process and if successful save the result in
12573
    self.out_data and the other parameters.
12574

12575
    """
12576
    try:
12577
      rdict = serializer.Load(self.out_text)
12578
    except Exception, err:
12579
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12580

    
12581
    if not isinstance(rdict, dict):
12582
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12583

    
12584
    # TODO: remove backwards compatiblity in later versions
12585
    if "nodes" in rdict and "result" not in rdict:
12586
      rdict["result"] = rdict["nodes"]
12587
      del rdict["nodes"]
12588

    
12589
    for key in "success", "info", "result":
12590
      if key not in rdict:
12591
        raise errors.OpExecError("Can't parse iallocator results:"
12592
                                 " missing key '%s'" % key)
12593
      setattr(self, key, rdict[key])
12594

    
12595
    if not self._result_check(self.result):
12596
      raise errors.OpExecError("Iallocator returned invalid result,"
12597
                               " expected %s, got %s" %
12598
                               (self._result_check, self.result),
12599
                               errors.ECODE_INVAL)
12600

    
12601
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12602
                     constants.IALLOCATOR_MODE_MEVAC):
12603
      node2group = dict((name, ndata["group"])
12604
                        for (name, ndata) in self.in_data["nodes"].items())
12605

    
12606
      fn = compat.partial(self._NodesToGroups, node2group,
12607
                          self.in_data["nodegroups"])
12608

    
12609
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12610
        assert self.relocate_from is not None
12611
        assert self.required_nodes == 1
12612

    
12613
        request_groups = fn(self.relocate_from)
12614
        result_groups = fn(rdict["result"])
12615

    
12616
        if result_groups != request_groups:
12617
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12618
                                   " differ from original groups (%s)" %
12619
                                   (utils.CommaJoin(result_groups),
12620
                                    utils.CommaJoin(request_groups)))
12621
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12622
        request_groups = fn(self.evac_nodes)
12623
        for (instance_name, secnode) in self.result:
12624
          result_groups = fn([secnode])
12625
          if result_groups != request_groups:
12626
            raise errors.OpExecError("Iallocator returned new secondary node"
12627
                                     " '%s' (group '%s') for instance '%s'"
12628
                                     " which is not in original group '%s'" %
12629
                                     (secnode, utils.CommaJoin(result_groups),
12630
                                      instance_name,
12631
                                      utils.CommaJoin(request_groups)))
12632
      else:
12633
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12634

    
12635
    elif self.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
12636
      assert self.evac_mode in constants.IALLOCATOR_NEVAC_MODES
12637

    
12638
    self.out_data = rdict
12639

    
12640
  @staticmethod
12641
  def _NodesToGroups(node2group, groups, nodes):
12642
    """Returns a list of unique group names for a list of nodes.
12643

12644
    @type node2group: dict
12645
    @param node2group: Map from node name to group UUID
12646
    @type groups: dict
12647
    @param groups: Group information
12648
    @type nodes: list
12649
    @param nodes: Node names
12650

12651
    """
12652
    result = set()
12653

    
12654
    for node in nodes:
12655
      try:
12656
        group_uuid = node2group[node]
12657
      except KeyError:
12658
        # Ignore unknown node
12659
        pass
12660
      else:
12661
        try:
12662
          group = groups[group_uuid]
12663
        except KeyError:
12664
          # Can't find group, let's use UUID
12665
          group_name = group_uuid
12666
        else:
12667
          group_name = group["name"]
12668

    
12669
        result.add(group_name)
12670

    
12671
    return sorted(result)
12672

    
12673

    
12674
class LUTestAllocator(NoHooksLU):
12675
  """Run allocator tests.
12676

12677
  This LU runs the allocator tests
12678

12679
  """
12680
  def CheckPrereq(self):
12681
    """Check prerequisites.
12682

12683
    This checks the opcode parameters depending on the director and mode test.
12684

12685
    """
12686
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12687
      for attr in ["memory", "disks", "disk_template",
12688
                   "os", "tags", "nics", "vcpus"]:
12689
        if not hasattr(self.op, attr):
12690
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12691
                                     attr, errors.ECODE_INVAL)
12692
      iname = self.cfg.ExpandInstanceName(self.op.name)
12693
      if iname is not None:
12694
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12695
                                   iname, errors.ECODE_EXISTS)
12696
      if not isinstance(self.op.nics, list):
12697
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12698
                                   errors.ECODE_INVAL)
12699
      if not isinstance(self.op.disks, list):
12700
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12701
                                   errors.ECODE_INVAL)
12702
      for row in self.op.disks:
12703
        if (not isinstance(row, dict) or
12704
            constants.IDISK_SIZE not in row or
12705
            not isinstance(row[constants.IDISK_SIZE], int) or
12706
            constants.IDISK_MODE not in row or
12707
            row[constants.IDISK_MODE] not in constants.DISK_ACCESS_SET):
12708
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12709
                                     " parameter", errors.ECODE_INVAL)
12710
      if self.op.hypervisor is None:
12711
        self.op.hypervisor = self.cfg.GetHypervisorType()
12712
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12713
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12714
      self.op.name = fname
12715
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12716
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12717
      if not hasattr(self.op, "evac_nodes"):
12718
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12719
                                   " opcode input", errors.ECODE_INVAL)
12720
    elif self.op.mode in (constants.IALLOCATOR_MODE_CHG_GROUP,
12721
                          constants.IALLOCATOR_MODE_NODE_EVAC):
12722
      if not self.op.instances:
12723
        raise errors.OpPrereqError("Missing instances", errors.ECODE_INVAL)
12724
      self.op.instances = _GetWantedInstances(self, self.op.instances)
12725
    else:
12726
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12727
                                 self.op.mode, errors.ECODE_INVAL)
12728

    
12729
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12730
      if self.op.allocator is None:
12731
        raise errors.OpPrereqError("Missing allocator name",
12732
                                   errors.ECODE_INVAL)
12733
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12734
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12735
                                 self.op.direction, errors.ECODE_INVAL)
12736

    
12737
  def Exec(self, feedback_fn):
12738
    """Run the allocator test.
12739

12740
    """
12741
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12742
      ial = IAllocator(self.cfg, self.rpc,
12743
                       mode=self.op.mode,
12744
                       name=self.op.name,
12745
                       memory=self.op.memory,
12746
                       disks=self.op.disks,
12747
                       disk_template=self.op.disk_template,
12748
                       os=self.op.os,
12749
                       tags=self.op.tags,
12750
                       nics=self.op.nics,
12751
                       vcpus=self.op.vcpus,
12752
                       hypervisor=self.op.hypervisor,
12753
                       )
12754
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12755
      ial = IAllocator(self.cfg, self.rpc,
12756
                       mode=self.op.mode,
12757
                       name=self.op.name,
12758
                       relocate_from=list(self.relocate_from),
12759
                       )
12760
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12761
      ial = IAllocator(self.cfg, self.rpc,
12762
                       mode=self.op.mode,
12763
                       evac_nodes=self.op.evac_nodes)
12764
    elif self.op.mode == constants.IALLOCATOR_MODE_CHG_GROUP:
12765
      ial = IAllocator(self.cfg, self.rpc,
12766
                       mode=self.op.mode,
12767
                       instances=self.op.instances,
12768
                       target_groups=self.op.target_groups)
12769
    elif self.op.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
12770
      ial = IAllocator(self.cfg, self.rpc,
12771
                       mode=self.op.mode,
12772
                       instances=self.op.instances,
12773
                       evac_mode=self.op.evac_mode)
12774
    else:
12775
      raise errors.ProgrammerError("Uncatched mode %s in"
12776
                                   " LUTestAllocator.Exec", self.op.mode)
12777

    
12778
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
12779
      result = ial.in_text
12780
    else:
12781
      ial.Run(self.op.allocator, validate=False)
12782
      result = ial.out_text
12783
    return result
12784

    
12785

    
12786
#: Query type implementations
12787
_QUERY_IMPL = {
12788
  constants.QR_INSTANCE: _InstanceQuery,
12789
  constants.QR_NODE: _NodeQuery,
12790
  constants.QR_GROUP: _GroupQuery,
12791
  constants.QR_OS: _OsQuery,
12792
  }
12793

    
12794
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
12795

    
12796

    
12797
def _GetQueryImplementation(name):
12798
  """Returns the implemtnation for a query type.
12799

12800
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
12801

12802
  """
12803
  try:
12804
    return _QUERY_IMPL[name]
12805
  except KeyError:
12806
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
12807
                               errors.ECODE_INVAL)