Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 2dad1652

History | View | Annotate | Download (439.2 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
64

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

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

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

    
77

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

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

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

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

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

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

    
99

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

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

113
  Note that all commands require root permissions.
114

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

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

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

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

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

    
155
    # Tasklets
156
    self.tasklets = None
157

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

    
161
    self.CheckArguments()
162

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

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

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

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

178
    """
179
    pass
180

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

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

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

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

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

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

206
    Examples::
207

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

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

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

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

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

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

245
    """
246

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

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

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

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

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

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

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

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

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

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

297
    """
298
    raise NotImplementedError
299

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

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

311
    """
312
    raise NotImplementedError
313

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
400
    del self.recalculate_locks[locking.LEVEL_NODE]
401

    
402

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

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

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

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

416
    This just raises an error.
417

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

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

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

    
427

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

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

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

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

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

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

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

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

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

460
    """
461
    pass
462

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

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

470
    """
471
    raise NotImplementedError
472

    
473

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

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

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

484
    """
485
    self.use_locking = use_locking
486

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

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

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

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

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

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

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

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

    
521
    # Return expanded names
522
    return self.wanted
523

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

527
    See L{LogicalUnit.ExpandNames}.
528

529
    """
530
    raise NotImplementedError()
531

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

535
    See L{LogicalUnit.DeclareLocks}.
536

537
    """
538
    raise NotImplementedError()
539

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

543
    @return: Query data object
544

545
    """
546
    raise NotImplementedError()
547

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

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

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

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

    
562

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

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

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

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

    
580

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

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

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

    
600

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

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

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

    
633

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

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

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

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

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

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

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

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

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

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

    
678

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

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

    
690

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

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

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

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

    
709

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

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

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

    
724

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

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

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

    
739

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

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

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

    
752

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

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

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

    
765

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

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

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

    
783

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

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

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

    
810

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

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

    
818

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

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

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

    
834

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

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

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

    
851

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

    
856

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

    
861

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

867
  This builds the hook environment from individual variables.
868

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

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

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

    
931
  env["INSTANCE_NIC_COUNT"] = nic_count
932

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

    
941
  env["INSTANCE_DISK_COUNT"] = disk_count
942

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

    
947
  return env
948

    
949

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

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

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

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

    
973

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

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

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

    
1011

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

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

    
1027

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

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

    
1038

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

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

    
1052

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

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

    
1061

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

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

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

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

    
1081

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

    
1085

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

1089
  """
1090

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

    
1093

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

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

    
1101

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

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

    
1109

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

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

    
1119
  return []
1120

    
1121

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

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

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

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

    
1136
  return faulty
1137

    
1138

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

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

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

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

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

    
1170

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

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

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

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

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

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

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

1195
    """
1196
    return True
1197

    
1198

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

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

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

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

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

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

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

1223
    This checks whether the cluster is empty.
1224

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

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

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

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

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

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

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

    
1253
    return master
1254

    
1255

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

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

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

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

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

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

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

    
1288

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

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

1300
  """
1301
  hvp_data = []
1302

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

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

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

    
1318
  return hvp_data
1319

    
1320

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

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

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

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

    
1360
  ETYPE_FIELD = "code"
1361
  ETYPE_ERROR = "ERROR"
1362
  ETYPE_WARNING = "WARNING"
1363

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

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

1370
    This must be called only from Exec and functions called from Exec.
1371

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

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

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

    
1402

    
1403
class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1404
  """Verifies the cluster config.
1405

1406
  """
1407

    
1408
  REQ_BGL = False
1409

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

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

    
1424
  def ExpandNames(self):
1425
    self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1426
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1427
    self.needed_locks = {}
1428

    
1429
  def Exec(self, feedback_fn):
1430
    """Verify integrity of cluster, performing various test on nodes.
1431

1432
    """
1433
    self.bad = False
1434
    self._feedback_fn = feedback_fn
1435

    
1436
    feedback_fn("* Verifying cluster config")
1437

    
1438
    for msg in self.cfg.VerifyConfig():
1439
      self._ErrorIf(True, self.ECLUSTERCFG, None, msg)
1440

    
1441
    feedback_fn("* Verifying cluster certificate files")
1442

    
1443
    for cert_filename in constants.ALL_CERT_FILES:
1444
      (errcode, msg) = _VerifyCertificate(cert_filename)
1445
      self._ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1446

    
1447
    feedback_fn("* Verifying hypervisor parameters")
1448

    
1449
    self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1450
                                                self.all_inst_info.values()))
1451

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

    
1454

    
1455
class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1456
  """Verifies the status of a node group.
1457

1458
  """
1459

    
1460
  HPATH = "cluster-verify"
1461
  HTYPE = constants.HTYPE_CLUSTER
1462
  REQ_BGL = False
1463

    
1464
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1465

    
1466
  class NodeImage(object):
1467
    """A class representing the logical and physical status of a node.
1468

1469
    @type name: string
1470
    @ivar name: the node name to which this object refers
1471
    @ivar volumes: a structure as returned from
1472
        L{ganeti.backend.GetVolumeList} (runtime)
1473
    @ivar instances: a list of running instances (runtime)
1474
    @ivar pinst: list of configured primary instances (config)
1475
    @ivar sinst: list of configured secondary instances (config)
1476
    @ivar sbp: dictionary of {primary-node: list of instances} for all
1477
        instances for which this node is secondary (config)
1478
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1479
    @ivar dfree: free disk, as reported by the node (runtime)
1480
    @ivar offline: the offline status (config)
1481
    @type rpc_fail: boolean
1482
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1483
        not whether the individual keys were correct) (runtime)
1484
    @type lvm_fail: boolean
1485
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1486
    @type hyp_fail: boolean
1487
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1488
    @type ghost: boolean
1489
    @ivar ghost: whether this is a known node or not (config)
1490
    @type os_fail: boolean
1491
    @ivar os_fail: whether the RPC call didn't return valid OS data
1492
    @type oslist: list
1493
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1494
    @type vm_capable: boolean
1495
    @ivar vm_capable: whether the node can host instances
1496

1497
    """
1498
    def __init__(self, offline=False, name=None, vm_capable=True):
1499
      self.name = name
1500
      self.volumes = {}
1501
      self.instances = []
1502
      self.pinst = []
1503
      self.sinst = []
1504
      self.sbp = {}
1505
      self.mfree = 0
1506
      self.dfree = 0
1507
      self.offline = offline
1508
      self.vm_capable = vm_capable
1509
      self.rpc_fail = False
1510
      self.lvm_fail = False
1511
      self.hyp_fail = False
1512
      self.ghost = False
1513
      self.os_fail = False
1514
      self.oslist = {}
1515

    
1516
  def ExpandNames(self):
1517
    # This raises errors.OpPrereqError on its own:
1518
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1519

    
1520
    all_node_info = self.cfg.GetAllNodesInfo()
1521
    all_inst_info = self.cfg.GetAllInstancesInfo()
1522

    
1523
    node_names = set(node.name
1524
                     for node in all_node_info.values()
1525
                     if node.group == self.group_uuid)
1526

    
1527
    inst_names = [inst.name
1528
                  for inst in all_inst_info.values()
1529
                  if inst.primary_node in node_names]
1530

    
1531
    self.needed_locks = {
1532
      locking.LEVEL_NODEGROUP: [self.group_uuid],
1533
      locking.LEVEL_NODE: list(node_names),
1534
      locking.LEVEL_INSTANCE: inst_names,
1535
    }
1536

    
1537
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1538

    
1539
  def CheckPrereq(self):
1540
    self.all_node_info = self.cfg.GetAllNodesInfo()
1541
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1542

    
1543
    group_nodes = set(node.name
1544
                      for node in self.all_node_info.values()
1545
                      if node.group == self.group_uuid)
1546

    
1547
    group_instances = set(inst.name
1548
                          for inst in self.all_inst_info.values()
1549
                          if inst.primary_node in group_nodes)
1550

    
1551
    unlocked_nodes = \
1552
        group_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1553

    
1554
    unlocked_instances = \
1555
        group_instances.difference(self.glm.list_owned(locking.LEVEL_INSTANCE))
1556

    
1557
    if unlocked_nodes:
1558
      raise errors.OpPrereqError("missing lock for nodes: %s" %
1559
                                 utils.CommaJoin(unlocked_nodes))
1560

    
1561
    if unlocked_instances:
1562
      raise errors.OpPrereqError("missing lock for instances: %s" %
1563
                                 utils.CommaJoin(unlocked_instances))
1564

    
1565
    self.my_node_names = utils.NiceSort(group_nodes)
1566
    self.my_inst_names = utils.NiceSort(group_instances)
1567

    
1568
    self.my_node_info = dict((name, self.all_node_info[name])
1569
                             for name in self.my_node_names)
1570

    
1571
    self.my_inst_info = dict((name, self.all_inst_info[name])
1572
                             for name in self.my_inst_names)
1573

    
1574
  def _VerifyNode(self, ninfo, nresult):
1575
    """Perform some basic validation on data returned from a node.
1576

1577
      - check the result data structure is well formed and has all the
1578
        mandatory fields
1579
      - check ganeti version
1580

1581
    @type ninfo: L{objects.Node}
1582
    @param ninfo: the node to check
1583
    @param nresult: the results from the node
1584
    @rtype: boolean
1585
    @return: whether overall this call was successful (and we can expect
1586
         reasonable values in the respose)
1587

1588
    """
1589
    node = ninfo.name
1590
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1591

    
1592
    # main result, nresult should be a non-empty dict
1593
    test = not nresult or not isinstance(nresult, dict)
1594
    _ErrorIf(test, self.ENODERPC, node,
1595
                  "unable to verify node: no data returned")
1596
    if test:
1597
      return False
1598

    
1599
    # compares ganeti version
1600
    local_version = constants.PROTOCOL_VERSION
1601
    remote_version = nresult.get("version", None)
1602
    test = not (remote_version and
1603
                isinstance(remote_version, (list, tuple)) and
1604
                len(remote_version) == 2)
1605
    _ErrorIf(test, self.ENODERPC, node,
1606
             "connection to node returned invalid data")
1607
    if test:
1608
      return False
1609

    
1610
    test = local_version != remote_version[0]
1611
    _ErrorIf(test, self.ENODEVERSION, node,
1612
             "incompatible protocol versions: master %s,"
1613
             " node %s", local_version, remote_version[0])
1614
    if test:
1615
      return False
1616

    
1617
    # node seems compatible, we can actually try to look into its results
1618

    
1619
    # full package version
1620
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1621
                  self.ENODEVERSION, node,
1622
                  "software version mismatch: master %s, node %s",
1623
                  constants.RELEASE_VERSION, remote_version[1],
1624
                  code=self.ETYPE_WARNING)
1625

    
1626
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1627
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1628
      for hv_name, hv_result in hyp_result.iteritems():
1629
        test = hv_result is not None
1630
        _ErrorIf(test, self.ENODEHV, node,
1631
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1632

    
1633
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1634
    if ninfo.vm_capable and isinstance(hvp_result, list):
1635
      for item, hv_name, hv_result in hvp_result:
1636
        _ErrorIf(True, self.ENODEHV, node,
1637
                 "hypervisor %s parameter verify failure (source %s): %s",
1638
                 hv_name, item, hv_result)
1639

    
1640
    test = nresult.get(constants.NV_NODESETUP,
1641
                       ["Missing NODESETUP results"])
1642
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1643
             "; ".join(test))
1644

    
1645
    return True
1646

    
1647
  def _VerifyNodeTime(self, ninfo, nresult,
1648
                      nvinfo_starttime, nvinfo_endtime):
1649
    """Check the node time.
1650

1651
    @type ninfo: L{objects.Node}
1652
    @param ninfo: the node to check
1653
    @param nresult: the remote results for the node
1654
    @param nvinfo_starttime: the start time of the RPC call
1655
    @param nvinfo_endtime: the end time of the RPC call
1656

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

    
1661
    ntime = nresult.get(constants.NV_TIME, None)
1662
    try:
1663
      ntime_merged = utils.MergeTime(ntime)
1664
    except (ValueError, TypeError):
1665
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1666
      return
1667

    
1668
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1669
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1670
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1671
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1672
    else:
1673
      ntime_diff = None
1674

    
1675
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1676
             "Node time diverges by at least %s from master node time",
1677
             ntime_diff)
1678

    
1679
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1680
    """Check the node LVM results.
1681

1682
    @type ninfo: L{objects.Node}
1683
    @param ninfo: the node to check
1684
    @param nresult: the remote results for the node
1685
    @param vg_name: the configured VG name
1686

1687
    """
1688
    if vg_name is None:
1689
      return
1690

    
1691
    node = ninfo.name
1692
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1693

    
1694
    # checks vg existence and size > 20G
1695
    vglist = nresult.get(constants.NV_VGLIST, None)
1696
    test = not vglist
1697
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1698
    if not test:
1699
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1700
                                            constants.MIN_VG_SIZE)
1701
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1702

    
1703
    # check pv names
1704
    pvlist = nresult.get(constants.NV_PVLIST, None)
1705
    test = pvlist is None
1706
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1707
    if not test:
1708
      # check that ':' is not present in PV names, since it's a
1709
      # special character for lvcreate (denotes the range of PEs to
1710
      # use on the PV)
1711
      for _, pvname, owner_vg in pvlist:
1712
        test = ":" in pvname
1713
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1714
                 " '%s' of VG '%s'", pvname, owner_vg)
1715

    
1716
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1717
    """Check the node bridges.
1718

1719
    @type ninfo: L{objects.Node}
1720
    @param ninfo: the node to check
1721
    @param nresult: the remote results for the node
1722
    @param bridges: the expected list of bridges
1723

1724
    """
1725
    if not bridges:
1726
      return
1727

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

    
1731
    missing = nresult.get(constants.NV_BRIDGES, None)
1732
    test = not isinstance(missing, list)
1733
    _ErrorIf(test, self.ENODENET, node,
1734
             "did not return valid bridge information")
1735
    if not test:
1736
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1737
               utils.CommaJoin(sorted(missing)))
1738

    
1739
  def _VerifyNodeNetwork(self, ninfo, nresult):
1740
    """Check the node network connectivity results.
1741

1742
    @type ninfo: L{objects.Node}
1743
    @param ninfo: the node to check
1744
    @param nresult: the remote results for the node
1745

1746
    """
1747
    node = ninfo.name
1748
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1749

    
1750
    test = constants.NV_NODELIST not in nresult
1751
    _ErrorIf(test, self.ENODESSH, node,
1752
             "node hasn't returned node ssh connectivity data")
1753
    if not test:
1754
      if nresult[constants.NV_NODELIST]:
1755
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1756
          _ErrorIf(True, self.ENODESSH, node,
1757
                   "ssh communication with node '%s': %s", a_node, a_msg)
1758

    
1759
    test = constants.NV_NODENETTEST not in nresult
1760
    _ErrorIf(test, self.ENODENET, node,
1761
             "node hasn't returned node tcp connectivity data")
1762
    if not test:
1763
      if nresult[constants.NV_NODENETTEST]:
1764
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1765
        for anode in nlist:
1766
          _ErrorIf(True, self.ENODENET, node,
1767
                   "tcp communication with node '%s': %s",
1768
                   anode, nresult[constants.NV_NODENETTEST][anode])
1769

    
1770
    test = constants.NV_MASTERIP not in nresult
1771
    _ErrorIf(test, self.ENODENET, node,
1772
             "node hasn't returned node master IP reachability data")
1773
    if not test:
1774
      if not nresult[constants.NV_MASTERIP]:
1775
        if node == self.master_node:
1776
          msg = "the master node cannot reach the master IP (not configured?)"
1777
        else:
1778
          msg = "cannot reach the master IP"
1779
        _ErrorIf(True, self.ENODENET, node, msg)
1780

    
1781
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1782
                      diskstatus):
1783
    """Verify an instance.
1784

1785
    This function checks to see if the required block devices are
1786
    available on the instance's node.
1787

1788
    """
1789
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1790
    node_current = instanceconfig.primary_node
1791

    
1792
    node_vol_should = {}
1793
    instanceconfig.MapLVsByNode(node_vol_should)
1794

    
1795
    for node in node_vol_should:
1796
      n_img = node_image[node]
1797
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1798
        # ignore missing volumes on offline or broken nodes
1799
        continue
1800
      for volume in node_vol_should[node]:
1801
        test = volume not in n_img.volumes
1802
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1803
                 "volume %s missing on node %s", volume, node)
1804

    
1805
    if instanceconfig.admin_up:
1806
      pri_img = node_image[node_current]
1807
      test = instance not in pri_img.instances and not pri_img.offline
1808
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1809
               "instance not running on its primary node %s",
1810
               node_current)
1811

    
1812
    diskdata = [(nname, success, status, idx)
1813
                for (nname, disks) in diskstatus.items()
1814
                for idx, (success, status) in enumerate(disks)]
1815

    
1816
    for nname, success, bdev_status, idx in diskdata:
1817
      # the 'ghost node' construction in Exec() ensures that we have a
1818
      # node here
1819
      snode = node_image[nname]
1820
      bad_snode = snode.ghost or snode.offline
1821
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1822
               self.EINSTANCEFAULTYDISK, instance,
1823
               "couldn't retrieve status for disk/%s on %s: %s",
1824
               idx, nname, bdev_status)
1825
      _ErrorIf((instanceconfig.admin_up and success and
1826
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1827
               self.EINSTANCEFAULTYDISK, instance,
1828
               "disk/%s on %s is faulty", idx, nname)
1829

    
1830
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1831
    """Verify if there are any unknown volumes in the cluster.
1832

1833
    The .os, .swap and backup volumes are ignored. All other volumes are
1834
    reported as unknown.
1835

1836
    @type reserved: L{ganeti.utils.FieldSet}
1837
    @param reserved: a FieldSet of reserved volume names
1838

1839
    """
1840
    for node, n_img in node_image.items():
1841
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1842
        # skip non-healthy nodes
1843
        continue
1844
      for volume in n_img.volumes:
1845
        test = ((node not in node_vol_should or
1846
                volume not in node_vol_should[node]) and
1847
                not reserved.Matches(volume))
1848
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1849
                      "volume %s is unknown", volume)
1850

    
1851
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1852
    """Verify N+1 Memory Resilience.
1853

1854
    Check that if one single node dies we can still start all the
1855
    instances it was primary for.
1856

1857
    """
1858
    cluster_info = self.cfg.GetClusterInfo()
1859
    for node, n_img in node_image.items():
1860
      # This code checks that every node which is now listed as
1861
      # secondary has enough memory to host all instances it is
1862
      # supposed to should a single other node in the cluster fail.
1863
      # FIXME: not ready for failover to an arbitrary node
1864
      # FIXME: does not support file-backed instances
1865
      # WARNING: we currently take into account down instances as well
1866
      # as up ones, considering that even if they're down someone
1867
      # might want to start them even in the event of a node failure.
1868
      if n_img.offline:
1869
        # we're skipping offline nodes from the N+1 warning, since
1870
        # most likely we don't have good memory infromation from them;
1871
        # we already list instances living on such nodes, and that's
1872
        # enough warning
1873
        continue
1874
      for prinode, instances in n_img.sbp.items():
1875
        needed_mem = 0
1876
        for instance in instances:
1877
          bep = cluster_info.FillBE(instance_cfg[instance])
1878
          if bep[constants.BE_AUTO_BALANCE]:
1879
            needed_mem += bep[constants.BE_MEMORY]
1880
        test = n_img.mfree < needed_mem
1881
        self._ErrorIf(test, self.ENODEN1, node,
1882
                      "not enough memory to accomodate instance failovers"
1883
                      " should node %s fail (%dMiB needed, %dMiB available)",
1884
                      prinode, needed_mem, n_img.mfree)
1885

    
1886
  @classmethod
1887
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1888
                   (files_all, files_all_opt, files_mc, files_vm)):
1889
    """Verifies file checksums collected from all nodes.
1890

1891
    @param errorif: Callback for reporting errors
1892
    @param nodeinfo: List of L{objects.Node} objects
1893
    @param master_node: Name of master node
1894
    @param all_nvinfo: RPC results
1895

1896
    """
1897
    node_names = frozenset(node.name for node in nodeinfo)
1898

    
1899
    assert master_node in node_names
1900
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1901
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1902
           "Found file listed in more than one file list"
1903

    
1904
    # Define functions determining which nodes to consider for a file
1905
    file2nodefn = dict([(filename, fn)
1906
      for (files, fn) in [(files_all, None),
1907
                          (files_all_opt, None),
1908
                          (files_mc, lambda node: (node.master_candidate or
1909
                                                   node.name == master_node)),
1910
                          (files_vm, lambda node: node.vm_capable)]
1911
      for filename in files])
1912

    
1913
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1914

    
1915
    for node in nodeinfo:
1916
      nresult = all_nvinfo[node.name]
1917

    
1918
      if nresult.fail_msg or not nresult.payload:
1919
        node_files = None
1920
      else:
1921
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1922

    
1923
      test = not (node_files and isinstance(node_files, dict))
1924
      errorif(test, cls.ENODEFILECHECK, node.name,
1925
              "Node did not return file checksum data")
1926
      if test:
1927
        continue
1928

    
1929
      for (filename, checksum) in node_files.items():
1930
        # Check if the file should be considered for a node
1931
        fn = file2nodefn[filename]
1932
        if fn is None or fn(node):
1933
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
1934

    
1935
    for (filename, checksums) in fileinfo.items():
1936
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
1937

    
1938
      # Nodes having the file
1939
      with_file = frozenset(node_name
1940
                            for nodes in fileinfo[filename].values()
1941
                            for node_name in nodes)
1942

    
1943
      # Nodes missing file
1944
      missing_file = node_names - with_file
1945

    
1946
      if filename in files_all_opt:
1947
        # All or no nodes
1948
        errorif(missing_file and missing_file != node_names,
1949
                cls.ECLUSTERFILECHECK, None,
1950
                "File %s is optional, but it must exist on all or no nodes (not"
1951
                " found on %s)",
1952
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
1953
      else:
1954
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
1955
                "File %s is missing from node(s) %s", filename,
1956
                utils.CommaJoin(utils.NiceSort(missing_file)))
1957

    
1958
      # See if there are multiple versions of the file
1959
      test = len(checksums) > 1
1960
      if test:
1961
        variants = ["variant %s on %s" %
1962
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
1963
                    for (idx, (checksum, nodes)) in
1964
                      enumerate(sorted(checksums.items()))]
1965
      else:
1966
        variants = []
1967

    
1968
      errorif(test, cls.ECLUSTERFILECHECK, None,
1969
              "File %s found with %s different checksums (%s)",
1970
              filename, len(checksums), "; ".join(variants))
1971

    
1972
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1973
                      drbd_map):
1974
    """Verifies and the node DRBD status.
1975

1976
    @type ninfo: L{objects.Node}
1977
    @param ninfo: the node to check
1978
    @param nresult: the remote results for the node
1979
    @param instanceinfo: the dict of instances
1980
    @param drbd_helper: the configured DRBD usermode helper
1981
    @param drbd_map: the DRBD map as returned by
1982
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1983

1984
    """
1985
    node = ninfo.name
1986
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1987

    
1988
    if drbd_helper:
1989
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1990
      test = (helper_result == None)
1991
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1992
               "no drbd usermode helper returned")
1993
      if helper_result:
1994
        status, payload = helper_result
1995
        test = not status
1996
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1997
                 "drbd usermode helper check unsuccessful: %s", payload)
1998
        test = status and (payload != drbd_helper)
1999
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2000
                 "wrong drbd usermode helper: %s", payload)
2001

    
2002
    # compute the DRBD minors
2003
    node_drbd = {}
2004
    for minor, instance in drbd_map[node].items():
2005
      test = instance not in instanceinfo
2006
      _ErrorIf(test, self.ECLUSTERCFG, None,
2007
               "ghost instance '%s' in temporary DRBD map", instance)
2008
        # ghost instance should not be running, but otherwise we
2009
        # don't give double warnings (both ghost instance and
2010
        # unallocated minor in use)
2011
      if test:
2012
        node_drbd[minor] = (instance, False)
2013
      else:
2014
        instance = instanceinfo[instance]
2015
        node_drbd[minor] = (instance.name, instance.admin_up)
2016

    
2017
    # and now check them
2018
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
2019
    test = not isinstance(used_minors, (tuple, list))
2020
    _ErrorIf(test, self.ENODEDRBD, node,
2021
             "cannot parse drbd status file: %s", str(used_minors))
2022
    if test:
2023
      # we cannot check drbd status
2024
      return
2025

    
2026
    for minor, (iname, must_exist) in node_drbd.items():
2027
      test = minor not in used_minors and must_exist
2028
      _ErrorIf(test, self.ENODEDRBD, node,
2029
               "drbd minor %d of instance %s is not active", minor, iname)
2030
    for minor in used_minors:
2031
      test = minor not in node_drbd
2032
      _ErrorIf(test, self.ENODEDRBD, node,
2033
               "unallocated drbd minor %d is in use", minor)
2034

    
2035
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
2036
    """Builds the node OS structures.
2037

2038
    @type ninfo: L{objects.Node}
2039
    @param ninfo: the node to check
2040
    @param nresult: the remote results for the node
2041
    @param nimg: the node image object
2042

2043
    """
2044
    node = ninfo.name
2045
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2046

    
2047
    remote_os = nresult.get(constants.NV_OSLIST, None)
2048
    test = (not isinstance(remote_os, list) or
2049
            not compat.all(isinstance(v, list) and len(v) == 7
2050
                           for v in remote_os))
2051

    
2052
    _ErrorIf(test, self.ENODEOS, node,
2053
             "node hasn't returned valid OS data")
2054

    
2055
    nimg.os_fail = test
2056

    
2057
    if test:
2058
      return
2059

    
2060
    os_dict = {}
2061

    
2062
    for (name, os_path, status, diagnose,
2063
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2064

    
2065
      if name not in os_dict:
2066
        os_dict[name] = []
2067

    
2068
      # parameters is a list of lists instead of list of tuples due to
2069
      # JSON lacking a real tuple type, fix it:
2070
      parameters = [tuple(v) for v in parameters]
2071
      os_dict[name].append((os_path, status, diagnose,
2072
                            set(variants), set(parameters), set(api_ver)))
2073

    
2074
    nimg.oslist = os_dict
2075

    
2076
  def _VerifyNodeOS(self, ninfo, nimg, base):
2077
    """Verifies the node OS list.
2078

2079
    @type ninfo: L{objects.Node}
2080
    @param ninfo: the node to check
2081
    @param nimg: the node image object
2082
    @param base: the 'template' node we match against (e.g. from the master)
2083

2084
    """
2085
    node = ninfo.name
2086
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2087

    
2088
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2089

    
2090
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
2091
    for os_name, os_data in nimg.oslist.items():
2092
      assert os_data, "Empty OS status for OS %s?!" % os_name
2093
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
2094
      _ErrorIf(not f_status, self.ENODEOS, node,
2095
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
2096
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
2097
               "OS '%s' has multiple entries (first one shadows the rest): %s",
2098
               os_name, utils.CommaJoin([v[0] for v in os_data]))
2099
      # this will catched in backend too
2100
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
2101
               and not f_var, self.ENODEOS, node,
2102
               "OS %s with API at least %d does not declare any variant",
2103
               os_name, constants.OS_API_V15)
2104
      # comparisons with the 'base' image
2105
      test = os_name not in base.oslist
2106
      _ErrorIf(test, self.ENODEOS, node,
2107
               "Extra OS %s not present on reference node (%s)",
2108
               os_name, base.name)
2109
      if test:
2110
        continue
2111
      assert base.oslist[os_name], "Base node has empty OS status?"
2112
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
2113
      if not b_status:
2114
        # base OS is invalid, skipping
2115
        continue
2116
      for kind, a, b in [("API version", f_api, b_api),
2117
                         ("variants list", f_var, b_var),
2118
                         ("parameters", beautify_params(f_param),
2119
                          beautify_params(b_param))]:
2120
        _ErrorIf(a != b, self.ENODEOS, node,
2121
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2122
                 kind, os_name, base.name,
2123
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2124

    
2125
    # check any missing OSes
2126
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2127
    _ErrorIf(missing, self.ENODEOS, node,
2128
             "OSes present on reference node %s but missing on this node: %s",
2129
             base.name, utils.CommaJoin(missing))
2130

    
2131
  def _VerifyOob(self, ninfo, nresult):
2132
    """Verifies out of band functionality of a node.
2133

2134
    @type ninfo: L{objects.Node}
2135
    @param ninfo: the node to check
2136
    @param nresult: the remote results for the node
2137

2138
    """
2139
    node = ninfo.name
2140
    # We just have to verify the paths on master and/or master candidates
2141
    # as the oob helper is invoked on the master
2142
    if ((ninfo.master_candidate or ninfo.master_capable) and
2143
        constants.NV_OOB_PATHS in nresult):
2144
      for path_result in nresult[constants.NV_OOB_PATHS]:
2145
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2146

    
2147
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2148
    """Verifies and updates the node volume data.
2149

2150
    This function will update a L{NodeImage}'s internal structures
2151
    with data from the remote call.
2152

2153
    @type ninfo: L{objects.Node}
2154
    @param ninfo: the node to check
2155
    @param nresult: the remote results for the node
2156
    @param nimg: the node image object
2157
    @param vg_name: the configured VG name
2158

2159
    """
2160
    node = ninfo.name
2161
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2162

    
2163
    nimg.lvm_fail = True
2164
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2165
    if vg_name is None:
2166
      pass
2167
    elif isinstance(lvdata, basestring):
2168
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2169
               utils.SafeEncode(lvdata))
2170
    elif not isinstance(lvdata, dict):
2171
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2172
    else:
2173
      nimg.volumes = lvdata
2174
      nimg.lvm_fail = False
2175

    
2176
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2177
    """Verifies and updates the node instance list.
2178

2179
    If the listing was successful, then updates this node's instance
2180
    list. Otherwise, it marks the RPC call as failed for the instance
2181
    list key.
2182

2183
    @type ninfo: L{objects.Node}
2184
    @param ninfo: the node to check
2185
    @param nresult: the remote results for the node
2186
    @param nimg: the node image object
2187

2188
    """
2189
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2190
    test = not isinstance(idata, list)
2191
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2192
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2193
    if test:
2194
      nimg.hyp_fail = True
2195
    else:
2196
      nimg.instances = idata
2197

    
2198
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2199
    """Verifies and computes a node information map
2200

2201
    @type ninfo: L{objects.Node}
2202
    @param ninfo: the node to check
2203
    @param nresult: the remote results for the node
2204
    @param nimg: the node image object
2205
    @param vg_name: the configured VG name
2206

2207
    """
2208
    node = ninfo.name
2209
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2210

    
2211
    # try to read free memory (from the hypervisor)
2212
    hv_info = nresult.get(constants.NV_HVINFO, None)
2213
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2214
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2215
    if not test:
2216
      try:
2217
        nimg.mfree = int(hv_info["memory_free"])
2218
      except (ValueError, TypeError):
2219
        _ErrorIf(True, self.ENODERPC, node,
2220
                 "node returned invalid nodeinfo, check hypervisor")
2221

    
2222
    # FIXME: devise a free space model for file based instances as well
2223
    if vg_name is not None:
2224
      test = (constants.NV_VGLIST not in nresult or
2225
              vg_name not in nresult[constants.NV_VGLIST])
2226
      _ErrorIf(test, self.ENODELVM, node,
2227
               "node didn't return data for the volume group '%s'"
2228
               " - it is either missing or broken", vg_name)
2229
      if not test:
2230
        try:
2231
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2232
        except (ValueError, TypeError):
2233
          _ErrorIf(True, self.ENODERPC, node,
2234
                   "node returned invalid LVM info, check LVM status")
2235

    
2236
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2237
    """Gets per-disk status information for all instances.
2238

2239
    @type nodelist: list of strings
2240
    @param nodelist: Node names
2241
    @type node_image: dict of (name, L{objects.Node})
2242
    @param node_image: Node objects
2243
    @type instanceinfo: dict of (name, L{objects.Instance})
2244
    @param instanceinfo: Instance objects
2245
    @rtype: {instance: {node: [(succes, payload)]}}
2246
    @return: a dictionary of per-instance dictionaries with nodes as
2247
        keys and disk information as values; the disk information is a
2248
        list of tuples (success, payload)
2249

2250
    """
2251
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2252

    
2253
    node_disks = {}
2254
    node_disks_devonly = {}
2255
    diskless_instances = set()
2256
    diskless = constants.DT_DISKLESS
2257

    
2258
    for nname in nodelist:
2259
      node_instances = list(itertools.chain(node_image[nname].pinst,
2260
                                            node_image[nname].sinst))
2261
      diskless_instances.update(inst for inst in node_instances
2262
                                if instanceinfo[inst].disk_template == diskless)
2263
      disks = [(inst, disk)
2264
               for inst in node_instances
2265
               for disk in instanceinfo[inst].disks]
2266

    
2267
      if not disks:
2268
        # No need to collect data
2269
        continue
2270

    
2271
      node_disks[nname] = disks
2272

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

    
2277
      for dev in devonly:
2278
        self.cfg.SetDiskID(dev, nname)
2279

    
2280
      node_disks_devonly[nname] = devonly
2281

    
2282
    assert len(node_disks) == len(node_disks_devonly)
2283

    
2284
    # Collect data from all nodes with disks
2285
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2286
                                                          node_disks_devonly)
2287

    
2288
    assert len(result) == len(node_disks)
2289

    
2290
    instdisk = {}
2291

    
2292
    for (nname, nres) in result.items():
2293
      disks = node_disks[nname]
2294

    
2295
      if nres.offline:
2296
        # No data from this node
2297
        data = len(disks) * [(False, "node offline")]
2298
      else:
2299
        msg = nres.fail_msg
2300
        _ErrorIf(msg, self.ENODERPC, nname,
2301
                 "while getting disk information: %s", msg)
2302
        if msg:
2303
          # No data from this node
2304
          data = len(disks) * [(False, msg)]
2305
        else:
2306
          data = []
2307
          for idx, i in enumerate(nres.payload):
2308
            if isinstance(i, (tuple, list)) and len(i) == 2:
2309
              data.append(i)
2310
            else:
2311
              logging.warning("Invalid result from node %s, entry %d: %s",
2312
                              nname, idx, i)
2313
              data.append((False, "Invalid result from the remote node"))
2314

    
2315
      for ((inst, _), status) in zip(disks, data):
2316
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2317

    
2318
    # Add empty entries for diskless instances.
2319
    for inst in diskless_instances:
2320
      assert inst not in instdisk
2321
      instdisk[inst] = {}
2322

    
2323
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2324
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2325
                      compat.all(isinstance(s, (tuple, list)) and
2326
                                 len(s) == 2 for s in statuses)
2327
                      for inst, nnames in instdisk.items()
2328
                      for nname, statuses in nnames.items())
2329
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2330

    
2331
    return instdisk
2332

    
2333
  def BuildHooksEnv(self):
2334
    """Build hooks env.
2335

2336
    Cluster-Verify hooks just ran in the post phase and their failure makes
2337
    the output be logged in the verify output and the verification to fail.
2338

2339
    """
2340
    env = {
2341
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2342
      }
2343

    
2344
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2345
               for node in self.my_node_info.values())
2346

    
2347
    return env
2348

    
2349
  def BuildHooksNodes(self):
2350
    """Build hooks nodes.
2351

2352
    """
2353
    assert self.my_node_names, ("Node list not gathered,"
2354
      " has CheckPrereq been executed?")
2355
    return ([], self.my_node_names)
2356

    
2357
  def Exec(self, feedback_fn):
2358
    """Verify integrity of the node group, performing various test on nodes.
2359

2360
    """
2361
    # This method has too many local variables. pylint: disable-msg=R0914
2362
    self.bad = False
2363
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2364
    verbose = self.op.verbose
2365
    self._feedback_fn = feedback_fn
2366

    
2367
    vg_name = self.cfg.GetVGName()
2368
    drbd_helper = self.cfg.GetDRBDHelper()
2369
    cluster = self.cfg.GetClusterInfo()
2370
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2371
    hypervisors = cluster.enabled_hypervisors
2372
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2373

    
2374
    i_non_redundant = [] # Non redundant instances
2375
    i_non_a_balanced = [] # Non auto-balanced instances
2376
    n_offline = 0 # Count of offline nodes
2377
    n_drained = 0 # Count of nodes being drained
2378
    node_vol_should = {}
2379

    
2380
    # FIXME: verify OS list
2381

    
2382
    # File verification
2383
    filemap = _ComputeAncillaryFiles(cluster, False)
2384

    
2385
    # do local checksums
2386
    master_node = self.master_node = self.cfg.GetMasterNode()
2387
    master_ip = self.cfg.GetMasterIP()
2388

    
2389
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2390

    
2391
    # We will make nodes contact all nodes in their group, and one node from
2392
    # every other group.
2393
    # TODO: should it be a *random* node, different every time?
2394
    online_nodes = [node.name for node in node_data_list if not node.offline]
2395
    other_group_nodes = {}
2396

    
2397
    for name in sorted(self.all_node_info):
2398
      node = self.all_node_info[name]
2399
      if (node.group not in other_group_nodes
2400
          and node.group != self.group_uuid
2401
          and not node.offline):
2402
        other_group_nodes[node.group] = node.name
2403

    
2404
    node_verify_param = {
2405
      constants.NV_FILELIST:
2406
        utils.UniqueSequence(filename
2407
                             for files in filemap
2408
                             for filename in files),
2409
      constants.NV_NODELIST: online_nodes + other_group_nodes.values(),
2410
      constants.NV_HYPERVISOR: hypervisors,
2411
      constants.NV_HVPARAMS:
2412
        _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2413
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2414
                                 for node in node_data_list
2415
                                 if not node.offline],
2416
      constants.NV_INSTANCELIST: hypervisors,
2417
      constants.NV_VERSION: None,
2418
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2419
      constants.NV_NODESETUP: None,
2420
      constants.NV_TIME: None,
2421
      constants.NV_MASTERIP: (master_node, master_ip),
2422
      constants.NV_OSLIST: None,
2423
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2424
      }
2425

    
2426
    if vg_name is not None:
2427
      node_verify_param[constants.NV_VGLIST] = None
2428
      node_verify_param[constants.NV_LVLIST] = vg_name
2429
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2430
      node_verify_param[constants.NV_DRBDLIST] = None
2431

    
2432
    if drbd_helper:
2433
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2434

    
2435
    # bridge checks
2436
    # FIXME: this needs to be changed per node-group, not cluster-wide
2437
    bridges = set()
2438
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2439
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2440
      bridges.add(default_nicpp[constants.NIC_LINK])
2441
    for instance in self.my_inst_info.values():
2442
      for nic in instance.nics:
2443
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2444
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2445
          bridges.add(full_nic[constants.NIC_LINK])
2446

    
2447
    if bridges:
2448
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2449

    
2450
    # Build our expected cluster state
2451
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2452
                                                 name=node.name,
2453
                                                 vm_capable=node.vm_capable))
2454
                      for node in node_data_list)
2455

    
2456
    # Gather OOB paths
2457
    oob_paths = []
2458
    for node in self.all_node_info.values():
2459
      path = _SupportsOob(self.cfg, node)
2460
      if path and path not in oob_paths:
2461
        oob_paths.append(path)
2462

    
2463
    if oob_paths:
2464
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2465

    
2466
    for instance in self.my_inst_names:
2467
      inst_config = self.my_inst_info[instance]
2468

    
2469
      for nname in inst_config.all_nodes:
2470
        if nname not in node_image:
2471
          # ghost node
2472
          gnode = self.NodeImage(name=nname)
2473
          gnode.ghost = True
2474
          node_image[nname] = gnode
2475

    
2476
      inst_config.MapLVsByNode(node_vol_should)
2477

    
2478
      pnode = inst_config.primary_node
2479
      node_image[pnode].pinst.append(instance)
2480

    
2481
      for snode in inst_config.secondary_nodes:
2482
        nimg = node_image[snode]
2483
        nimg.sinst.append(instance)
2484
        if pnode not in nimg.sbp:
2485
          nimg.sbp[pnode] = []
2486
        nimg.sbp[pnode].append(instance)
2487

    
2488
    # At this point, we have the in-memory data structures complete,
2489
    # except for the runtime information, which we'll gather next
2490

    
2491
    # Due to the way our RPC system works, exact response times cannot be
2492
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2493
    # time before and after executing the request, we can at least have a time
2494
    # window.
2495
    nvinfo_starttime = time.time()
2496
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2497
                                           node_verify_param,
2498
                                           self.cfg.GetClusterName())
2499
    nvinfo_endtime = time.time()
2500

    
2501
    all_drbd_map = self.cfg.ComputeDRBDMap()
2502

    
2503
    feedback_fn("* Gathering disk information (%s nodes)" %
2504
                len(self.my_node_names))
2505
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2506
                                     self.my_inst_info)
2507

    
2508
    feedback_fn("* Verifying configuration file consistency")
2509

    
2510
    # If not all nodes are being checked, we need to make sure the master node
2511
    # and a non-checked vm_capable node are in the list.
2512
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2513
    if absent_nodes:
2514
      vf_nvinfo = all_nvinfo.copy()
2515
      vf_node_info = list(self.my_node_info.values())
2516
      additional_nodes = []
2517
      if master_node not in self.my_node_info:
2518
        additional_nodes.append(master_node)
2519
        vf_node_info.append(self.all_node_info[master_node])
2520
      # Add the first vm_capable node we find which is not included
2521
      for node in absent_nodes:
2522
        nodeinfo = self.all_node_info[node]
2523
        if nodeinfo.vm_capable and not nodeinfo.offline:
2524
          additional_nodes.append(node)
2525
          vf_node_info.append(self.all_node_info[node])
2526
          break
2527
      key = constants.NV_FILELIST
2528
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2529
                                                 {key: node_verify_param[key]},
2530
                                                 self.cfg.GetClusterName()))
2531
    else:
2532
      vf_nvinfo = all_nvinfo
2533
      vf_node_info = self.my_node_info.values()
2534

    
2535
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2536

    
2537
    feedback_fn("* Verifying node status")
2538

    
2539
    refos_img = None
2540

    
2541
    for node_i in node_data_list:
2542
      node = node_i.name
2543
      nimg = node_image[node]
2544

    
2545
      if node_i.offline:
2546
        if verbose:
2547
          feedback_fn("* Skipping offline node %s" % (node,))
2548
        n_offline += 1
2549
        continue
2550

    
2551
      if node == master_node:
2552
        ntype = "master"
2553
      elif node_i.master_candidate:
2554
        ntype = "master candidate"
2555
      elif node_i.drained:
2556
        ntype = "drained"
2557
        n_drained += 1
2558
      else:
2559
        ntype = "regular"
2560
      if verbose:
2561
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2562

    
2563
      msg = all_nvinfo[node].fail_msg
2564
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2565
      if msg:
2566
        nimg.rpc_fail = True
2567
        continue
2568

    
2569
      nresult = all_nvinfo[node].payload
2570

    
2571
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2572
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2573
      self._VerifyNodeNetwork(node_i, nresult)
2574
      self._VerifyOob(node_i, nresult)
2575

    
2576
      if nimg.vm_capable:
2577
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2578
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2579
                             all_drbd_map)
2580

    
2581
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2582
        self._UpdateNodeInstances(node_i, nresult, nimg)
2583
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2584
        self._UpdateNodeOS(node_i, nresult, nimg)
2585

    
2586
        if not nimg.os_fail:
2587
          if refos_img is None:
2588
            refos_img = nimg
2589
          self._VerifyNodeOS(node_i, nimg, refos_img)
2590
        self._VerifyNodeBridges(node_i, nresult, bridges)
2591

    
2592
        # Check whether all running instancies are primary for the node. (This
2593
        # can no longer be done from _VerifyInstance below, since some of the
2594
        # wrong instances could be from other node groups.)
2595
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2596

    
2597
        for inst in non_primary_inst:
2598
          test = inst in self.all_inst_info
2599
          _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2600
                   "instance should not run on node %s", node_i.name)
2601
          _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2602
                   "node is running unknown instance %s", inst)
2603

    
2604
    feedback_fn("* Verifying instance status")
2605
    for instance in self.my_inst_names:
2606
      if verbose:
2607
        feedback_fn("* Verifying instance %s" % instance)
2608
      inst_config = self.my_inst_info[instance]
2609
      self._VerifyInstance(instance, inst_config, node_image,
2610
                           instdisk[instance])
2611
      inst_nodes_offline = []
2612

    
2613
      pnode = inst_config.primary_node
2614
      pnode_img = node_image[pnode]
2615
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2616
               self.ENODERPC, pnode, "instance %s, connection to"
2617
               " primary node failed", instance)
2618

    
2619
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2620
               self.EINSTANCEBADNODE, instance,
2621
               "instance is marked as running and lives on offline node %s",
2622
               inst_config.primary_node)
2623

    
2624
      # If the instance is non-redundant we cannot survive losing its primary
2625
      # node, so we are not N+1 compliant. On the other hand we have no disk
2626
      # templates with more than one secondary so that situation is not well
2627
      # supported either.
2628
      # FIXME: does not support file-backed instances
2629
      if not inst_config.secondary_nodes:
2630
        i_non_redundant.append(instance)
2631

    
2632
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2633
               instance, "instance has multiple secondary nodes: %s",
2634
               utils.CommaJoin(inst_config.secondary_nodes),
2635
               code=self.ETYPE_WARNING)
2636

    
2637
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2638
        pnode = inst_config.primary_node
2639
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2640
        instance_groups = {}
2641

    
2642
        for node in instance_nodes:
2643
          instance_groups.setdefault(self.all_node_info[node].group,
2644
                                     []).append(node)
2645

    
2646
        pretty_list = [
2647
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2648
          # Sort so that we always list the primary node first.
2649
          for group, nodes in sorted(instance_groups.items(),
2650
                                     key=lambda (_, nodes): pnode in nodes,
2651
                                     reverse=True)]
2652

    
2653
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2654
                      instance, "instance has primary and secondary nodes in"
2655
                      " different groups: %s", utils.CommaJoin(pretty_list),
2656
                      code=self.ETYPE_WARNING)
2657

    
2658
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2659
        i_non_a_balanced.append(instance)
2660

    
2661
      for snode in inst_config.secondary_nodes:
2662
        s_img = node_image[snode]
2663
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2664
                 "instance %s, connection to secondary node failed", instance)
2665

    
2666
        if s_img.offline:
2667
          inst_nodes_offline.append(snode)
2668

    
2669
      # warn that the instance lives on offline nodes
2670
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2671
               "instance has offline secondary node(s) %s",
2672
               utils.CommaJoin(inst_nodes_offline))
2673
      # ... or ghost/non-vm_capable nodes
2674
      for node in inst_config.all_nodes:
2675
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2676
                 "instance lives on ghost node %s", node)
2677
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2678
                 instance, "instance lives on non-vm_capable node %s", node)
2679

    
2680
    feedback_fn("* Verifying orphan volumes")
2681
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2682
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2683

    
2684
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2685
      feedback_fn("* Verifying N+1 Memory redundancy")
2686
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2687

    
2688
    feedback_fn("* Other Notes")
2689
    if i_non_redundant:
2690
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2691
                  % len(i_non_redundant))
2692

    
2693
    if i_non_a_balanced:
2694
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2695
                  % len(i_non_a_balanced))
2696

    
2697
    if n_offline:
2698
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2699

    
2700
    if n_drained:
2701
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2702

    
2703
    return not self.bad
2704

    
2705
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2706
    """Analyze the post-hooks' result
2707

2708
    This method analyses the hook result, handles it, and sends some
2709
    nicely-formatted feedback back to the user.
2710

2711
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2712
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2713
    @param hooks_results: the results of the multi-node hooks rpc call
2714
    @param feedback_fn: function used send feedback back to the caller
2715
    @param lu_result: previous Exec result
2716
    @return: the new Exec result, based on the previous result
2717
        and hook results
2718

2719
    """
2720
    # We only really run POST phase hooks, and are only interested in
2721
    # their results
2722
    if phase == constants.HOOKS_PHASE_POST:
2723
      # Used to change hooks' output to proper indentation
2724
      feedback_fn("* Hooks Results")
2725
      assert hooks_results, "invalid result from hooks"
2726

    
2727
      for node_name in hooks_results:
2728
        res = hooks_results[node_name]
2729
        msg = res.fail_msg
2730
        test = msg and not res.offline
2731
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2732
                      "Communication failure in hooks execution: %s", msg)
2733
        if res.offline or msg:
2734
          # No need to investigate payload if node is offline or gave an error.
2735
          # override manually lu_result here as _ErrorIf only
2736
          # overrides self.bad
2737
          lu_result = 1
2738
          continue
2739
        for script, hkr, output in res.payload:
2740
          test = hkr == constants.HKR_FAIL
2741
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2742
                        "Script %s failed, output:", script)
2743
          if test:
2744
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2745
            feedback_fn("%s" % output)
2746
            lu_result = 0
2747

    
2748
      return lu_result
2749

    
2750

    
2751
class LUClusterVerifyDisks(NoHooksLU):
2752
  """Verifies the cluster disks status.
2753

2754
  """
2755
  REQ_BGL = False
2756

    
2757
  def ExpandNames(self):
2758
    self.needed_locks = {
2759
      locking.LEVEL_NODE: locking.ALL_SET,
2760
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2761
    }
2762
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2763

    
2764
  def Exec(self, feedback_fn):
2765
    """Verify integrity of cluster disks.
2766

2767
    @rtype: tuple of three items
2768
    @return: a tuple of (dict of node-to-node_error, list of instances
2769
        which need activate-disks, dict of instance: (node, volume) for
2770
        missing volumes
2771

2772
    """
2773
    result = res_nodes, res_instances, res_missing = {}, [], {}
2774

    
2775
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2776
    instances = self.cfg.GetAllInstancesInfo().values()
2777

    
2778
    nv_dict = {}
2779
    for inst in instances:
2780
      inst_lvs = {}
2781
      if not inst.admin_up:
2782
        continue
2783
      inst.MapLVsByNode(inst_lvs)
2784
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2785
      for node, vol_list in inst_lvs.iteritems():
2786
        for vol in vol_list:
2787
          nv_dict[(node, vol)] = inst
2788

    
2789
    if not nv_dict:
2790
      return result
2791

    
2792
    node_lvs = self.rpc.call_lv_list(nodes, [])
2793
    for node, node_res in node_lvs.items():
2794
      if node_res.offline:
2795
        continue
2796
      msg = node_res.fail_msg
2797
      if msg:
2798
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2799
        res_nodes[node] = msg
2800
        continue
2801

    
2802
      lvs = node_res.payload
2803
      for lv_name, (_, _, lv_online) in lvs.items():
2804
        inst = nv_dict.pop((node, lv_name), None)
2805
        if (not lv_online and inst is not None
2806
            and inst.name not in res_instances):
2807
          res_instances.append(inst.name)
2808

    
2809
    # any leftover items in nv_dict are missing LVs, let's arrange the
2810
    # data better
2811
    for key, inst in nv_dict.iteritems():
2812
      if inst.name not in res_missing:
2813
        res_missing[inst.name] = []
2814
      res_missing[inst.name].append(key)
2815

    
2816
    return result
2817

    
2818

    
2819
class LUClusterRepairDiskSizes(NoHooksLU):
2820
  """Verifies the cluster disks sizes.
2821

2822
  """
2823
  REQ_BGL = False
2824

    
2825
  def ExpandNames(self):
2826
    if self.op.instances:
2827
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2828
      self.needed_locks = {
2829
        locking.LEVEL_NODE: [],
2830
        locking.LEVEL_INSTANCE: self.wanted_names,
2831
        }
2832
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2833
    else:
2834
      self.wanted_names = None
2835
      self.needed_locks = {
2836
        locking.LEVEL_NODE: locking.ALL_SET,
2837
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2838
        }
2839
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2840

    
2841
  def DeclareLocks(self, level):
2842
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2843
      self._LockInstancesNodes(primary_only=True)
2844

    
2845
  def CheckPrereq(self):
2846
    """Check prerequisites.
2847

2848
    This only checks the optional instance list against the existing names.
2849

2850
    """
2851
    if self.wanted_names is None:
2852
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2853

    
2854
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2855
                             in self.wanted_names]
2856

    
2857
  def _EnsureChildSizes(self, disk):
2858
    """Ensure children of the disk have the needed disk size.
2859

2860
    This is valid mainly for DRBD8 and fixes an issue where the
2861
    children have smaller disk size.
2862

2863
    @param disk: an L{ganeti.objects.Disk} object
2864

2865
    """
2866
    if disk.dev_type == constants.LD_DRBD8:
2867
      assert disk.children, "Empty children for DRBD8?"
2868
      fchild = disk.children[0]
2869
      mismatch = fchild.size < disk.size
2870
      if mismatch:
2871
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2872
                     fchild.size, disk.size)
2873
        fchild.size = disk.size
2874

    
2875
      # and we recurse on this child only, not on the metadev
2876
      return self._EnsureChildSizes(fchild) or mismatch
2877
    else:
2878
      return False
2879

    
2880
  def Exec(self, feedback_fn):
2881
    """Verify the size of cluster disks.
2882

2883
    """
2884
    # TODO: check child disks too
2885
    # TODO: check differences in size between primary/secondary nodes
2886
    per_node_disks = {}
2887
    for instance in self.wanted_instances:
2888
      pnode = instance.primary_node
2889
      if pnode not in per_node_disks:
2890
        per_node_disks[pnode] = []
2891
      for idx, disk in enumerate(instance.disks):
2892
        per_node_disks[pnode].append((instance, idx, disk))
2893

    
2894
    changed = []
2895
    for node, dskl in per_node_disks.items():
2896
      newl = [v[2].Copy() for v in dskl]
2897
      for dsk in newl:
2898
        self.cfg.SetDiskID(dsk, node)
2899
      result = self.rpc.call_blockdev_getsize(node, newl)
2900
      if result.fail_msg:
2901
        self.LogWarning("Failure in blockdev_getsize call to node"
2902
                        " %s, ignoring", node)
2903
        continue
2904
      if len(result.payload) != len(dskl):
2905
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2906
                        " result.payload=%s", node, len(dskl), result.payload)
2907
        self.LogWarning("Invalid result from node %s, ignoring node results",
2908
                        node)
2909
        continue
2910
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2911
        if size is None:
2912
          self.LogWarning("Disk %d of instance %s did not return size"
2913
                          " information, ignoring", idx, instance.name)
2914
          continue
2915
        if not isinstance(size, (int, long)):
2916
          self.LogWarning("Disk %d of instance %s did not return valid"
2917
                          " size information, ignoring", idx, instance.name)
2918
          continue
2919
        size = size >> 20
2920
        if size != disk.size:
2921
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2922
                       " correcting: recorded %d, actual %d", idx,
2923
                       instance.name, disk.size, size)
2924
          disk.size = size
2925
          self.cfg.Update(instance, feedback_fn)
2926
          changed.append((instance.name, idx, size))
2927
        if self._EnsureChildSizes(disk):
2928
          self.cfg.Update(instance, feedback_fn)
2929
          changed.append((instance.name, idx, disk.size))
2930
    return changed
2931

    
2932

    
2933
class LUClusterRename(LogicalUnit):
2934
  """Rename the cluster.
2935

2936
  """
2937
  HPATH = "cluster-rename"
2938
  HTYPE = constants.HTYPE_CLUSTER
2939

    
2940
  def BuildHooksEnv(self):
2941
    """Build hooks env.
2942

2943
    """
2944
    return {
2945
      "OP_TARGET": self.cfg.GetClusterName(),
2946
      "NEW_NAME": self.op.name,
2947
      }
2948

    
2949
  def BuildHooksNodes(self):
2950
    """Build hooks nodes.
2951

2952
    """
2953
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
2954

    
2955
  def CheckPrereq(self):
2956
    """Verify that the passed name is a valid one.
2957

2958
    """
2959
    hostname = netutils.GetHostname(name=self.op.name,
2960
                                    family=self.cfg.GetPrimaryIPFamily())
2961

    
2962
    new_name = hostname.name
2963
    self.ip = new_ip = hostname.ip
2964
    old_name = self.cfg.GetClusterName()
2965
    old_ip = self.cfg.GetMasterIP()
2966
    if new_name == old_name and new_ip == old_ip:
2967
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2968
                                 " cluster has changed",
2969
                                 errors.ECODE_INVAL)
2970
    if new_ip != old_ip:
2971
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2972
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2973
                                   " reachable on the network" %
2974
                                   new_ip, errors.ECODE_NOTUNIQUE)
2975

    
2976
    self.op.name = new_name
2977

    
2978
  def Exec(self, feedback_fn):
2979
    """Rename the cluster.
2980

2981
    """
2982
    clustername = self.op.name
2983
    ip = self.ip
2984

    
2985
    # shutdown the master IP
2986
    master = self.cfg.GetMasterNode()
2987
    result = self.rpc.call_node_stop_master(master, False)
2988
    result.Raise("Could not disable the master role")
2989

    
2990
    try:
2991
      cluster = self.cfg.GetClusterInfo()
2992
      cluster.cluster_name = clustername
2993
      cluster.master_ip = ip
2994
      self.cfg.Update(cluster, feedback_fn)
2995

    
2996
      # update the known hosts file
2997
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2998
      node_list = self.cfg.GetOnlineNodeList()
2999
      try:
3000
        node_list.remove(master)
3001
      except ValueError:
3002
        pass
3003
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3004
    finally:
3005
      result = self.rpc.call_node_start_master(master, False, False)
3006
      msg = result.fail_msg
3007
      if msg:
3008
        self.LogWarning("Could not re-enable the master role on"
3009
                        " the master, please restart manually: %s", msg)
3010

    
3011
    return clustername
3012

    
3013

    
3014
class LUClusterSetParams(LogicalUnit):
3015
  """Change the parameters of the cluster.
3016

3017
  """
3018
  HPATH = "cluster-modify"
3019
  HTYPE = constants.HTYPE_CLUSTER
3020
  REQ_BGL = False
3021

    
3022
  def CheckArguments(self):
3023
    """Check parameters
3024

3025
    """
3026
    if self.op.uid_pool:
3027
      uidpool.CheckUidPool(self.op.uid_pool)
3028

    
3029
    if self.op.add_uids:
3030
      uidpool.CheckUidPool(self.op.add_uids)
3031

    
3032
    if self.op.remove_uids:
3033
      uidpool.CheckUidPool(self.op.remove_uids)
3034

    
3035
  def ExpandNames(self):
3036
    # FIXME: in the future maybe other cluster params won't require checking on
3037
    # all nodes to be modified.
3038
    self.needed_locks = {
3039
      locking.LEVEL_NODE: locking.ALL_SET,
3040
    }
3041
    self.share_locks[locking.LEVEL_NODE] = 1
3042

    
3043
  def BuildHooksEnv(self):
3044
    """Build hooks env.
3045

3046
    """
3047
    return {
3048
      "OP_TARGET": self.cfg.GetClusterName(),
3049
      "NEW_VG_NAME": self.op.vg_name,
3050
      }
3051

    
3052
  def BuildHooksNodes(self):
3053
    """Build hooks nodes.
3054

3055
    """
3056
    mn = self.cfg.GetMasterNode()
3057
    return ([mn], [mn])
3058

    
3059
  def CheckPrereq(self):
3060
    """Check prerequisites.
3061

3062
    This checks whether the given params don't conflict and
3063
    if the given volume group is valid.
3064

3065
    """
3066
    if self.op.vg_name is not None and not self.op.vg_name:
3067
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3068
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3069
                                   " instances exist", errors.ECODE_INVAL)
3070

    
3071
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
3072
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3073
        raise errors.OpPrereqError("Cannot disable drbd helper while"
3074
                                   " drbd-based instances exist",
3075
                                   errors.ECODE_INVAL)
3076

    
3077
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
3078

    
3079
    # if vg_name not None, checks given volume group on all nodes
3080
    if self.op.vg_name:
3081
      vglist = self.rpc.call_vg_list(node_list)
3082
      for node in node_list:
3083
        msg = vglist[node].fail_msg
3084
        if msg:
3085
          # ignoring down node
3086
          self.LogWarning("Error while gathering data on node %s"
3087
                          " (ignoring node): %s", node, msg)
3088
          continue
3089
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3090
                                              self.op.vg_name,
3091
                                              constants.MIN_VG_SIZE)
3092
        if vgstatus:
3093
          raise errors.OpPrereqError("Error on node '%s': %s" %
3094
                                     (node, vgstatus), errors.ECODE_ENVIRON)
3095

    
3096
    if self.op.drbd_helper:
3097
      # checks given drbd helper on all nodes
3098
      helpers = self.rpc.call_drbd_helper(node_list)
3099
      for node in node_list:
3100
        ninfo = self.cfg.GetNodeInfo(node)
3101
        if ninfo.offline:
3102
          self.LogInfo("Not checking drbd helper on offline node %s", node)
3103
          continue
3104
        msg = helpers[node].fail_msg
3105
        if msg:
3106
          raise errors.OpPrereqError("Error checking drbd helper on node"
3107
                                     " '%s': %s" % (node, msg),
3108
                                     errors.ECODE_ENVIRON)
3109
        node_helper = helpers[node].payload
3110
        if node_helper != self.op.drbd_helper:
3111
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3112
                                     (node, node_helper), errors.ECODE_ENVIRON)
3113

    
3114
    self.cluster = cluster = self.cfg.GetClusterInfo()
3115
    # validate params changes
3116
    if self.op.beparams:
3117
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3118
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3119

    
3120
    if self.op.ndparams:
3121
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3122
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3123

    
3124
      # TODO: we need a more general way to handle resetting
3125
      # cluster-level parameters to default values
3126
      if self.new_ndparams["oob_program"] == "":
3127
        self.new_ndparams["oob_program"] = \
3128
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3129

    
3130
    if self.op.nicparams:
3131
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3132
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3133
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3134
      nic_errors = []
3135

    
3136
      # check all instances for consistency
3137
      for instance in self.cfg.GetAllInstancesInfo().values():
3138
        for nic_idx, nic in enumerate(instance.nics):
3139
          params_copy = copy.deepcopy(nic.nicparams)
3140
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3141

    
3142
          # check parameter syntax
3143
          try:
3144
            objects.NIC.CheckParameterSyntax(params_filled)
3145
          except errors.ConfigurationError, err:
3146
            nic_errors.append("Instance %s, nic/%d: %s" %
3147
                              (instance.name, nic_idx, err))
3148

    
3149
          # if we're moving instances to routed, check that they have an ip
3150
          target_mode = params_filled[constants.NIC_MODE]
3151
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3152
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3153
                              " address" % (instance.name, nic_idx))
3154
      if nic_errors:
3155
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3156
                                   "\n".join(nic_errors))
3157

    
3158
    # hypervisor list/parameters
3159
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3160
    if self.op.hvparams:
3161
      for hv_name, hv_dict in self.op.hvparams.items():
3162
        if hv_name not in self.new_hvparams:
3163
          self.new_hvparams[hv_name] = hv_dict
3164
        else:
3165
          self.new_hvparams[hv_name].update(hv_dict)
3166

    
3167
    # os hypervisor parameters
3168
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3169
    if self.op.os_hvp:
3170
      for os_name, hvs in self.op.os_hvp.items():
3171
        if os_name not in self.new_os_hvp:
3172
          self.new_os_hvp[os_name] = hvs
3173
        else:
3174
          for hv_name, hv_dict in hvs.items():
3175
            if hv_name not in self.new_os_hvp[os_name]:
3176
              self.new_os_hvp[os_name][hv_name] = hv_dict
3177
            else:
3178
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3179

    
3180
    # os parameters
3181
    self.new_osp = objects.FillDict(cluster.osparams, {})
3182
    if self.op.osparams:
3183
      for os_name, osp in self.op.osparams.items():
3184
        if os_name not in self.new_osp:
3185
          self.new_osp[os_name] = {}
3186

    
3187
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3188
                                                  use_none=True)
3189

    
3190
        if not self.new_osp[os_name]:
3191
          # we removed all parameters
3192
          del self.new_osp[os_name]
3193
        else:
3194
          # check the parameter validity (remote check)
3195
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3196
                         os_name, self.new_osp[os_name])
3197

    
3198
    # changes to the hypervisor list
3199
    if self.op.enabled_hypervisors is not None:
3200
      self.hv_list = self.op.enabled_hypervisors
3201
      for hv in self.hv_list:
3202
        # if the hypervisor doesn't already exist in the cluster
3203
        # hvparams, we initialize it to empty, and then (in both
3204
        # cases) we make sure to fill the defaults, as we might not
3205
        # have a complete defaults list if the hypervisor wasn't
3206
        # enabled before
3207
        if hv not in new_hvp:
3208
          new_hvp[hv] = {}
3209
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3210
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3211
    else:
3212
      self.hv_list = cluster.enabled_hypervisors
3213

    
3214
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3215
      # either the enabled list has changed, or the parameters have, validate
3216
      for hv_name, hv_params in self.new_hvparams.items():
3217
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3218
            (self.op.enabled_hypervisors and
3219
             hv_name in self.op.enabled_hypervisors)):
3220
          # either this is a new hypervisor, or its parameters have changed
3221
          hv_class = hypervisor.GetHypervisor(hv_name)
3222
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3223
          hv_class.CheckParameterSyntax(hv_params)
3224
          _CheckHVParams(self, node_list, hv_name, hv_params)
3225

    
3226
    if self.op.os_hvp:
3227
      # no need to check any newly-enabled hypervisors, since the
3228
      # defaults have already been checked in the above code-block
3229
      for os_name, os_hvp in self.new_os_hvp.items():
3230
        for hv_name, hv_params in os_hvp.items():
3231
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3232
          # we need to fill in the new os_hvp on top of the actual hv_p
3233
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3234
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3235
          hv_class = hypervisor.GetHypervisor(hv_name)
3236
          hv_class.CheckParameterSyntax(new_osp)
3237
          _CheckHVParams(self, node_list, hv_name, new_osp)
3238

    
3239
    if self.op.default_iallocator:
3240
      alloc_script = utils.FindFile(self.op.default_iallocator,
3241
                                    constants.IALLOCATOR_SEARCH_PATH,
3242
                                    os.path.isfile)
3243
      if alloc_script is None:
3244
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3245
                                   " specified" % self.op.default_iallocator,
3246
                                   errors.ECODE_INVAL)
3247

    
3248
  def Exec(self, feedback_fn):
3249
    """Change the parameters of the cluster.
3250

3251
    """
3252
    if self.op.vg_name is not None:
3253
      new_volume = self.op.vg_name
3254
      if not new_volume:
3255
        new_volume = None
3256
      if new_volume != self.cfg.GetVGName():
3257
        self.cfg.SetVGName(new_volume)
3258
      else:
3259
        feedback_fn("Cluster LVM configuration already in desired"
3260
                    " state, not changing")
3261
    if self.op.drbd_helper is not None:
3262
      new_helper = self.op.drbd_helper
3263
      if not new_helper:
3264
        new_helper = None
3265
      if new_helper != self.cfg.GetDRBDHelper():
3266
        self.cfg.SetDRBDHelper(new_helper)
3267
      else:
3268
        feedback_fn("Cluster DRBD helper already in desired state,"
3269
                    " not changing")
3270
    if self.op.hvparams:
3271
      self.cluster.hvparams = self.new_hvparams
3272
    if self.op.os_hvp:
3273
      self.cluster.os_hvp = self.new_os_hvp
3274
    if self.op.enabled_hypervisors is not None:
3275
      self.cluster.hvparams = self.new_hvparams
3276
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3277
    if self.op.beparams:
3278
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3279
    if self.op.nicparams:
3280
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3281
    if self.op.osparams:
3282
      self.cluster.osparams = self.new_osp
3283
    if self.op.ndparams:
3284
      self.cluster.ndparams = self.new_ndparams
3285

    
3286
    if self.op.candidate_pool_size is not None:
3287
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3288
      # we need to update the pool size here, otherwise the save will fail
3289
      _AdjustCandidatePool(self, [])
3290

    
3291
    if self.op.maintain_node_health is not None:
3292
      self.cluster.maintain_node_health = self.op.maintain_node_health
3293

    
3294
    if self.op.prealloc_wipe_disks is not None:
3295
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3296

    
3297
    if self.op.add_uids is not None:
3298
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3299

    
3300
    if self.op.remove_uids is not None:
3301
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3302

    
3303
    if self.op.uid_pool is not None:
3304
      self.cluster.uid_pool = self.op.uid_pool
3305

    
3306
    if self.op.default_iallocator is not None:
3307
      self.cluster.default_iallocator = self.op.default_iallocator
3308

    
3309
    if self.op.reserved_lvs is not None:
3310
      self.cluster.reserved_lvs = self.op.reserved_lvs
3311

    
3312
    def helper_os(aname, mods, desc):
3313
      desc += " OS list"
3314
      lst = getattr(self.cluster, aname)
3315
      for key, val in mods:
3316
        if key == constants.DDM_ADD:
3317
          if val in lst:
3318
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3319
          else:
3320
            lst.append(val)
3321
        elif key == constants.DDM_REMOVE:
3322
          if val in lst:
3323
            lst.remove(val)
3324
          else:
3325
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3326
        else:
3327
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3328

    
3329
    if self.op.hidden_os:
3330
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3331

    
3332
    if self.op.blacklisted_os:
3333
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3334

    
3335
    if self.op.master_netdev:
3336
      master = self.cfg.GetMasterNode()
3337
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3338
                  self.cluster.master_netdev)
3339
      result = self.rpc.call_node_stop_master(master, False)
3340
      result.Raise("Could not disable the master ip")
3341
      feedback_fn("Changing master_netdev from %s to %s" %
3342
                  (self.cluster.master_netdev, self.op.master_netdev))
3343
      self.cluster.master_netdev = self.op.master_netdev
3344

    
3345
    self.cfg.Update(self.cluster, feedback_fn)
3346

    
3347
    if self.op.master_netdev:
3348
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3349
                  self.op.master_netdev)
3350
      result = self.rpc.call_node_start_master(master, False, False)
3351
      if result.fail_msg:
3352
        self.LogWarning("Could not re-enable the master ip on"
3353
                        " the master, please restart manually: %s",
3354
                        result.fail_msg)
3355

    
3356

    
3357
def _UploadHelper(lu, nodes, fname):
3358
  """Helper for uploading a file and showing warnings.
3359

3360
  """
3361
  if os.path.exists(fname):
3362
    result = lu.rpc.call_upload_file(nodes, fname)
3363
    for to_node, to_result in result.items():
3364
      msg = to_result.fail_msg
3365
      if msg:
3366
        msg = ("Copy of file %s to node %s failed: %s" %
3367
               (fname, to_node, msg))
3368
        lu.proc.LogWarning(msg)
3369

    
3370

    
3371
def _ComputeAncillaryFiles(cluster, redist):
3372
  """Compute files external to Ganeti which need to be consistent.
3373

3374
  @type redist: boolean
3375
  @param redist: Whether to include files which need to be redistributed
3376

3377
  """
3378
  # Compute files for all nodes
3379
  files_all = set([
3380
    constants.SSH_KNOWN_HOSTS_FILE,
3381
    constants.CONFD_HMAC_KEY,
3382
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3383
    ])
3384

    
3385
  if not redist:
3386
    files_all.update(constants.ALL_CERT_FILES)
3387
    files_all.update(ssconf.SimpleStore().GetFileList())
3388

    
3389
  if cluster.modify_etc_hosts:
3390
    files_all.add(constants.ETC_HOSTS)
3391

    
3392
  # Files which must either exist on all nodes or on none
3393
  files_all_opt = set([
3394
    constants.RAPI_USERS_FILE,
3395
    ])
3396

    
3397
  # Files which should only be on master candidates
3398
  files_mc = set()
3399
  if not redist:
3400
    files_mc.add(constants.CLUSTER_CONF_FILE)
3401

    
3402
  # Files which should only be on VM-capable nodes
3403
  files_vm = set(filename
3404
    for hv_name in cluster.enabled_hypervisors
3405
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3406

    
3407
  # Filenames must be unique
3408
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3409
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3410
         "Found file listed in more than one file list"
3411

    
3412
  return (files_all, files_all_opt, files_mc, files_vm)
3413

    
3414

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

3418
  ConfigWriter takes care of distributing the config and ssconf files, but
3419
  there are more files which should be distributed to all nodes. This function
3420
  makes sure those are copied.
3421

3422
  @param lu: calling logical unit
3423
  @param additional_nodes: list of nodes not in the config to distribute to
3424
  @type additional_vm: boolean
3425
  @param additional_vm: whether the additional nodes are vm-capable or not
3426

3427
  """
3428
  # Gather target nodes
3429
  cluster = lu.cfg.GetClusterInfo()
3430
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3431

    
3432
  online_nodes = lu.cfg.GetOnlineNodeList()
3433
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3434

    
3435
  if additional_nodes is not None:
3436
    online_nodes.extend(additional_nodes)
3437
    if additional_vm:
3438
      vm_nodes.extend(additional_nodes)
3439

    
3440
  # Never distribute to master node
3441
  for nodelist in [online_nodes, vm_nodes]:
3442
    if master_info.name in nodelist:
3443
      nodelist.remove(master_info.name)
3444

    
3445
  # Gather file lists
3446
  (files_all, files_all_opt, files_mc, files_vm) = \
3447
    _ComputeAncillaryFiles(cluster, True)
3448

    
3449
  # Never re-distribute configuration file from here
3450
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3451
              constants.CLUSTER_CONF_FILE in files_vm)
3452
  assert not files_mc, "Master candidates not handled in this function"
3453

    
3454
  filemap = [
3455
    (online_nodes, files_all),
3456
    (online_nodes, files_all_opt),
3457
    (vm_nodes, files_vm),
3458
    ]
3459

    
3460
  # Upload the files
3461
  for (node_list, files) in filemap:
3462
    for fname in files:
3463
      _UploadHelper(lu, node_list, fname)
3464

    
3465

    
3466
class LUClusterRedistConf(NoHooksLU):
3467
  """Force the redistribution of cluster configuration.
3468

3469
  This is a very simple LU.
3470

3471
  """
3472
  REQ_BGL = False
3473

    
3474
  def ExpandNames(self):
3475
    self.needed_locks = {
3476
      locking.LEVEL_NODE: locking.ALL_SET,
3477
    }
3478
    self.share_locks[locking.LEVEL_NODE] = 1
3479

    
3480
  def Exec(self, feedback_fn):
3481
    """Redistribute the configuration.
3482

3483
    """
3484
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3485
    _RedistributeAncillaryFiles(self)
3486

    
3487

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

3491
  """
3492
  if not instance.disks or disks is not None and not disks:
3493
    return True
3494

    
3495
  disks = _ExpandCheckDisks(instance, disks)
3496

    
3497
  if not oneshot:
3498
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3499

    
3500
  node = instance.primary_node
3501

    
3502
  for dev in disks:
3503
    lu.cfg.SetDiskID(dev, node)
3504

    
3505
  # TODO: Convert to utils.Retry
3506

    
3507
  retries = 0
3508
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3509
  while True:
3510
    max_time = 0
3511
    done = True
3512
    cumul_degraded = False
3513
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3514
    msg = rstats.fail_msg
3515
    if msg:
3516
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3517
      retries += 1
3518
      if retries >= 10:
3519
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3520
                                 " aborting." % node)
3521
      time.sleep(6)
3522
      continue
3523
    rstats = rstats.payload
3524
    retries = 0
3525
    for i, mstat in enumerate(rstats):
3526
      if mstat is None:
3527
        lu.LogWarning("Can't compute data for node %s/%s",
3528
                           node, disks[i].iv_name)
3529
        continue
3530

    
3531
      cumul_degraded = (cumul_degraded or
3532
                        (mstat.is_degraded and mstat.sync_percent is None))
3533
      if mstat.sync_percent is not None:
3534
        done = False
3535
        if mstat.estimated_time is not None:
3536
          rem_time = ("%s remaining (estimated)" %
3537
                      utils.FormatSeconds(mstat.estimated_time))
3538
          max_time = mstat.estimated_time
3539
        else:
3540
          rem_time = "no time estimate"
3541
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3542
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3543

    
3544
    # if we're done but degraded, let's do a few small retries, to
3545
    # make sure we see a stable and not transient situation; therefore
3546
    # we force restart of the loop
3547
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3548
      logging.info("Degraded disks found, %d retries left", degr_retries)
3549
      degr_retries -= 1
3550
      time.sleep(1)
3551
      continue
3552

    
3553
    if done or oneshot:
3554
      break
3555

    
3556
    time.sleep(min(60, max_time))
3557

    
3558
  if done:
3559
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3560
  return not cumul_degraded
3561

    
3562

    
3563
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3564
  """Check that mirrors are not degraded.
3565

3566
  The ldisk parameter, if True, will change the test from the
3567
  is_degraded attribute (which represents overall non-ok status for
3568
  the device(s)) to the ldisk (representing the local storage status).
3569

3570
  """
3571
  lu.cfg.SetDiskID(dev, node)
3572

    
3573
  result = True
3574

    
3575
  if on_primary or dev.AssembleOnSecondary():
3576
    rstats = lu.rpc.call_blockdev_find(node, dev)
3577
    msg = rstats.fail_msg
3578
    if msg:
3579
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3580
      result = False
3581
    elif not rstats.payload:
3582
      lu.LogWarning("Can't find disk on node %s", node)
3583
      result = False
3584
    else:
3585
      if ldisk:
3586
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3587
      else:
3588
        result = result and not rstats.payload.is_degraded
3589

    
3590
  if dev.children:
3591
    for child in dev.children:
3592
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3593

    
3594
  return result
3595

    
3596

    
3597
class LUOobCommand(NoHooksLU):
3598
  """Logical unit for OOB handling.
3599

3600
  """
3601
  REG_BGL = False
3602
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3603

    
3604
  def ExpandNames(self):
3605
    """Gather locks we need.
3606

3607
    """
3608
    if self.op.node_names:
3609
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3610
      lock_names = self.op.node_names
3611
    else:
3612
      lock_names = locking.ALL_SET
3613

    
3614
    self.needed_locks = {
3615
      locking.LEVEL_NODE: lock_names,
3616
      }
3617

    
3618
  def CheckPrereq(self):
3619
    """Check prerequisites.
3620

3621
    This checks:
3622
     - the node exists in the configuration
3623
     - OOB is supported
3624

3625
    Any errors are signaled by raising errors.OpPrereqError.
3626

3627
    """
3628
    self.nodes = []
3629
    self.master_node = self.cfg.GetMasterNode()
3630

    
3631
    assert self.op.power_delay >= 0.0
3632

    
3633
    if self.op.node_names:
3634
      if (self.op.command in self._SKIP_MASTER and
3635
          self.master_node in self.op.node_names):
3636
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3637
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3638

    
3639
        if master_oob_handler:
3640
          additional_text = ("run '%s %s %s' if you want to operate on the"
3641
                             " master regardless") % (master_oob_handler,
3642
                                                      self.op.command,
3643
                                                      self.master_node)
3644
        else:
3645
          additional_text = "it does not support out-of-band operations"
3646

    
3647
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3648
                                    " allowed for %s; %s") %
3649
                                   (self.master_node, self.op.command,
3650
                                    additional_text), errors.ECODE_INVAL)
3651
    else:
3652
      self.op.node_names = self.cfg.GetNodeList()
3653
      if self.op.command in self._SKIP_MASTER:
3654
        self.op.node_names.remove(self.master_node)
3655

    
3656
    if self.op.command in self._SKIP_MASTER:
3657
      assert self.master_node not in self.op.node_names
3658

    
3659
    for node_name in self.op.node_names:
3660
      node = self.cfg.GetNodeInfo(node_name)
3661

    
3662
      if node is None:
3663
        raise errors.OpPrereqError("Node %s not found" % node_name,
3664
                                   errors.ECODE_NOENT)
3665
      else:
3666
        self.nodes.append(node)
3667

    
3668
      if (not self.op.ignore_status and
3669
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3670
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3671
                                    " not marked offline") % node_name,
3672
                                   errors.ECODE_STATE)
3673

    
3674
  def Exec(self, feedback_fn):
3675
    """Execute OOB and return result if we expect any.
3676

3677
    """
3678
    master_node = self.master_node
3679
    ret = []
3680

    
3681
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3682
                                              key=lambda node: node.name)):
3683
      node_entry = [(constants.RS_NORMAL, node.name)]
3684
      ret.append(node_entry)
3685

    
3686
      oob_program = _SupportsOob(self.cfg, node)
3687

    
3688
      if not oob_program:
3689
        node_entry.append((constants.RS_UNAVAIL, None))
3690
        continue
3691

    
3692
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3693
                   self.op.command, oob_program, node.name)
3694
      result = self.rpc.call_run_oob(master_node, oob_program,
3695
                                     self.op.command, node.name,
3696
                                     self.op.timeout)
3697

    
3698
      if result.fail_msg:
3699
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3700
                        node.name, result.fail_msg)
3701
        node_entry.append((constants.RS_NODATA, None))
3702
      else:
3703
        try:
3704
          self._CheckPayload(result)
3705
        except errors.OpExecError, err:
3706
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3707
                          node.name, err)
3708
          node_entry.append((constants.RS_NODATA, None))
3709
        else:
3710
          if self.op.command == constants.OOB_HEALTH:
3711
            # For health we should log important events
3712
            for item, status in result.payload:
3713
              if status in [constants.OOB_STATUS_WARNING,
3714
                            constants.OOB_STATUS_CRITICAL]:
3715
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3716
                                item, node.name, status)
3717

    
3718
          if self.op.command == constants.OOB_POWER_ON:
3719
            node.powered = True
3720
          elif self.op.command == constants.OOB_POWER_OFF:
3721
            node.powered = False
3722
          elif self.op.command == constants.OOB_POWER_STATUS:
3723
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3724
            if powered != node.powered:
3725
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3726
                               " match actual power state (%s)"), node.powered,
3727
                              node.name, powered)
3728

    
3729
          # For configuration changing commands we should update the node
3730
          if self.op.command in (constants.OOB_POWER_ON,
3731
                                 constants.OOB_POWER_OFF):
3732
            self.cfg.Update(node, feedback_fn)
3733

    
3734
          node_entry.append((constants.RS_NORMAL, result.payload))
3735

    
3736
          if (self.op.command == constants.OOB_POWER_ON and
3737
              idx < len(self.nodes) - 1):
3738
            time.sleep(self.op.power_delay)
3739

    
3740
    return ret
3741

    
3742
  def _CheckPayload(self, result):
3743
    """Checks if the payload is valid.
3744

3745
    @param result: RPC result
3746
    @raises errors.OpExecError: If payload is not valid
3747

3748
    """
3749
    errs = []
3750
    if self.op.command == constants.OOB_HEALTH:
3751
      if not isinstance(result.payload, list):
3752
        errs.append("command 'health' is expected to return a list but got %s" %
3753
                    type(result.payload))
3754
      else:
3755
        for item, status in result.payload:
3756
          if status not in constants.OOB_STATUSES:
3757
            errs.append("health item '%s' has invalid status '%s'" %
3758
                        (item, status))
3759

    
3760
    if self.op.command == constants.OOB_POWER_STATUS:
3761
      if not isinstance(result.payload, dict):
3762
        errs.append("power-status is expected to return a dict but got %s" %
3763
                    type(result.payload))
3764

    
3765
    if self.op.command in [
3766
        constants.OOB_POWER_ON,
3767
        constants.OOB_POWER_OFF,
3768
        constants.OOB_POWER_CYCLE,
3769
        ]:
3770
      if result.payload is not None:
3771
        errs.append("%s is expected to not return payload but got '%s'" %
3772
                    (self.op.command, result.payload))
3773

    
3774
    if errs:
3775
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3776
                               utils.CommaJoin(errs))
3777

    
3778
class _OsQuery(_QueryBase):
3779
  FIELDS = query.OS_FIELDS
3780

    
3781
  def ExpandNames(self, lu):
3782
    # Lock all nodes in shared mode
3783
    # Temporary removal of locks, should be reverted later
3784
    # TODO: reintroduce locks when they are lighter-weight
3785
    lu.needed_locks = {}
3786
    #self.share_locks[locking.LEVEL_NODE] = 1
3787
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3788

    
3789
    # The following variables interact with _QueryBase._GetNames
3790
    if self.names:
3791
      self.wanted = self.names
3792
    else:
3793
      self.wanted = locking.ALL_SET
3794

    
3795
    self.do_locking = self.use_locking
3796

    
3797
  def DeclareLocks(self, lu, level):
3798
    pass
3799

    
3800
  @staticmethod
3801
  def _DiagnoseByOS(rlist):
3802
    """Remaps a per-node return list into an a per-os per-node dictionary
3803

3804
    @param rlist: a map with node names as keys and OS objects as values
3805

3806
    @rtype: dict
3807
    @return: a dictionary with osnames as keys and as value another
3808
        map, with nodes as keys and tuples of (path, status, diagnose,
3809
        variants, parameters, api_versions) as values, eg::
3810

3811
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3812
                                     (/srv/..., False, "invalid api")],
3813
                           "node2": [(/srv/..., True, "", [], [])]}
3814
          }
3815

3816
    """
3817
    all_os = {}
3818
    # we build here the list of nodes that didn't fail the RPC (at RPC
3819
    # level), so that nodes with a non-responding node daemon don't
3820
    # make all OSes invalid
3821
    good_nodes = [node_name for node_name in rlist
3822
                  if not rlist[node_name].fail_msg]
3823
    for node_name, nr in rlist.items():
3824
      if nr.fail_msg or not nr.payload:
3825
        continue
3826
      for (name, path, status, diagnose, variants,
3827
           params, api_versions) in nr.payload:
3828
        if name not in all_os:
3829
          # build a list of nodes for this os containing empty lists
3830
          # for each node in node_list
3831
          all_os[name] = {}
3832
          for nname in good_nodes:
3833
            all_os[name][nname] = []
3834
        # convert params from [name, help] to (name, help)
3835
        params = [tuple(v) for v in params]
3836
        all_os[name][node_name].append((path, status, diagnose,
3837
                                        variants, params, api_versions))
3838
    return all_os
3839

    
3840
  def _GetQueryData(self, lu):
3841
    """Computes the list of nodes and their attributes.
3842

3843
    """
3844
    # Locking is not used
3845
    assert not (compat.any(lu.glm.is_owned(level)
3846
                           for level in locking.LEVELS
3847
                           if level != locking.LEVEL_CLUSTER) or
3848
                self.do_locking or self.use_locking)
3849

    
3850
    valid_nodes = [node.name
3851
                   for node in lu.cfg.GetAllNodesInfo().values()
3852
                   if not node.offline and node.vm_capable]
3853
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3854
    cluster = lu.cfg.GetClusterInfo()
3855

    
3856
    data = {}
3857

    
3858
    for (os_name, os_data) in pol.items():
3859
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3860
                          hidden=(os_name in cluster.hidden_os),
3861
                          blacklisted=(os_name in cluster.blacklisted_os))
3862

    
3863
      variants = set()
3864
      parameters = set()
3865
      api_versions = set()
3866

    
3867
      for idx, osl in enumerate(os_data.values()):
3868
        info.valid = bool(info.valid and osl and osl[0][1])
3869
        if not info.valid:
3870
          break
3871

    
3872
        (node_variants, node_params, node_api) = osl[0][3:6]
3873
        if idx == 0:
3874
          # First entry
3875
          variants.update(node_variants)
3876
          parameters.update(node_params)
3877
          api_versions.update(node_api)
3878
        else:
3879
          # Filter out inconsistent values
3880
          variants.intersection_update(node_variants)
3881
          parameters.intersection_update(node_params)
3882
          api_versions.intersection_update(node_api)
3883

    
3884
      info.variants = list(variants)
3885
      info.parameters = list(parameters)
3886
      info.api_versions = list(api_versions)
3887

    
3888
      data[os_name] = info
3889

    
3890
    # Prepare data in requested order
3891
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3892
            if name in data]
3893

    
3894

    
3895
class LUOsDiagnose(NoHooksLU):
3896
  """Logical unit for OS diagnose/query.
3897

3898
  """
3899
  REQ_BGL = False
3900

    
3901
  @staticmethod
3902
  def _BuildFilter(fields, names):
3903
    """Builds a filter for querying OSes.
3904

3905
    """
3906
    name_filter = qlang.MakeSimpleFilter("name", names)
3907

    
3908
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
3909
    # respective field is not requested
3910
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
3911
                     for fname in ["hidden", "blacklisted"]
3912
                     if fname not in fields]
3913
    if "valid" not in fields:
3914
      status_filter.append([qlang.OP_TRUE, "valid"])
3915

    
3916
    if status_filter:
3917
      status_filter.insert(0, qlang.OP_AND)
3918
    else:
3919
      status_filter = None
3920

    
3921
    if name_filter and status_filter:
3922
      return [qlang.OP_AND, name_filter, status_filter]
3923
    elif name_filter:
3924
      return name_filter
3925
    else:
3926
      return status_filter
3927

    
3928
  def CheckArguments(self):
3929
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
3930
                       self.op.output_fields, False)
3931

    
3932
  def ExpandNames(self):
3933
    self.oq.ExpandNames(self)
3934

    
3935
  def Exec(self, feedback_fn):
3936
    return self.oq.OldStyleQuery(self)
3937

    
3938

    
3939
class LUNodeRemove(LogicalUnit):
3940
  """Logical unit for removing a node.
3941

3942
  """
3943
  HPATH = "node-remove"
3944
  HTYPE = constants.HTYPE_NODE
3945

    
3946
  def BuildHooksEnv(self):
3947
    """Build hooks env.
3948

3949
    This doesn't run on the target node in the pre phase as a failed
3950
    node would then be impossible to remove.
3951

3952
    """
3953
    return {
3954
      "OP_TARGET": self.op.node_name,
3955
      "NODE_NAME": self.op.node_name,
3956
      }
3957

    
3958
  def BuildHooksNodes(self):
3959
    """Build hooks nodes.
3960

3961
    """
3962
    all_nodes = self.cfg.GetNodeList()
3963
    try:
3964
      all_nodes.remove(self.op.node_name)
3965
    except ValueError:
3966
      logging.warning("Node '%s', which is about to be removed, was not found"
3967
                      " in the list of all nodes", self.op.node_name)
3968
    return (all_nodes, all_nodes)
3969

    
3970
  def CheckPrereq(self):
3971
    """Check prerequisites.
3972

3973
    This checks:
3974
     - the node exists in the configuration
3975
     - it does not have primary or secondary instances
3976
     - it's not the master
3977

3978
    Any errors are signaled by raising errors.OpPrereqError.
3979

3980
    """
3981
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3982
    node = self.cfg.GetNodeInfo(self.op.node_name)
3983
    assert node is not None
3984

    
3985
    instance_list = self.cfg.GetInstanceList()
3986

    
3987
    masternode = self.cfg.GetMasterNode()
3988
    if node.name == masternode:
3989
      raise errors.OpPrereqError("Node is the master node, failover to another"
3990
                                 " node is required", errors.ECODE_INVAL)
3991

    
3992
    for instance_name in instance_list:
3993
      instance = self.cfg.GetInstanceInfo(instance_name)
3994
      if node.name in instance.all_nodes:
3995
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3996
                                   " please remove first" % instance_name,
3997
                                   errors.ECODE_INVAL)
3998
    self.op.node_name = node.name
3999
    self.node = node
4000

    
4001
  def Exec(self, feedback_fn):
4002
    """Removes the node from the cluster.
4003

4004
    """
4005
    node = self.node
4006
    logging.info("Stopping the node daemon and removing configs from node %s",
4007
                 node.name)
4008

    
4009
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
4010

    
4011
    # Promote nodes to master candidate as needed
4012
    _AdjustCandidatePool(self, exceptions=[node.name])
4013
    self.context.RemoveNode(node.name)
4014

    
4015
    # Run post hooks on the node before it's removed
4016
    _RunPostHook(self, node.name)
4017

    
4018
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
4019
    msg = result.fail_msg
4020
    if msg:
4021
      self.LogWarning("Errors encountered on the remote node while leaving"
4022
                      " the cluster: %s", msg)
4023

    
4024
    # Remove node from our /etc/hosts
4025
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4026
      master_node = self.cfg.GetMasterNode()
4027
      result = self.rpc.call_etc_hosts_modify(master_node,
4028
                                              constants.ETC_HOSTS_REMOVE,
4029
                                              node.name, None)
4030
      result.Raise("Can't update hosts file with new host data")
4031
      _RedistributeAncillaryFiles(self)
4032

    
4033

    
4034
class _NodeQuery(_QueryBase):
4035
  FIELDS = query.NODE_FIELDS
4036

    
4037
  def ExpandNames(self, lu):
4038
    lu.needed_locks = {}
4039
    lu.share_locks[locking.LEVEL_NODE] = 1
4040

    
4041
    if self.names:
4042
      self.wanted = _GetWantedNodes(lu, self.names)
4043
    else:
4044
      self.wanted = locking.ALL_SET
4045

    
4046
    self.do_locking = (self.use_locking and
4047
                       query.NQ_LIVE in self.requested_data)
4048

    
4049
    if self.do_locking:
4050
      # if we don't request only static fields, we need to lock the nodes
4051
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
4052

    
4053
  def DeclareLocks(self, lu, level):
4054
    pass
4055

    
4056
  def _GetQueryData(self, lu):
4057
    """Computes the list of nodes and their attributes.
4058

4059
    """
4060
    all_info = lu.cfg.GetAllNodesInfo()
4061

    
4062
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
4063

    
4064
    # Gather data as requested
4065
    if query.NQ_LIVE in self.requested_data:
4066
      # filter out non-vm_capable nodes
4067
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
4068

    
4069
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
4070
                                        lu.cfg.GetHypervisorType())
4071
      live_data = dict((name, nresult.payload)
4072
                       for (name, nresult) in node_data.items()
4073
                       if not nresult.fail_msg and nresult.payload)
4074
    else:
4075
      live_data = None
4076

    
4077
    if query.NQ_INST in self.requested_data:
4078
      node_to_primary = dict([(name, set()) for name in nodenames])
4079
      node_to_secondary = dict([(name, set()) for name in nodenames])
4080

    
4081
      inst_data = lu.cfg.GetAllInstancesInfo()
4082

    
4083
      for inst in inst_data.values():
4084
        if inst.primary_node in node_to_primary:
4085
          node_to_primary[inst.primary_node].add(inst.name)
4086
        for secnode in inst.secondary_nodes:
4087
          if secnode in node_to_secondary:
4088
            node_to_secondary[secnode].add(inst.name)
4089
    else:
4090
      node_to_primary = None
4091
      node_to_secondary = None
4092

    
4093
    if query.NQ_OOB in self.requested_data:
4094
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
4095
                         for name, node in all_info.iteritems())
4096
    else:
4097
      oob_support = None
4098

    
4099
    if query.NQ_GROUP in self.requested_data:
4100
      groups = lu.cfg.GetAllNodeGroupsInfo()
4101
    else:
4102
      groups = {}
4103

    
4104
    return query.NodeQueryData([all_info[name] for name in nodenames],
4105
                               live_data, lu.cfg.GetMasterNode(),
4106
                               node_to_primary, node_to_secondary, groups,
4107
                               oob_support, lu.cfg.GetClusterInfo())
4108

    
4109

    
4110
class LUNodeQuery(NoHooksLU):
4111
  """Logical unit for querying nodes.
4112

4113
  """
4114
  # pylint: disable-msg=W0142
4115
  REQ_BGL = False
4116

    
4117
  def CheckArguments(self):
4118
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4119
                         self.op.output_fields, self.op.use_locking)
4120

    
4121
  def ExpandNames(self):
4122
    self.nq.ExpandNames(self)
4123

    
4124
  def Exec(self, feedback_fn):
4125
    return self.nq.OldStyleQuery(self)
4126

    
4127

    
4128
class LUNodeQueryvols(NoHooksLU):
4129
  """Logical unit for getting volumes on node(s).
4130

4131
  """
4132
  REQ_BGL = False
4133
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4134
  _FIELDS_STATIC = utils.FieldSet("node")
4135

    
4136
  def CheckArguments(self):
4137
    _CheckOutputFields(static=self._FIELDS_STATIC,
4138
                       dynamic=self._FIELDS_DYNAMIC,
4139
                       selected=self.op.output_fields)
4140

    
4141
  def ExpandNames(self):
4142
    self.needed_locks = {}
4143
    self.share_locks[locking.LEVEL_NODE] = 1
4144
    if not self.op.nodes:
4145
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4146
    else:
4147
      self.needed_locks[locking.LEVEL_NODE] = \
4148
        _GetWantedNodes(self, self.op.nodes)
4149

    
4150
  def Exec(self, feedback_fn):
4151
    """Computes the list of nodes and their attributes.
4152

4153
    """
4154
    nodenames = self.glm.list_owned(locking.LEVEL_NODE)
4155
    volumes = self.rpc.call_node_volumes(nodenames)
4156

    
4157
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
4158
             in self.cfg.GetInstanceList()]
4159

    
4160
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
4161

    
4162
    output = []
4163
    for node in nodenames:
4164
      nresult = volumes[node]
4165
      if nresult.offline:
4166
        continue
4167
      msg = nresult.fail_msg
4168
      if msg:
4169
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4170
        continue
4171

    
4172
      node_vols = nresult.payload[:]
4173
      node_vols.sort(key=lambda vol: vol['dev'])
4174

    
4175
      for vol in node_vols:
4176
        node_output = []
4177
        for field in self.op.output_fields:
4178
          if field == "node":
4179
            val = node
4180
          elif field == "phys":
4181
            val = vol['dev']
4182
          elif field == "vg":
4183
            val = vol['vg']
4184
          elif field == "name":
4185
            val = vol['name']
4186
          elif field == "size":
4187
            val = int(float(vol['size']))
4188
          elif field == "instance":
4189
            for inst in ilist:
4190
              if node not in lv_by_node[inst]:
4191
                continue
4192
              if vol['name'] in lv_by_node[inst][node]:
4193
                val = inst.name
4194
                break
4195
            else:
4196
              val = '-'
4197
          else:
4198
            raise errors.ParameterError(field)
4199
          node_output.append(str(val))
4200

    
4201
        output.append(node_output)
4202

    
4203
    return output
4204

    
4205

    
4206
class LUNodeQueryStorage(NoHooksLU):
4207
  """Logical unit for getting information on storage units on node(s).
4208

4209
  """
4210
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4211
  REQ_BGL = False
4212

    
4213
  def CheckArguments(self):
4214
    _CheckOutputFields(static=self._FIELDS_STATIC,
4215
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4216
                       selected=self.op.output_fields)
4217

    
4218
  def ExpandNames(self):
4219
    self.needed_locks = {}
4220
    self.share_locks[locking.LEVEL_NODE] = 1
4221

    
4222
    if self.op.nodes:
4223
      self.needed_locks[locking.LEVEL_NODE] = \
4224
        _GetWantedNodes(self, self.op.nodes)
4225
    else:
4226
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4227

    
4228
  def Exec(self, feedback_fn):
4229
    """Computes the list of nodes and their attributes.
4230

4231
    """
4232
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
4233

    
4234
    # Always get name to sort by
4235
    if constants.SF_NAME in self.op.output_fields:
4236
      fields = self.op.output_fields[:]
4237
    else:
4238
      fields = [constants.SF_NAME] + self.op.output_fields
4239

    
4240
    # Never ask for node or type as it's only known to the LU
4241
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4242
      while extra in fields:
4243
        fields.remove(extra)
4244

    
4245
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4246
    name_idx = field_idx[constants.SF_NAME]
4247

    
4248
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4249
    data = self.rpc.call_storage_list(self.nodes,
4250
                                      self.op.storage_type, st_args,
4251
                                      self.op.name, fields)
4252

    
4253
    result = []
4254

    
4255
    for node in utils.NiceSort(self.nodes):
4256
      nresult = data[node]
4257
      if nresult.offline:
4258
        continue
4259

    
4260
      msg = nresult.fail_msg
4261
      if msg:
4262
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4263
        continue
4264

    
4265
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4266

    
4267
      for name in utils.NiceSort(rows.keys()):
4268
        row = rows[name]
4269

    
4270
        out = []
4271

    
4272
        for field in self.op.output_fields:
4273
          if field == constants.SF_NODE:
4274
            val = node
4275
          elif field == constants.SF_TYPE:
4276
            val = self.op.storage_type
4277
          elif field in field_idx:
4278
            val = row[field_idx[field]]
4279
          else:
4280
            raise errors.ParameterError(field)
4281

    
4282
          out.append(val)
4283

    
4284
        result.append(out)
4285

    
4286
    return result
4287

    
4288

    
4289
class _InstanceQuery(_QueryBase):
4290
  FIELDS = query.INSTANCE_FIELDS
4291

    
4292
  def ExpandNames(self, lu):
4293
    lu.needed_locks = {}
4294
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
4295
    lu.share_locks[locking.LEVEL_NODE] = 1
4296

    
4297
    if self.names:
4298
      self.wanted = _GetWantedInstances(lu, self.names)
4299
    else:
4300
      self.wanted = locking.ALL_SET
4301

    
4302
    self.do_locking = (self.use_locking and
4303
                       query.IQ_LIVE in self.requested_data)
4304
    if self.do_locking:
4305
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4306
      lu.needed_locks[locking.LEVEL_NODE] = []
4307
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4308

    
4309
  def DeclareLocks(self, lu, level):
4310
    if level == locking.LEVEL_NODE and self.do_locking:
4311
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
4312

    
4313
  def _GetQueryData(self, lu):
4314
    """Computes the list of instances and their attributes.
4315

4316
    """
4317
    cluster = lu.cfg.GetClusterInfo()
4318
    all_info = lu.cfg.GetAllInstancesInfo()
4319

    
4320
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4321

    
4322
    instance_list = [all_info[name] for name in instance_names]
4323
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4324
                                        for inst in instance_list)))
4325
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4326
    bad_nodes = []
4327
    offline_nodes = []
4328
    wrongnode_inst = set()
4329

    
4330
    # Gather data as requested
4331
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4332
      live_data = {}
4333
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4334
      for name in nodes:
4335
        result = node_data[name]
4336
        if result.offline:
4337
          # offline nodes will be in both lists
4338
          assert result.fail_msg
4339
          offline_nodes.append(name)
4340
        if result.fail_msg:
4341
          bad_nodes.append(name)
4342
        elif result.payload:
4343
          for inst in result.payload:
4344
            if inst in all_info:
4345
              if all_info[inst].primary_node == name:
4346
                live_data.update(result.payload)
4347
              else:
4348
                wrongnode_inst.add(inst)
4349
            else:
4350
              # orphan instance; we don't list it here as we don't
4351
              # handle this case yet in the output of instance listing
4352
              logging.warning("Orphan instance '%s' found on node %s",
4353
                              inst, name)
4354
        # else no instance is alive
4355
    else:
4356
      live_data = {}
4357

    
4358
    if query.IQ_DISKUSAGE in self.requested_data:
4359
      disk_usage = dict((inst.name,
4360
                         _ComputeDiskSize(inst.disk_template,
4361
                                          [{constants.IDISK_SIZE: disk.size}
4362
                                           for disk in inst.disks]))
4363
                        for inst in instance_list)
4364
    else:
4365
      disk_usage = None
4366

    
4367
    if query.IQ_CONSOLE in self.requested_data:
4368
      consinfo = {}
4369
      for inst in instance_list:
4370
        if inst.name in live_data:
4371
          # Instance is running
4372
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4373
        else:
4374
          consinfo[inst.name] = None
4375
      assert set(consinfo.keys()) == set(instance_names)
4376
    else:
4377
      consinfo = None
4378

    
4379
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4380
                                   disk_usage, offline_nodes, bad_nodes,
4381
                                   live_data, wrongnode_inst, consinfo)
4382

    
4383

    
4384
class LUQuery(NoHooksLU):
4385
  """Query for resources/items of a certain kind.
4386

4387
  """
4388
  # pylint: disable-msg=W0142
4389
  REQ_BGL = False
4390

    
4391
  def CheckArguments(self):
4392
    qcls = _GetQueryImplementation(self.op.what)
4393

    
4394
    self.impl = qcls(self.op.filter, self.op.fields, False)
4395

    
4396
  def ExpandNames(self):
4397
    self.impl.ExpandNames(self)
4398

    
4399
  def DeclareLocks(self, level):
4400
    self.impl.DeclareLocks(self, level)
4401

    
4402
  def Exec(self, feedback_fn):
4403
    return self.impl.NewStyleQuery(self)
4404

    
4405

    
4406
class LUQueryFields(NoHooksLU):
4407
  """Query for resources/items of a certain kind.
4408

4409
  """
4410
  # pylint: disable-msg=W0142
4411
  REQ_BGL = False
4412

    
4413
  def CheckArguments(self):
4414
    self.qcls = _GetQueryImplementation(self.op.what)
4415

    
4416
  def ExpandNames(self):
4417
    self.needed_locks = {}
4418

    
4419
  def Exec(self, feedback_fn):
4420
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4421

    
4422

    
4423
class LUNodeModifyStorage(NoHooksLU):
4424
  """Logical unit for modifying a storage volume on a node.
4425

4426
  """
4427
  REQ_BGL = False
4428

    
4429
  def CheckArguments(self):
4430
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4431

    
4432
    storage_type = self.op.storage_type
4433

    
4434
    try:
4435
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4436
    except KeyError:
4437
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4438
                                 " modified" % storage_type,
4439
                                 errors.ECODE_INVAL)
4440

    
4441
    diff = set(self.op.changes.keys()) - modifiable
4442
    if diff:
4443
      raise errors.OpPrereqError("The following fields can not be modified for"
4444
                                 " storage units of type '%s': %r" %
4445
                                 (storage_type, list(diff)),
4446
                                 errors.ECODE_INVAL)
4447

    
4448
  def ExpandNames(self):
4449
    self.needed_locks = {
4450
      locking.LEVEL_NODE: self.op.node_name,
4451
      }
4452

    
4453
  def Exec(self, feedback_fn):
4454
    """Computes the list of nodes and their attributes.
4455

4456
    """
4457
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4458
    result = self.rpc.call_storage_modify(self.op.node_name,
4459
                                          self.op.storage_type, st_args,
4460
                                          self.op.name, self.op.changes)
4461
    result.Raise("Failed to modify storage unit '%s' on %s" %
4462
                 (self.op.name, self.op.node_name))
4463

    
4464

    
4465
class LUNodeAdd(LogicalUnit):
4466
  """Logical unit for adding node to the cluster.
4467

4468
  """
4469
  HPATH = "node-add"
4470
  HTYPE = constants.HTYPE_NODE
4471
  _NFLAGS = ["master_capable", "vm_capable"]
4472

    
4473
  def CheckArguments(self):
4474
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4475
    # validate/normalize the node name
4476
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4477
                                         family=self.primary_ip_family)
4478
    self.op.node_name = self.hostname.name
4479

    
4480
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4481
      raise errors.OpPrereqError("Cannot readd the master node",
4482
                                 errors.ECODE_STATE)
4483

    
4484
    if self.op.readd and self.op.group:
4485
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4486
                                 " being readded", errors.ECODE_INVAL)
4487

    
4488
  def BuildHooksEnv(self):
4489
    """Build hooks env.
4490

4491
    This will run on all nodes before, and on all nodes + the new node after.
4492

4493
    """
4494
    return {
4495
      "OP_TARGET": self.op.node_name,
4496
      "NODE_NAME": self.op.node_name,
4497
      "NODE_PIP": self.op.primary_ip,
4498
      "NODE_SIP": self.op.secondary_ip,
4499
      "MASTER_CAPABLE": str(self.op.master_capable),
4500
      "VM_CAPABLE": str(self.op.vm_capable),
4501
      }
4502

    
4503
  def BuildHooksNodes(self):
4504
    """Build hooks nodes.
4505

4506
    """
4507
    # Exclude added node
4508
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4509
    post_nodes = pre_nodes + [self.op.node_name, ]
4510

    
4511
    return (pre_nodes, post_nodes)
4512

    
4513
  def CheckPrereq(self):
4514
    """Check prerequisites.
4515

4516
    This checks:
4517
     - the new node is not already in the config
4518
     - it is resolvable
4519
     - its parameters (single/dual homed) matches the cluster
4520

4521
    Any errors are signaled by raising errors.OpPrereqError.
4522

4523
    """
4524
    cfg = self.cfg
4525
    hostname = self.hostname
4526
    node = hostname.name
4527
    primary_ip = self.op.primary_ip = hostname.ip
4528
    if self.op.secondary_ip is None:
4529
      if self.primary_ip_family == netutils.IP6Address.family:
4530
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4531
                                   " IPv4 address must be given as secondary",
4532
                                   errors.ECODE_INVAL)
4533
      self.op.secondary_ip = primary_ip
4534

    
4535
    secondary_ip = self.op.secondary_ip
4536
    if not netutils.IP4Address.IsValid(secondary_ip):
4537
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4538
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4539

    
4540
    node_list = cfg.GetNodeList()
4541
    if not self.op.readd and node in node_list:
4542
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4543
                                 node, errors.ECODE_EXISTS)
4544
    elif self.op.readd and node not in node_list:
4545
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4546
                                 errors.ECODE_NOENT)
4547

    
4548
    self.changed_primary_ip = False
4549

    
4550
    for existing_node_name in node_list:
4551
      existing_node = cfg.GetNodeInfo(existing_node_name)
4552

    
4553
      if self.op.readd and node == existing_node_name:
4554
        if existing_node.secondary_ip != secondary_ip:
4555
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4556
                                     " address configuration as before",
4557
                                     errors.ECODE_INVAL)
4558
        if existing_node.primary_ip != primary_ip:
4559
          self.changed_primary_ip = True
4560

    
4561
        continue
4562

    
4563
      if (existing_node.primary_ip == primary_ip or
4564
          existing_node.secondary_ip == primary_ip or
4565
          existing_node.primary_ip == secondary_ip or
4566
          existing_node.secondary_ip == secondary_ip):
4567
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4568
                                   " existing node %s" % existing_node.name,
4569
                                   errors.ECODE_NOTUNIQUE)
4570

    
4571
    # After this 'if' block, None is no longer a valid value for the
4572
    # _capable op attributes
4573
    if self.op.readd:
4574
      old_node = self.cfg.GetNodeInfo(node)
4575
      assert old_node is not None, "Can't retrieve locked node %s" % node
4576
      for attr in self._NFLAGS:
4577
        if getattr(self.op, attr) is None:
4578
          setattr(self.op, attr, getattr(old_node, attr))
4579
    else:
4580
      for attr in self._NFLAGS:
4581
        if getattr(self.op, attr) is None:
4582
          setattr(self.op, attr, True)
4583

    
4584
    if self.op.readd and not self.op.vm_capable:
4585
      pri, sec = cfg.GetNodeInstances(node)
4586
      if pri or sec:
4587
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4588
                                   " flag set to false, but it already holds"
4589
                                   " instances" % node,
4590
                                   errors.ECODE_STATE)
4591

    
4592
    # check that the type of the node (single versus dual homed) is the
4593
    # same as for the master
4594
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4595
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4596
    newbie_singlehomed = secondary_ip == primary_ip
4597
    if master_singlehomed != newbie_singlehomed:
4598
      if master_singlehomed:
4599
        raise errors.OpPrereqError("The master has no secondary ip but the"
4600
                                   " new node has one",
4601
                                   errors.ECODE_INVAL)
4602
      else:
4603
        raise errors.OpPrereqError("The master has a secondary ip but the"
4604
                                   " new node doesn't have one",
4605
                                   errors.ECODE_INVAL)
4606

    
4607
    # checks reachability
4608
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4609
      raise errors.OpPrereqError("Node not reachable by ping",
4610
                                 errors.ECODE_ENVIRON)
4611

    
4612
    if not newbie_singlehomed:
4613
      # check reachability from my secondary ip to newbie's secondary ip
4614
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4615
                           source=myself.secondary_ip):
4616
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4617
                                   " based ping to node daemon port",
4618
                                   errors.ECODE_ENVIRON)
4619

    
4620
    if self.op.readd:
4621
      exceptions = [node]
4622
    else:
4623
      exceptions = []
4624

    
4625
    if self.op.master_capable:
4626
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4627
    else:
4628
      self.master_candidate = False
4629

    
4630
    if self.op.readd:
4631
      self.new_node = old_node
4632
    else:
4633
      node_group = cfg.LookupNodeGroup(self.op.group)
4634
      self.new_node = objects.Node(name=node,
4635
                                   primary_ip=primary_ip,
4636
                                   secondary_ip=secondary_ip,
4637
                                   master_candidate=self.master_candidate,
4638
                                   offline=False, drained=False,
4639
                                   group=node_group)
4640

    
4641
    if self.op.ndparams:
4642
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4643

    
4644
  def Exec(self, feedback_fn):
4645
    """Adds the new node to the cluster.
4646

4647
    """
4648
    new_node = self.new_node
4649
    node = new_node.name
4650

    
4651
    # We adding a new node so we assume it's powered
4652
    new_node.powered = True
4653

    
4654
    # for re-adds, reset the offline/drained/master-candidate flags;
4655
    # we need to reset here, otherwise offline would prevent RPC calls
4656
    # later in the procedure; this also means that if the re-add
4657
    # fails, we are left with a non-offlined, broken node
4658
    if self.op.readd:
4659
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4660
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4661
      # if we demote the node, we do cleanup later in the procedure
4662
      new_node.master_candidate = self.master_candidate
4663
      if self.changed_primary_ip:
4664
        new_node.primary_ip = self.op.primary_ip
4665

    
4666
    # copy the master/vm_capable flags
4667
    for attr in self._NFLAGS:
4668
      setattr(new_node, attr, getattr(self.op, attr))
4669

    
4670
    # notify the user about any possible mc promotion
4671
    if new_node.master_candidate:
4672
      self.LogInfo("Node will be a master candidate")
4673

    
4674
    if self.op.ndparams:
4675
      new_node.ndparams = self.op.ndparams
4676
    else:
4677
      new_node.ndparams = {}
4678

    
4679
    # check connectivity
4680
    result = self.rpc.call_version([node])[node]
4681
    result.Raise("Can't get version information from node %s" % node)
4682
    if constants.PROTOCOL_VERSION == result.payload:
4683
      logging.info("Communication to node %s fine, sw version %s match",
4684
                   node, result.payload)
4685
    else:
4686
      raise errors.OpExecError("Version mismatch master version %s,"
4687
                               " node version %s" %
4688
                               (constants.PROTOCOL_VERSION, result.payload))
4689

    
4690
    # Add node to our /etc/hosts, and add key to known_hosts
4691
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4692
      master_node = self.cfg.GetMasterNode()
4693
      result = self.rpc.call_etc_hosts_modify(master_node,
4694
                                              constants.ETC_HOSTS_ADD,
4695
                                              self.hostname.name,
4696
                                              self.hostname.ip)
4697
      result.Raise("Can't update hosts file with new host data")
4698

    
4699
    if new_node.secondary_ip != new_node.primary_ip:
4700
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4701
                               False)
4702

    
4703
    node_verify_list = [self.cfg.GetMasterNode()]
4704
    node_verify_param = {
4705
      constants.NV_NODELIST: [node],
4706
      # TODO: do a node-net-test as well?
4707
    }
4708

    
4709
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4710
                                       self.cfg.GetClusterName())
4711
    for verifier in node_verify_list:
4712
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4713
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4714
      if nl_payload:
4715
        for failed in nl_payload:
4716
          feedback_fn("ssh/hostname verification failed"
4717
                      " (checking from %s): %s" %
4718
                      (verifier, nl_payload[failed]))
4719
        raise errors.OpExecError("ssh/hostname verification failed")
4720

    
4721
    if self.op.readd:
4722
      _RedistributeAncillaryFiles(self)
4723
      self.context.ReaddNode(new_node)
4724
      # make sure we redistribute the config
4725
      self.cfg.Update(new_node, feedback_fn)
4726
      # and make sure the new node will not have old files around
4727
      if not new_node.master_candidate:
4728
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4729
        msg = result.fail_msg
4730
        if msg:
4731
          self.LogWarning("Node failed to demote itself from master"
4732
                          " candidate status: %s" % msg)
4733
    else:
4734
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4735
                                  additional_vm=self.op.vm_capable)
4736
      self.context.AddNode(new_node, self.proc.GetECId())
4737

    
4738

    
4739
class LUNodeSetParams(LogicalUnit):
4740
  """Modifies the parameters of a node.
4741

4742
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4743
      to the node role (as _ROLE_*)
4744
  @cvar _R2F: a dictionary from node role to tuples of flags
4745
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4746

4747
  """
4748
  HPATH = "node-modify"
4749
  HTYPE = constants.HTYPE_NODE
4750
  REQ_BGL = False
4751
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4752
  _F2R = {
4753
    (True, False, False): _ROLE_CANDIDATE,
4754
    (False, True, False): _ROLE_DRAINED,
4755
    (False, False, True): _ROLE_OFFLINE,
4756
    (False, False, False): _ROLE_REGULAR,
4757
    }
4758
  _R2F = dict((v, k) for k, v in _F2R.items())
4759
  _FLAGS = ["master_candidate", "drained", "offline"]
4760

    
4761
  def CheckArguments(self):
4762
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4763
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4764
                self.op.master_capable, self.op.vm_capable,
4765
                self.op.secondary_ip, self.op.ndparams]
4766
    if all_mods.count(None) == len(all_mods):
4767
      raise errors.OpPrereqError("Please pass at least one modification",
4768
                                 errors.ECODE_INVAL)
4769
    if all_mods.count(True) > 1:
4770
      raise errors.OpPrereqError("Can't set the node into more than one"
4771
                                 " state at the same time",
4772
                                 errors.ECODE_INVAL)
4773

    
4774
    # Boolean value that tells us whether we might be demoting from MC
4775
    self.might_demote = (self.op.master_candidate == False or
4776
                         self.op.offline == True or
4777
                         self.op.drained == True or
4778
                         self.op.master_capable == False)
4779

    
4780
    if self.op.secondary_ip:
4781
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4782
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4783
                                   " address" % self.op.secondary_ip,
4784
                                   errors.ECODE_INVAL)
4785

    
4786
    self.lock_all = self.op.auto_promote and self.might_demote
4787
    self.lock_instances = self.op.secondary_ip is not None
4788

    
4789
  def ExpandNames(self):
4790
    if self.lock_all:
4791
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4792
    else:
4793
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4794

    
4795
    if self.lock_instances:
4796
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4797

    
4798
  def DeclareLocks(self, level):
4799
    # If we have locked all instances, before waiting to lock nodes, release
4800
    # all the ones living on nodes unrelated to the current operation.
4801
    if level == locking.LEVEL_NODE and self.lock_instances:
4802
      self.affected_instances = []
4803
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4804
        instances_keep = []
4805

    
4806
        # Build list of instances to release
4807
        for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
4808
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4809
          if (instance.disk_template in constants.DTS_INT_MIRROR and
4810
              self.op.node_name in instance.all_nodes):
4811
            instances_keep.append(instance_name)
4812
            self.affected_instances.append(instance)
4813

    
4814
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
4815

    
4816
        assert (set(self.glm.list_owned(locking.LEVEL_INSTANCE)) ==
4817
                set(instances_keep))
4818

    
4819
  def BuildHooksEnv(self):
4820
    """Build hooks env.
4821

4822
    This runs on the master node.
4823

4824
    """
4825
    return {
4826
      "OP_TARGET": self.op.node_name,
4827
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4828
      "OFFLINE": str(self.op.offline),
4829
      "DRAINED": str(self.op.drained),
4830
      "MASTER_CAPABLE": str(self.op.master_capable),
4831
      "VM_CAPABLE": str(self.op.vm_capable),
4832
      }
4833

    
4834
  def BuildHooksNodes(self):
4835
    """Build hooks nodes.
4836

4837
    """
4838
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
4839
    return (nl, nl)
4840

    
4841
  def CheckPrereq(self):
4842
    """Check prerequisites.
4843

4844
    This only checks the instance list against the existing names.
4845

4846
    """
4847
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4848

    
4849
    if (self.op.master_candidate is not None or
4850
        self.op.drained is not None or
4851
        self.op.offline is not None):
4852
      # we can't change the master's node flags
4853
      if self.op.node_name == self.cfg.GetMasterNode():
4854
        raise errors.OpPrereqError("The master role can be changed"
4855
                                   " only via master-failover",
4856
                                   errors.ECODE_INVAL)
4857

    
4858
    if self.op.master_candidate and not node.master_capable:
4859
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4860
                                 " it a master candidate" % node.name,
4861
                                 errors.ECODE_STATE)
4862

    
4863
    if self.op.vm_capable == False:
4864
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4865
      if ipri or isec:
4866
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4867
                                   " the vm_capable flag" % node.name,
4868
                                   errors.ECODE_STATE)
4869

    
4870
    if node.master_candidate and self.might_demote and not self.lock_all:
4871
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4872
      # check if after removing the current node, we're missing master
4873
      # candidates
4874
      (mc_remaining, mc_should, _) = \
4875
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4876
      if mc_remaining < mc_should:
4877
        raise errors.OpPrereqError("Not enough master candidates, please"
4878
                                   " pass auto promote option to allow"
4879
                                   " promotion", errors.ECODE_STATE)
4880

    
4881
    self.old_flags = old_flags = (node.master_candidate,
4882
                                  node.drained, node.offline)
4883
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
4884
    self.old_role = old_role = self._F2R[old_flags]
4885

    
4886
    # Check for ineffective changes
4887
    for attr in self._FLAGS:
4888
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4889
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4890
        setattr(self.op, attr, None)
4891

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

    
4895
    # TODO: We might query the real power state if it supports OOB
4896
    if _SupportsOob(self.cfg, node):
4897
      if self.op.offline is False and not (node.powered or
4898
                                           self.op.powered == True):
4899
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
4900
                                    " offline status can be reset") %
4901
                                   self.op.node_name)
4902
    elif self.op.powered is not None:
4903
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4904
                                  " as it does not support out-of-band"
4905
                                  " handling") % self.op.node_name)
4906

    
4907
    # If we're being deofflined/drained, we'll MC ourself if needed
4908
    if (self.op.drained == False or self.op.offline == False or
4909
        (self.op.master_capable and not node.master_capable)):
4910
      if _DecideSelfPromotion(self):
4911
        self.op.master_candidate = True
4912
        self.LogInfo("Auto-promoting node to master candidate")
4913

    
4914
    # If we're no longer master capable, we'll demote ourselves from MC
4915
    if self.op.master_capable == False and node.master_candidate:
4916
      self.LogInfo("Demoting from master candidate")
4917
      self.op.master_candidate = False
4918

    
4919
    # Compute new role
4920
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4921
    if self.op.master_candidate:
4922
      new_role = self._ROLE_CANDIDATE
4923
    elif self.op.drained:
4924
      new_role = self._ROLE_DRAINED
4925
    elif self.op.offline:
4926
      new_role = self._ROLE_OFFLINE
4927
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4928
      # False is still in new flags, which means we're un-setting (the
4929
      # only) True flag
4930
      new_role = self._ROLE_REGULAR
4931
    else: # no new flags, nothing, keep old role
4932
      new_role = old_role
4933

    
4934
    self.new_role = new_role
4935

    
4936
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4937
      # Trying to transition out of offline status
4938
      result = self.rpc.call_version([node.name])[node.name]
4939
      if result.fail_msg:
4940
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4941
                                   " to report its version: %s" %
4942
                                   (node.name, result.fail_msg),
4943
                                   errors.ECODE_STATE)
4944
      else:
4945
        self.LogWarning("Transitioning node from offline to online state"
4946
                        " without using re-add. Please make sure the node"
4947
                        " is healthy!")
4948

    
4949
    if self.op.secondary_ip:
4950
      # Ok even without locking, because this can't be changed by any LU
4951
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4952
      master_singlehomed = master.secondary_ip == master.primary_ip
4953
      if master_singlehomed and self.op.secondary_ip:
4954
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4955
                                   " homed cluster", errors.ECODE_INVAL)
4956

    
4957
      if node.offline:
4958
        if self.affected_instances:
4959
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4960
                                     " node has instances (%s) configured"
4961
                                     " to use it" % self.affected_instances)
4962
      else:
4963
        # On online nodes, check that no instances are running, and that
4964
        # the node has the new ip and we can reach it.
4965
        for instance in self.affected_instances:
4966
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4967

    
4968
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4969
        if master.name != node.name:
4970
          # check reachability from master secondary ip to new secondary ip
4971
          if not netutils.TcpPing(self.op.secondary_ip,
4972
                                  constants.DEFAULT_NODED_PORT,
4973
                                  source=master.secondary_ip):
4974
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4975
                                       " based ping to node daemon port",
4976
                                       errors.ECODE_ENVIRON)
4977

    
4978
    if self.op.ndparams:
4979
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4980
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4981
      self.new_ndparams = new_ndparams
4982

    
4983
  def Exec(self, feedback_fn):
4984
    """Modifies a node.
4985

4986
    """
4987
    node = self.node
4988
    old_role = self.old_role
4989
    new_role = self.new_role
4990

    
4991
    result = []
4992

    
4993
    if self.op.ndparams:
4994
      node.ndparams = self.new_ndparams
4995

    
4996
    if self.op.powered is not None:
4997
      node.powered = self.op.powered
4998

    
4999
    for attr in ["master_capable", "vm_capable"]:
5000
      val = getattr(self.op, attr)
5001
      if val is not None:
5002
        setattr(node, attr, val)
5003
        result.append((attr, str(val)))
5004

    
5005
    if new_role != old_role:
5006
      # Tell the node to demote itself, if no longer MC and not offline
5007
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5008
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5009
        if msg:
5010
          self.LogWarning("Node failed to demote itself: %s", msg)
5011

    
5012
      new_flags = self._R2F[new_role]
5013
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5014
        if of != nf:
5015
          result.append((desc, str(nf)))
5016
      (node.master_candidate, node.drained, node.offline) = new_flags
5017

    
5018
      # we locked all nodes, we adjust the CP before updating this node
5019
      if self.lock_all:
5020
        _AdjustCandidatePool(self, [node.name])
5021

    
5022
    if self.op.secondary_ip:
5023
      node.secondary_ip = self.op.secondary_ip
5024
      result.append(("secondary_ip", self.op.secondary_ip))
5025

    
5026
    # this will trigger configuration file update, if needed
5027
    self.cfg.Update(node, feedback_fn)
5028

    
5029
    # this will trigger job queue propagation or cleanup if the mc
5030
    # flag changed
5031
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5032
      self.context.ReaddNode(node)
5033

    
5034
    return result
5035

    
5036

    
5037
class LUNodePowercycle(NoHooksLU):
5038
  """Powercycles a node.
5039

5040
  """
5041
  REQ_BGL = False
5042

    
5043
  def CheckArguments(self):
5044
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5045
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5046
      raise errors.OpPrereqError("The node is the master and the force"
5047
                                 " parameter was not set",
5048
                                 errors.ECODE_INVAL)
5049

    
5050
  def ExpandNames(self):
5051
    """Locking for PowercycleNode.
5052

5053
    This is a last-resort option and shouldn't block on other
5054
    jobs. Therefore, we grab no locks.
5055

5056
    """
5057
    self.needed_locks = {}
5058

    
5059
  def Exec(self, feedback_fn):
5060
    """Reboots a node.
5061

5062
    """
5063
    result = self.rpc.call_node_powercycle(self.op.node_name,
5064
                                           self.cfg.GetHypervisorType())
5065
    result.Raise("Failed to schedule the reboot")
5066
    return result.payload
5067

    
5068

    
5069
class LUClusterQuery(NoHooksLU):
5070
  """Query cluster configuration.
5071

5072
  """
5073
  REQ_BGL = False
5074

    
5075
  def ExpandNames(self):
5076
    self.needed_locks = {}
5077

    
5078
  def Exec(self, feedback_fn):
5079
    """Return cluster config.
5080

5081
    """
5082
    cluster = self.cfg.GetClusterInfo()
5083
    os_hvp = {}
5084

    
5085
    # Filter just for enabled hypervisors
5086
    for os_name, hv_dict in cluster.os_hvp.items():
5087
      os_hvp[os_name] = {}
5088
      for hv_name, hv_params in hv_dict.items():
5089
        if hv_name in cluster.enabled_hypervisors:
5090
          os_hvp[os_name][hv_name] = hv_params
5091

    
5092
    # Convert ip_family to ip_version
5093
    primary_ip_version = constants.IP4_VERSION
5094
    if cluster.primary_ip_family == netutils.IP6Address.family:
5095
      primary_ip_version = constants.IP6_VERSION
5096

    
5097
    result = {
5098
      "software_version": constants.RELEASE_VERSION,
5099
      "protocol_version": constants.PROTOCOL_VERSION,
5100
      "config_version": constants.CONFIG_VERSION,
5101
      "os_api_version": max(constants.OS_API_VERSIONS),
5102
      "export_version": constants.EXPORT_VERSION,
5103
      "architecture": (platform.architecture()[0], platform.machine()),
5104
      "name": cluster.cluster_name,
5105
      "master": cluster.master_node,
5106
      "default_hypervisor": cluster.enabled_hypervisors[0],
5107
      "enabled_hypervisors": cluster.enabled_hypervisors,
5108
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5109
                        for hypervisor_name in cluster.enabled_hypervisors]),
5110
      "os_hvp": os_hvp,
5111
      "beparams": cluster.beparams,
5112
      "osparams": cluster.osparams,
5113
      "nicparams": cluster.nicparams,
5114
      "ndparams": cluster.ndparams,
5115
      "candidate_pool_size": cluster.candidate_pool_size,
5116
      "master_netdev": cluster.master_netdev,
5117
      "volume_group_name": cluster.volume_group_name,
5118
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5119
      "file_storage_dir": cluster.file_storage_dir,
5120
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5121
      "maintain_node_health": cluster.maintain_node_health,
5122
      "ctime": cluster.ctime,
5123
      "mtime": cluster.mtime,
5124
      "uuid": cluster.uuid,
5125
      "tags": list(cluster.GetTags()),
5126
      "uid_pool": cluster.uid_pool,
5127
      "default_iallocator": cluster.default_iallocator,
5128
      "reserved_lvs": cluster.reserved_lvs,
5129
      "primary_ip_version": primary_ip_version,
5130
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5131
      "hidden_os": cluster.hidden_os,
5132
      "blacklisted_os": cluster.blacklisted_os,
5133
      }
5134

    
5135
    return result
5136

    
5137

    
5138
class LUClusterConfigQuery(NoHooksLU):
5139
  """Return configuration values.
5140

5141
  """
5142
  REQ_BGL = False
5143
  _FIELDS_DYNAMIC = utils.FieldSet()
5144
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5145
                                  "watcher_pause", "volume_group_name")
5146

    
5147
  def CheckArguments(self):
5148
    _CheckOutputFields(static=self._FIELDS_STATIC,
5149
                       dynamic=self._FIELDS_DYNAMIC,
5150
                       selected=self.op.output_fields)
5151

    
5152
  def ExpandNames(self):
5153
    self.needed_locks = {}
5154

    
5155
  def Exec(self, feedback_fn):
5156
    """Dump a representation of the cluster config to the standard output.
5157

5158
    """
5159
    values = []
5160
    for field in self.op.output_fields:
5161
      if field == "cluster_name":
5162
        entry = self.cfg.GetClusterName()
5163
      elif field == "master_node":
5164
        entry = self.cfg.GetMasterNode()
5165
      elif field == "drain_flag":
5166
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5167
      elif field == "watcher_pause":
5168
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5169
      elif field == "volume_group_name":
5170
        entry = self.cfg.GetVGName()
5171
      else:
5172
        raise errors.ParameterError(field)
5173
      values.append(entry)
5174
    return values
5175

    
5176

    
5177
class LUInstanceActivateDisks(NoHooksLU):
5178
  """Bring up an instance's disks.
5179

5180
  """
5181
  REQ_BGL = False
5182

    
5183
  def ExpandNames(self):
5184
    self._ExpandAndLockInstance()
5185
    self.needed_locks[locking.LEVEL_NODE] = []
5186
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5187

    
5188
  def DeclareLocks(self, level):
5189
    if level == locking.LEVEL_NODE:
5190
      self._LockInstancesNodes()
5191

    
5192
  def CheckPrereq(self):
5193
    """Check prerequisites.
5194

5195
    This checks that the instance is in the cluster.
5196

5197
    """
5198
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5199
    assert self.instance is not None, \
5200
      "Cannot retrieve locked instance %s" % self.op.instance_name
5201
    _CheckNodeOnline(self, self.instance.primary_node)
5202

    
5203
  def Exec(self, feedback_fn):
5204
    """Activate the disks.
5205

5206
    """
5207
    disks_ok, disks_info = \
5208
              _AssembleInstanceDisks(self, self.instance,
5209
                                     ignore_size=self.op.ignore_size)
5210
    if not disks_ok:
5211
      raise errors.OpExecError("Cannot activate block devices")
5212

    
5213
    return disks_info
5214

    
5215

    
5216
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5217
                           ignore_size=False):
5218
  """Prepare the block devices for an instance.
5219

5220
  This sets up the block devices on all nodes.
5221

5222
  @type lu: L{LogicalUnit}
5223
  @param lu: the logical unit on whose behalf we execute
5224
  @type instance: L{objects.Instance}
5225
  @param instance: the instance for whose disks we assemble
5226
  @type disks: list of L{objects.Disk} or None
5227
  @param disks: which disks to assemble (or all, if None)
5228
  @type ignore_secondaries: boolean
5229
  @param ignore_secondaries: if true, errors on secondary nodes
5230
      won't result in an error return from the function
5231
  @type ignore_size: boolean
5232
  @param ignore_size: if true, the current known size of the disk
5233
      will not be used during the disk activation, useful for cases
5234
      when the size is wrong
5235
  @return: False if the operation failed, otherwise a list of
5236
      (host, instance_visible_name, node_visible_name)
5237
      with the mapping from node devices to instance devices
5238

5239
  """
5240
  device_info = []
5241
  disks_ok = True
5242
  iname = instance.name
5243
  disks = _ExpandCheckDisks(instance, disks)
5244

    
5245
  # With the two passes mechanism we try to reduce the window of
5246
  # opportunity for the race condition of switching DRBD to primary
5247
  # before handshaking occured, but we do not eliminate it
5248

    
5249
  # The proper fix would be to wait (with some limits) until the
5250
  # connection has been made and drbd transitions from WFConnection
5251
  # into any other network-connected state (Connected, SyncTarget,
5252
  # SyncSource, etc.)
5253

    
5254
  # 1st pass, assemble on all nodes in secondary mode
5255
  for idx, inst_disk in enumerate(disks):
5256
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5257
      if ignore_size:
5258
        node_disk = node_disk.Copy()
5259
        node_disk.UnsetSize()
5260
      lu.cfg.SetDiskID(node_disk, node)
5261
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5262
      msg = result.fail_msg
5263
      if msg:
5264
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5265
                           " (is_primary=False, pass=1): %s",
5266
                           inst_disk.iv_name, node, msg)
5267
        if not ignore_secondaries:
5268
          disks_ok = False
5269

    
5270
  # FIXME: race condition on drbd migration to primary
5271

    
5272
  # 2nd pass, do only the primary node
5273
  for idx, inst_disk in enumerate(disks):
5274
    dev_path = None
5275

    
5276
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5277
      if node != instance.primary_node:
5278
        continue
5279
      if ignore_size:
5280
        node_disk = node_disk.Copy()
5281
        node_disk.UnsetSize()
5282
      lu.cfg.SetDiskID(node_disk, node)
5283
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5284
      msg = result.fail_msg
5285
      if msg:
5286
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5287
                           " (is_primary=True, pass=2): %s",
5288
                           inst_disk.iv_name, node, msg)
5289
        disks_ok = False
5290
      else:
5291
        dev_path = result.payload
5292

    
5293
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5294

    
5295
  # leave the disks configured for the primary node
5296
  # this is a workaround that would be fixed better by
5297
  # improving the logical/physical id handling
5298
  for disk in disks:
5299
    lu.cfg.SetDiskID(disk, instance.primary_node)
5300

    
5301
  return disks_ok, device_info
5302

    
5303

    
5304
def _StartInstanceDisks(lu, instance, force):
5305
  """Start the disks of an instance.
5306

5307
  """
5308
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5309
                                           ignore_secondaries=force)
5310
  if not disks_ok:
5311
    _ShutdownInstanceDisks(lu, instance)
5312
    if force is not None and not force:
5313
      lu.proc.LogWarning("", hint="If the message above refers to a"
5314
                         " secondary node,"
5315
                         " you can retry the operation using '--force'.")
5316
    raise errors.OpExecError("Disk consistency error")
5317

    
5318

    
5319
class LUInstanceDeactivateDisks(NoHooksLU):
5320
  """Shutdown an instance's disks.
5321

5322
  """
5323
  REQ_BGL = False
5324

    
5325
  def ExpandNames(self):
5326
    self._ExpandAndLockInstance()
5327
    self.needed_locks[locking.LEVEL_NODE] = []
5328
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5329

    
5330
  def DeclareLocks(self, level):
5331
    if level == locking.LEVEL_NODE:
5332
      self._LockInstancesNodes()
5333

    
5334
  def CheckPrereq(self):
5335
    """Check prerequisites.
5336

5337
    This checks that the instance is in the cluster.
5338

5339
    """
5340
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5341
    assert self.instance is not None, \
5342
      "Cannot retrieve locked instance %s" % self.op.instance_name
5343

    
5344
  def Exec(self, feedback_fn):
5345
    """Deactivate the disks
5346

5347
    """
5348
    instance = self.instance
5349
    if self.op.force:
5350
      _ShutdownInstanceDisks(self, instance)
5351
    else:
5352
      _SafeShutdownInstanceDisks(self, instance)
5353

    
5354

    
5355
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5356
  """Shutdown block devices of an instance.
5357

5358
  This function checks if an instance is running, before calling
5359
  _ShutdownInstanceDisks.
5360

5361
  """
5362
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5363
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5364

    
5365

    
5366
def _ExpandCheckDisks(instance, disks):
5367
  """Return the instance disks selected by the disks list
5368

5369
  @type disks: list of L{objects.Disk} or None
5370
  @param disks: selected disks
5371
  @rtype: list of L{objects.Disk}
5372
  @return: selected instance disks to act on
5373

5374
  """
5375
  if disks is None:
5376
    return instance.disks
5377
  else:
5378
    if not set(disks).issubset(instance.disks):
5379
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5380
                                   " target instance")
5381
    return disks
5382

    
5383

    
5384
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5385
  """Shutdown block devices of an instance.
5386

5387
  This does the shutdown on all nodes of the instance.
5388

5389
  If the ignore_primary is false, errors on the primary node are
5390
  ignored.
5391

5392
  """
5393
  all_result = True
5394
  disks = _ExpandCheckDisks(instance, disks)
5395

    
5396
  for disk in disks:
5397
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5398
      lu.cfg.SetDiskID(top_disk, node)
5399
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5400
      msg = result.fail_msg
5401
      if msg:
5402
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5403
                      disk.iv_name, node, msg)
5404
        if ((node == instance.primary_node and not ignore_primary) or
5405
            (node != instance.primary_node and not result.offline)):
5406
          all_result = False
5407
  return all_result
5408

    
5409

    
5410
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5411
  """Checks if a node has enough free memory.
5412

5413
  This function check if a given node has the needed amount of free
5414
  memory. In case the node has less memory or we cannot get the
5415
  information from the node, this function raise an OpPrereqError
5416
  exception.
5417

5418
  @type lu: C{LogicalUnit}
5419
  @param lu: a logical unit from which we get configuration data
5420
  @type node: C{str}
5421
  @param node: the node to check
5422
  @type reason: C{str}
5423
  @param reason: string to use in the error message
5424
  @type requested: C{int}
5425
  @param requested: the amount of memory in MiB to check for
5426
  @type hypervisor_name: C{str}
5427
  @param hypervisor_name: the hypervisor to ask for memory stats
5428
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5429
      we cannot check the node
5430

5431
  """
5432
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5433
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5434
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5435
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5436
  if not isinstance(free_mem, int):
5437
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5438
                               " was '%s'" % (node, free_mem),
5439
                               errors.ECODE_ENVIRON)
5440
  if requested > free_mem:
5441
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5442
                               " needed %s MiB, available %s MiB" %
5443
                               (node, reason, requested, free_mem),
5444
                               errors.ECODE_NORES)
5445

    
5446

    
5447
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5448
  """Checks if nodes have enough free disk space in the all VGs.
5449

5450
  This function check if all given nodes have the needed amount of
5451
  free disk. In case any node has less disk or we cannot get the
5452
  information from the node, this function raise an OpPrereqError
5453
  exception.
5454

5455
  @type lu: C{LogicalUnit}
5456
  @param lu: a logical unit from which we get configuration data
5457
  @type nodenames: C{list}
5458
  @param nodenames: the list of node names to check
5459
  @type req_sizes: C{dict}
5460
  @param req_sizes: the hash of vg and corresponding amount of disk in
5461
      MiB to check for
5462
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5463
      or we cannot check the node
5464

5465
  """
5466
  for vg, req_size in req_sizes.items():
5467
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5468

    
5469

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

5473
  This function check if all given nodes have the needed amount of
5474
  free disk. In case any node has less disk or we cannot get the
5475
  information from the node, this function raise an OpPrereqError
5476
  exception.
5477

5478
  @type lu: C{LogicalUnit}
5479
  @param lu: a logical unit from which we get configuration data
5480
  @type nodenames: C{list}
5481
  @param nodenames: the list of node names to check
5482
  @type vg: C{str}
5483
  @param vg: the volume group to check
5484
  @type requested: C{int}
5485
  @param requested: the amount of disk in MiB to check for
5486
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5487
      or we cannot check the node
5488

5489
  """
5490
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5491
  for node in nodenames:
5492
    info = nodeinfo[node]
5493
    info.Raise("Cannot get current information from node %s" % node,
5494
               prereq=True, ecode=errors.ECODE_ENVIRON)
5495
    vg_free = info.payload.get("vg_free", None)
5496
    if not isinstance(vg_free, int):
5497
      raise errors.OpPrereqError("Can't compute free disk space on node"
5498
                                 " %s for vg %s, result was '%s'" %
5499
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5500
    if requested > vg_free:
5501
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5502
                                 " vg %s: required %d MiB, available %d MiB" %
5503
                                 (node, vg, requested, vg_free),
5504
                                 errors.ECODE_NORES)
5505

    
5506

    
5507
class LUInstanceStartup(LogicalUnit):
5508
  """Starts an instance.
5509

5510
  """
5511
  HPATH = "instance-start"
5512
  HTYPE = constants.HTYPE_INSTANCE
5513
  REQ_BGL = False
5514

    
5515
  def CheckArguments(self):
5516
    # extra beparams
5517
    if self.op.beparams:
5518
      # fill the beparams dict
5519
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5520

    
5521
  def ExpandNames(self):
5522
    self._ExpandAndLockInstance()
5523

    
5524
  def BuildHooksEnv(self):
5525
    """Build hooks env.
5526

5527
    This runs on master, primary and secondary nodes of the instance.
5528

5529
    """
5530
    env = {
5531
      "FORCE": self.op.force,
5532
      }
5533

    
5534
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5535

    
5536
    return env
5537

    
5538
  def BuildHooksNodes(self):
5539
    """Build hooks nodes.
5540

5541
    """
5542
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5543
    return (nl, nl)
5544

    
5545
  def CheckPrereq(self):
5546
    """Check prerequisites.
5547

5548
    This checks that the instance is in the cluster.
5549

5550
    """
5551
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5552
    assert self.instance is not None, \
5553
      "Cannot retrieve locked instance %s" % self.op.instance_name
5554

    
5555
    # extra hvparams
5556
    if self.op.hvparams:
5557
      # check hypervisor parameter syntax (locally)
5558
      cluster = self.cfg.GetClusterInfo()
5559
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5560
      filled_hvp = cluster.FillHV(instance)
5561
      filled_hvp.update(self.op.hvparams)
5562
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5563
      hv_type.CheckParameterSyntax(filled_hvp)
5564
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5565

    
5566
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5567

    
5568
    if self.primary_offline and self.op.ignore_offline_nodes:
5569
      self.proc.LogWarning("Ignoring offline primary node")
5570

    
5571
      if self.op.hvparams or self.op.beparams:
5572
        self.proc.LogWarning("Overridden parameters are ignored")
5573
    else:
5574
      _CheckNodeOnline(self, instance.primary_node)
5575

    
5576
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5577

    
5578
      # check bridges existence
5579
      _CheckInstanceBridgesExist(self, instance)
5580

    
5581
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5582
                                                instance.name,
5583
                                                instance.hypervisor)
5584
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5585
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5586
      if not remote_info.payload: # not running already
5587
        _CheckNodeFreeMemory(self, instance.primary_node,
5588
                             "starting instance %s" % instance.name,
5589
                             bep[constants.BE_MEMORY], instance.hypervisor)
5590

    
5591
  def Exec(self, feedback_fn):
5592
    """Start the instance.
5593

5594
    """
5595
    instance = self.instance
5596
    force = self.op.force
5597

    
5598
    if not self.op.no_remember:
5599
      self.cfg.MarkInstanceUp(instance.name)
5600

    
5601
    if self.primary_offline:
5602
      assert self.op.ignore_offline_nodes
5603
      self.proc.LogInfo("Primary node offline, marked instance as started")
5604
    else:
5605
      node_current = instance.primary_node
5606

    
5607
      _StartInstanceDisks(self, instance, force)
5608

    
5609
      result = self.rpc.call_instance_start(node_current, instance,
5610
                                            self.op.hvparams, self.op.beparams)
5611
      msg = result.fail_msg
5612
      if msg:
5613
        _ShutdownInstanceDisks(self, instance)
5614
        raise errors.OpExecError("Could not start instance: %s" % msg)
5615

    
5616

    
5617
class LUInstanceReboot(LogicalUnit):
5618
  """Reboot an instance.
5619

5620
  """
5621
  HPATH = "instance-reboot"
5622
  HTYPE = constants.HTYPE_INSTANCE
5623
  REQ_BGL = False
5624

    
5625
  def ExpandNames(self):
5626
    self._ExpandAndLockInstance()
5627

    
5628
  def BuildHooksEnv(self):
5629
    """Build hooks env.
5630

5631
    This runs on master, primary and secondary nodes of the instance.
5632

5633
    """
5634
    env = {
5635
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5636
      "REBOOT_TYPE": self.op.reboot_type,
5637
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5638
      }
5639

    
5640
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5641

    
5642
    return env
5643

    
5644
  def BuildHooksNodes(self):
5645
    """Build hooks nodes.
5646

5647
    """
5648
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5649
    return (nl, nl)
5650

    
5651
  def CheckPrereq(self):
5652
    """Check prerequisites.
5653

5654
    This checks that the instance is in the cluster.
5655

5656
    """
5657
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5658
    assert self.instance is not None, \
5659
      "Cannot retrieve locked instance %s" % self.op.instance_name
5660

    
5661
    _CheckNodeOnline(self, instance.primary_node)
5662

    
5663
    # check bridges existence
5664
    _CheckInstanceBridgesExist(self, instance)
5665

    
5666
  def Exec(self, feedback_fn):
5667
    """Reboot the instance.
5668

5669
    """
5670
    instance = self.instance
5671
    ignore_secondaries = self.op.ignore_secondaries
5672
    reboot_type = self.op.reboot_type
5673

    
5674
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5675
                                              instance.name,
5676
                                              instance.hypervisor)
5677
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5678
    instance_running = bool(remote_info.payload)
5679

    
5680
    node_current = instance.primary_node
5681

    
5682
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5683
                                            constants.INSTANCE_REBOOT_HARD]:
5684
      for disk in instance.disks:
5685
        self.cfg.SetDiskID(disk, node_current)
5686
      result = self.rpc.call_instance_reboot(node_current, instance,
5687
                                             reboot_type,
5688
                                             self.op.shutdown_timeout)
5689
      result.Raise("Could not reboot instance")
5690
    else:
5691
      if instance_running:
5692
        result = self.rpc.call_instance_shutdown(node_current, instance,
5693
                                                 self.op.shutdown_timeout)
5694
        result.Raise("Could not shutdown instance for full reboot")
5695
        _ShutdownInstanceDisks(self, instance)
5696
      else:
5697
        self.LogInfo("Instance %s was already stopped, starting now",
5698
                     instance.name)
5699
      _StartInstanceDisks(self, instance, ignore_secondaries)
5700
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5701
      msg = result.fail_msg
5702
      if msg:
5703
        _ShutdownInstanceDisks(self, instance)
5704
        raise errors.OpExecError("Could not start instance for"
5705
                                 " full reboot: %s" % msg)
5706

    
5707
    self.cfg.MarkInstanceUp(instance.name)
5708

    
5709

    
5710
class LUInstanceShutdown(LogicalUnit):
5711
  """Shutdown an instance.
5712

5713
  """
5714
  HPATH = "instance-stop"
5715
  HTYPE = constants.HTYPE_INSTANCE
5716
  REQ_BGL = False
5717

    
5718
  def ExpandNames(self):
5719
    self._ExpandAndLockInstance()
5720

    
5721
  def BuildHooksEnv(self):
5722
    """Build hooks env.
5723

5724
    This runs on master, primary and secondary nodes of the instance.
5725

5726
    """
5727
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5728
    env["TIMEOUT"] = self.op.timeout
5729
    return env
5730

    
5731
  def BuildHooksNodes(self):
5732
    """Build hooks nodes.
5733

5734
    """
5735
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5736
    return (nl, nl)
5737

    
5738
  def CheckPrereq(self):
5739
    """Check prerequisites.
5740

5741
    This checks that the instance is in the cluster.
5742

5743
    """
5744
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5745
    assert self.instance is not None, \
5746
      "Cannot retrieve locked instance %s" % self.op.instance_name
5747

    
5748
    self.primary_offline = \
5749
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5750

    
5751
    if self.primary_offline and self.op.ignore_offline_nodes:
5752
      self.proc.LogWarning("Ignoring offline primary node")
5753
    else:
5754
      _CheckNodeOnline(self, self.instance.primary_node)
5755

    
5756
  def Exec(self, feedback_fn):
5757
    """Shutdown the instance.
5758

5759
    """
5760
    instance = self.instance
5761
    node_current = instance.primary_node
5762
    timeout = self.op.timeout
5763

    
5764
    if not self.op.no_remember:
5765
      self.cfg.MarkInstanceDown(instance.name)
5766

    
5767
    if self.primary_offline:
5768
      assert self.op.ignore_offline_nodes
5769
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5770
    else:
5771
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5772
      msg = result.fail_msg
5773
      if msg:
5774
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5775

    
5776
      _ShutdownInstanceDisks(self, instance)
5777

    
5778

    
5779
class LUInstanceReinstall(LogicalUnit):
5780
  """Reinstall an instance.
5781

5782
  """
5783
  HPATH = "instance-reinstall"
5784
  HTYPE = constants.HTYPE_INSTANCE
5785
  REQ_BGL = False
5786

    
5787
  def ExpandNames(self):
5788
    self._ExpandAndLockInstance()
5789

    
5790
  def BuildHooksEnv(self):
5791
    """Build hooks env.
5792

5793
    This runs on master, primary and secondary nodes of the instance.
5794

5795
    """
5796
    return _BuildInstanceHookEnvByObject(self, self.instance)
5797

    
5798
  def BuildHooksNodes(self):
5799
    """Build hooks nodes.
5800

5801
    """
5802
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5803
    return (nl, nl)
5804

    
5805
  def CheckPrereq(self):
5806
    """Check prerequisites.
5807

5808
    This checks that the instance is in the cluster and is not running.
5809

5810
    """
5811
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5812
    assert instance is not None, \
5813
      "Cannot retrieve locked instance %s" % self.op.instance_name
5814
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5815
                     " offline, cannot reinstall")
5816
    for node in instance.secondary_nodes:
5817
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5818
                       " cannot reinstall")
5819

    
5820
    if instance.disk_template == constants.DT_DISKLESS:
5821
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5822
                                 self.op.instance_name,
5823
                                 errors.ECODE_INVAL)
5824
    _CheckInstanceDown(self, instance, "cannot reinstall")
5825

    
5826
    if self.op.os_type is not None:
5827
      # OS verification
5828
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5829
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5830
      instance_os = self.op.os_type
5831
    else:
5832
      instance_os = instance.os
5833

    
5834
    nodelist = list(instance.all_nodes)
5835

    
5836
    if self.op.osparams:
5837
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5838
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5839
      self.os_inst = i_osdict # the new dict (without defaults)
5840
    else:
5841
      self.os_inst = None
5842

    
5843
    self.instance = instance
5844

    
5845
  def Exec(self, feedback_fn):
5846
    """Reinstall the instance.
5847

5848
    """
5849
    inst = self.instance
5850

    
5851
    if self.op.os_type is not None:
5852
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5853
      inst.os = self.op.os_type
5854
      # Write to configuration
5855
      self.cfg.Update(inst, feedback_fn)
5856

    
5857
    _StartInstanceDisks(self, inst, None)
5858
    try:
5859
      feedback_fn("Running the instance OS create scripts...")
5860
      # FIXME: pass debug option from opcode to backend
5861
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5862
                                             self.op.debug_level,
5863
                                             osparams=self.os_inst)
5864
      result.Raise("Could not install OS for instance %s on node %s" %
5865
                   (inst.name, inst.primary_node))
5866
    finally:
5867
      _ShutdownInstanceDisks(self, inst)
5868

    
5869

    
5870
class LUInstanceRecreateDisks(LogicalUnit):
5871
  """Recreate an instance's missing disks.
5872

5873
  """
5874
  HPATH = "instance-recreate-disks"
5875
  HTYPE = constants.HTYPE_INSTANCE
5876
  REQ_BGL = False
5877

    
5878
  def CheckArguments(self):
5879
    # normalise the disk list
5880
    self.op.disks = sorted(frozenset(self.op.disks))
5881

    
5882
  def ExpandNames(self):
5883
    self._ExpandAndLockInstance()
5884
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5885
    if self.op.nodes:
5886
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5887
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5888
    else:
5889
      self.needed_locks[locking.LEVEL_NODE] = []
5890

    
5891
  def DeclareLocks(self, level):
5892
    if level == locking.LEVEL_NODE:
5893
      # if we replace the nodes, we only need to lock the old primary,
5894
      # otherwise we need to lock all nodes for disk re-creation
5895
      primary_only = bool(self.op.nodes)
5896
      self._LockInstancesNodes(primary_only=primary_only)
5897

    
5898
  def BuildHooksEnv(self):
5899
    """Build hooks env.
5900

5901
    This runs on master, primary and secondary nodes of the instance.
5902

5903
    """
5904
    return _BuildInstanceHookEnvByObject(self, self.instance)
5905

    
5906
  def BuildHooksNodes(self):
5907
    """Build hooks nodes.
5908

5909
    """
5910
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5911
    return (nl, nl)
5912

    
5913
  def CheckPrereq(self):
5914
    """Check prerequisites.
5915

5916
    This checks that the instance is in the cluster and is not running.
5917

5918
    """
5919
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5920
    assert instance is not None, \
5921
      "Cannot retrieve locked instance %s" % self.op.instance_name
5922
    if self.op.nodes:
5923
      if len(self.op.nodes) != len(instance.all_nodes):
5924
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
5925
                                   " %d replacement nodes were specified" %
5926
                                   (instance.name, len(instance.all_nodes),
5927
                                    len(self.op.nodes)),
5928
                                   errors.ECODE_INVAL)
5929
      assert instance.disk_template != constants.DT_DRBD8 or \
5930
          len(self.op.nodes) == 2
5931
      assert instance.disk_template != constants.DT_PLAIN or \
5932
          len(self.op.nodes) == 1
5933
      primary_node = self.op.nodes[0]
5934
    else:
5935
      primary_node = instance.primary_node
5936
    _CheckNodeOnline(self, primary_node)
5937

    
5938
    if instance.disk_template == constants.DT_DISKLESS:
5939
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5940
                                 self.op.instance_name, errors.ECODE_INVAL)
5941
    # if we replace nodes *and* the old primary is offline, we don't
5942
    # check
5943
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
5944
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
5945
    if not (self.op.nodes and old_pnode.offline):
5946
      _CheckInstanceDown(self, instance, "cannot recreate disks")
5947

    
5948
    if not self.op.disks:
5949
      self.op.disks = range(len(instance.disks))
5950
    else:
5951
      for idx in self.op.disks:
5952
        if idx >= len(instance.disks):
5953
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
5954
                                     errors.ECODE_INVAL)
5955
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
5956
      raise errors.OpPrereqError("Can't recreate disks partially and"
5957
                                 " change the nodes at the same time",
5958
                                 errors.ECODE_INVAL)
5959
    self.instance = instance
5960

    
5961
  def Exec(self, feedback_fn):
5962
    """Recreate the disks.
5963

5964
    """
5965
    # change primary node, if needed
5966
    if self.op.nodes:
5967
      self.instance.primary_node = self.op.nodes[0]
5968
      self.LogWarning("Changing the instance's nodes, you will have to"
5969
                      " remove any disks left on the older nodes manually")
5970

    
5971
    to_skip = []
5972
    for idx, disk in enumerate(self.instance.disks):
5973
      if idx not in self.op.disks: # disk idx has not been passed in
5974
        to_skip.append(idx)
5975
        continue
5976
      # update secondaries for disks, if needed
5977
      if self.op.nodes:
5978
        if disk.dev_type == constants.LD_DRBD8:
5979
          # need to update the nodes
5980
          assert len(self.op.nodes) == 2
5981
          logical_id = list(disk.logical_id)
5982
          logical_id[0] = self.op.nodes[0]
5983
          logical_id[1] = self.op.nodes[1]
5984
          disk.logical_id = tuple(logical_id)
5985

    
5986
    if self.op.nodes:
5987
      self.cfg.Update(self.instance, feedback_fn)
5988

    
5989
    _CreateDisks(self, self.instance, to_skip=to_skip)
5990

    
5991

    
5992
class LUInstanceRename(LogicalUnit):
5993
  """Rename an instance.
5994

5995
  """
5996
  HPATH = "instance-rename"
5997
  HTYPE = constants.HTYPE_INSTANCE
5998

    
5999
  def CheckArguments(self):
6000
    """Check arguments.
6001

6002
    """
6003
    if self.op.ip_check and not self.op.name_check:
6004
      # TODO: make the ip check more flexible and not depend on the name check
6005
      raise errors.OpPrereqError("IP address check requires a name check",
6006
                                 errors.ECODE_INVAL)
6007

    
6008
  def BuildHooksEnv(self):
6009
    """Build hooks env.
6010

6011
    This runs on master, primary and secondary nodes of the instance.
6012

6013
    """
6014
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6015
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6016
    return env
6017

    
6018
  def BuildHooksNodes(self):
6019
    """Build hooks nodes.
6020

6021
    """
6022
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6023
    return (nl, nl)
6024

    
6025
  def CheckPrereq(self):
6026
    """Check prerequisites.
6027

6028
    This checks that the instance is in the cluster and is not running.
6029

6030
    """
6031
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6032
                                                self.op.instance_name)
6033
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6034
    assert instance is not None
6035
    _CheckNodeOnline(self, instance.primary_node)
6036
    _CheckInstanceDown(self, instance, "cannot rename")
6037
    self.instance = instance
6038

    
6039
    new_name = self.op.new_name
6040
    if self.op.name_check:
6041
      hostname = netutils.GetHostname(name=new_name)
6042
      if hostname != new_name:
6043
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6044
                     hostname.name)
6045
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6046
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6047
                                    " same as given hostname '%s'") %
6048
                                    (hostname.name, self.op.new_name),
6049
                                    errors.ECODE_INVAL)
6050
      new_name = self.op.new_name = hostname.name
6051
      if (self.op.ip_check and
6052
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6053
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6054
                                   (hostname.ip, new_name),
6055
                                   errors.ECODE_NOTUNIQUE)
6056

    
6057
    instance_list = self.cfg.GetInstanceList()
6058
    if new_name in instance_list and new_name != instance.name:
6059
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6060
                                 new_name, errors.ECODE_EXISTS)
6061

    
6062
  def Exec(self, feedback_fn):
6063
    """Rename the instance.
6064

6065
    """
6066
    inst = self.instance
6067
    old_name = inst.name
6068

    
6069
    rename_file_storage = False
6070
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
6071
        self.op.new_name != inst.name):
6072
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6073
      rename_file_storage = True
6074

    
6075
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6076
    # Change the instance lock. This is definitely safe while we hold the BGL.
6077
    # Otherwise the new lock would have to be added in acquired mode.
6078
    assert self.REQ_BGL
6079
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6080
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6081

    
6082
    # re-read the instance from the configuration after rename
6083
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6084

    
6085
    if rename_file_storage:
6086
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6087
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6088
                                                     old_file_storage_dir,
6089
                                                     new_file_storage_dir)
6090
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6091
                   " (but the instance has been renamed in Ganeti)" %
6092
                   (inst.primary_node, old_file_storage_dir,
6093
                    new_file_storage_dir))
6094

    
6095
    _StartInstanceDisks(self, inst, None)
6096
    try:
6097
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6098
                                                 old_name, self.op.debug_level)
6099
      msg = result.fail_msg
6100
      if msg:
6101
        msg = ("Could not run OS rename script for instance %s on node %s"
6102
               " (but the instance has been renamed in Ganeti): %s" %
6103
               (inst.name, inst.primary_node, msg))
6104
        self.proc.LogWarning(msg)
6105
    finally:
6106
      _ShutdownInstanceDisks(self, inst)
6107

    
6108
    return inst.name
6109

    
6110

    
6111
class LUInstanceRemove(LogicalUnit):
6112
  """Remove an instance.
6113

6114
  """
6115
  HPATH = "instance-remove"
6116
  HTYPE = constants.HTYPE_INSTANCE
6117
  REQ_BGL = False
6118

    
6119
  def ExpandNames(self):
6120
    self._ExpandAndLockInstance()
6121
    self.needed_locks[locking.LEVEL_NODE] = []
6122
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6123

    
6124
  def DeclareLocks(self, level):
6125
    if level == locking.LEVEL_NODE:
6126
      self._LockInstancesNodes()
6127

    
6128
  def BuildHooksEnv(self):
6129
    """Build hooks env.
6130

6131
    This runs on master, primary and secondary nodes of the instance.
6132

6133
    """
6134
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6135
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6136
    return env
6137

    
6138
  def BuildHooksNodes(self):
6139
    """Build hooks nodes.
6140

6141
    """
6142
    nl = [self.cfg.GetMasterNode()]
6143
    nl_post = list(self.instance.all_nodes) + nl
6144
    return (nl, nl_post)
6145

    
6146
  def CheckPrereq(self):
6147
    """Check prerequisites.
6148

6149
    This checks that the instance is in the cluster.
6150

6151
    """
6152
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6153
    assert self.instance is not None, \
6154
      "Cannot retrieve locked instance %s" % self.op.instance_name
6155

    
6156
  def Exec(self, feedback_fn):
6157
    """Remove the instance.
6158

6159
    """
6160
    instance = self.instance
6161
    logging.info("Shutting down instance %s on node %s",
6162
                 instance.name, instance.primary_node)
6163

    
6164
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6165
                                             self.op.shutdown_timeout)
6166
    msg = result.fail_msg
6167
    if msg:
6168
      if self.op.ignore_failures:
6169
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6170
      else:
6171
        raise errors.OpExecError("Could not shutdown instance %s on"
6172
                                 " node %s: %s" %
6173
                                 (instance.name, instance.primary_node, msg))
6174

    
6175
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6176

    
6177

    
6178
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6179
  """Utility function to remove an instance.
6180

6181
  """
6182
  logging.info("Removing block devices for instance %s", instance.name)
6183

    
6184
  if not _RemoveDisks(lu, instance):
6185
    if not ignore_failures:
6186
      raise errors.OpExecError("Can't remove instance's disks")
6187
    feedback_fn("Warning: can't remove instance's disks")
6188

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

    
6191
  lu.cfg.RemoveInstance(instance.name)
6192

    
6193
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6194
    "Instance lock removal conflict"
6195

    
6196
  # Remove lock for the instance
6197
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6198

    
6199

    
6200
class LUInstanceQuery(NoHooksLU):
6201
  """Logical unit for querying instances.
6202

6203
  """
6204
  # pylint: disable-msg=W0142
6205
  REQ_BGL = False
6206

    
6207
  def CheckArguments(self):
6208
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6209
                             self.op.output_fields, self.op.use_locking)
6210

    
6211
  def ExpandNames(self):
6212
    self.iq.ExpandNames(self)
6213

    
6214
  def DeclareLocks(self, level):
6215
    self.iq.DeclareLocks(self, level)
6216

    
6217
  def Exec(self, feedback_fn):
6218
    return self.iq.OldStyleQuery(self)
6219

    
6220

    
6221
class LUInstanceFailover(LogicalUnit):
6222
  """Failover an instance.
6223

6224
  """
6225
  HPATH = "instance-failover"
6226
  HTYPE = constants.HTYPE_INSTANCE
6227
  REQ_BGL = False
6228

    
6229
  def CheckArguments(self):
6230
    """Check the arguments.
6231

6232
    """
6233
    self.iallocator = getattr(self.op, "iallocator", None)
6234
    self.target_node = getattr(self.op, "target_node", None)
6235

    
6236
  def ExpandNames(self):
6237
    self._ExpandAndLockInstance()
6238

    
6239
    if self.op.target_node is not None:
6240
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6241

    
6242
    self.needed_locks[locking.LEVEL_NODE] = []
6243
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6244

    
6245
    ignore_consistency = self.op.ignore_consistency
6246
    shutdown_timeout = self.op.shutdown_timeout
6247
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6248
                                       cleanup=False,
6249
                                       failover=True,
6250
                                       ignore_consistency=ignore_consistency,
6251
                                       shutdown_timeout=shutdown_timeout)
6252
    self.tasklets = [self._migrater]
6253

    
6254
  def DeclareLocks(self, level):
6255
    if level == locking.LEVEL_NODE:
6256
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6257
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6258
        if self.op.target_node is None:
6259
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6260
        else:
6261
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6262
                                                   self.op.target_node]
6263
        del self.recalculate_locks[locking.LEVEL_NODE]
6264
      else:
6265
        self._LockInstancesNodes()
6266

    
6267
  def BuildHooksEnv(self):
6268
    """Build hooks env.
6269

6270
    This runs on master, primary and secondary nodes of the instance.
6271

6272
    """
6273
    instance = self._migrater.instance
6274
    source_node = instance.primary_node
6275
    target_node = self.op.target_node
6276
    env = {
6277
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6278
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6279
      "OLD_PRIMARY": source_node,
6280
      "NEW_PRIMARY": target_node,
6281
      }
6282

    
6283
    if instance.disk_template in constants.DTS_INT_MIRROR:
6284
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6285
      env["NEW_SECONDARY"] = source_node
6286
    else:
6287
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6288

    
6289
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6290

    
6291
    return env
6292

    
6293
  def BuildHooksNodes(self):
6294
    """Build hooks nodes.
6295

6296
    """
6297
    instance = self._migrater.instance
6298
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6299
    return (nl, nl + [instance.primary_node])
6300

    
6301

    
6302
class LUInstanceMigrate(LogicalUnit):
6303
  """Migrate an instance.
6304

6305
  This is migration without shutting down, compared to the failover,
6306
  which is done with shutdown.
6307

6308
  """
6309
  HPATH = "instance-migrate"
6310
  HTYPE = constants.HTYPE_INSTANCE
6311
  REQ_BGL = False
6312

    
6313
  def ExpandNames(self):
6314
    self._ExpandAndLockInstance()
6315

    
6316
    if self.op.target_node is not None:
6317
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6318

    
6319
    self.needed_locks[locking.LEVEL_NODE] = []
6320
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6321

    
6322
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6323
                                       cleanup=self.op.cleanup,
6324
                                       failover=False,
6325
                                       fallback=self.op.allow_failover)
6326
    self.tasklets = [self._migrater]
6327

    
6328
  def DeclareLocks(self, level):
6329
    if level == locking.LEVEL_NODE:
6330
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6331
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6332
        if self.op.target_node is None:
6333
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6334
        else:
6335
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6336
                                                   self.op.target_node]
6337
        del self.recalculate_locks[locking.LEVEL_NODE]
6338
      else:
6339
        self._LockInstancesNodes()
6340

    
6341
  def BuildHooksEnv(self):
6342
    """Build hooks env.
6343

6344
    This runs on master, primary and secondary nodes of the instance.
6345

6346
    """
6347
    instance = self._migrater.instance
6348
    source_node = instance.primary_node
6349
    target_node = self.op.target_node
6350
    env = _BuildInstanceHookEnvByObject(self, instance)
6351
    env.update({
6352
      "MIGRATE_LIVE": self._migrater.live,
6353
      "MIGRATE_CLEANUP": self.op.cleanup,
6354
      "OLD_PRIMARY": source_node,
6355
      "NEW_PRIMARY": target_node,
6356
      })
6357

    
6358
    if instance.disk_template in constants.DTS_INT_MIRROR:
6359
      env["OLD_SECONDARY"] = target_node
6360
      env["NEW_SECONDARY"] = source_node
6361
    else:
6362
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6363

    
6364
    return env
6365

    
6366
  def BuildHooksNodes(self):
6367
    """Build hooks nodes.
6368

6369
    """
6370
    instance = self._migrater.instance
6371
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6372
    return (nl, nl + [instance.primary_node])
6373

    
6374

    
6375
class LUInstanceMove(LogicalUnit):
6376
  """Move an instance by data-copying.
6377

6378
  """
6379
  HPATH = "instance-move"
6380
  HTYPE = constants.HTYPE_INSTANCE
6381
  REQ_BGL = False
6382

    
6383
  def ExpandNames(self):
6384
    self._ExpandAndLockInstance()
6385
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6386
    self.op.target_node = target_node
6387
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6388
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6389

    
6390
  def DeclareLocks(self, level):
6391
    if level == locking.LEVEL_NODE:
6392
      self._LockInstancesNodes(primary_only=True)
6393

    
6394
  def BuildHooksEnv(self):
6395
    """Build hooks env.
6396

6397
    This runs on master, primary and secondary nodes of the instance.
6398

6399
    """
6400
    env = {
6401
      "TARGET_NODE": self.op.target_node,
6402
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6403
      }
6404
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6405
    return env
6406

    
6407
  def BuildHooksNodes(self):
6408
    """Build hooks nodes.
6409

6410
    """
6411
    nl = [
6412
      self.cfg.GetMasterNode(),
6413
      self.instance.primary_node,
6414
      self.op.target_node,
6415
      ]
6416
    return (nl, nl)
6417

    
6418
  def CheckPrereq(self):
6419
    """Check prerequisites.
6420

6421
    This checks that the instance is in the cluster.
6422

6423
    """
6424
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6425
    assert self.instance is not None, \
6426
      "Cannot retrieve locked instance %s" % self.op.instance_name
6427

    
6428
    node = self.cfg.GetNodeInfo(self.op.target_node)
6429
    assert node is not None, \
6430
      "Cannot retrieve locked node %s" % self.op.target_node
6431

    
6432
    self.target_node = target_node = node.name
6433

    
6434
    if target_node == instance.primary_node:
6435
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6436
                                 (instance.name, target_node),
6437
                                 errors.ECODE_STATE)
6438

    
6439
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6440

    
6441
    for idx, dsk in enumerate(instance.disks):
6442
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6443
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6444
                                   " cannot copy" % idx, errors.ECODE_STATE)
6445

    
6446
    _CheckNodeOnline(self, target_node)
6447
    _CheckNodeNotDrained(self, target_node)
6448
    _CheckNodeVmCapable(self, target_node)
6449

    
6450
    if instance.admin_up:
6451
      # check memory requirements on the secondary node
6452
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6453
                           instance.name, bep[constants.BE_MEMORY],
6454
                           instance.hypervisor)
6455
    else:
6456
      self.LogInfo("Not checking memory on the secondary node as"
6457
                   " instance will not be started")
6458

    
6459
    # check bridge existance
6460
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6461

    
6462
  def Exec(self, feedback_fn):
6463
    """Move an instance.
6464

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

6468
    """
6469
    instance = self.instance
6470

    
6471
    source_node = instance.primary_node
6472
    target_node = self.target_node
6473

    
6474
    self.LogInfo("Shutting down instance %s on source node %s",
6475
                 instance.name, source_node)
6476

    
6477
    result = self.rpc.call_instance_shutdown(source_node, instance,
6478
                                             self.op.shutdown_timeout)
6479
    msg = result.fail_msg
6480
    if msg:
6481
      if self.op.ignore_consistency:
6482
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6483
                             " Proceeding anyway. Please make sure node"
6484
                             " %s is down. Error details: %s",
6485
                             instance.name, source_node, source_node, msg)
6486
      else:
6487
        raise errors.OpExecError("Could not shutdown instance %s on"
6488
                                 " node %s: %s" %
6489
                                 (instance.name, source_node, msg))
6490

    
6491
    # create the target disks
6492
    try:
6493
      _CreateDisks(self, instance, target_node=target_node)
6494
    except errors.OpExecError:
6495
      self.LogWarning("Device creation failed, reverting...")
6496
      try:
6497
        _RemoveDisks(self, instance, target_node=target_node)
6498
      finally:
6499
        self.cfg.ReleaseDRBDMinors(instance.name)
6500
        raise
6501

    
6502
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6503

    
6504
    errs = []
6505
    # activate, get path, copy the data over
6506
    for idx, disk in enumerate(instance.disks):
6507
      self.LogInfo("Copying data for disk %d", idx)
6508
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6509
                                               instance.name, True, idx)
6510
      if result.fail_msg:
6511
        self.LogWarning("Can't assemble newly created disk %d: %s",
6512
                        idx, result.fail_msg)
6513
        errs.append(result.fail_msg)
6514
        break
6515
      dev_path = result.payload
6516
      result = self.rpc.call_blockdev_export(source_node, disk,
6517
                                             target_node, dev_path,
6518
                                             cluster_name)
6519
      if result.fail_msg:
6520
        self.LogWarning("Can't copy data over for disk %d: %s",
6521
                        idx, result.fail_msg)
6522
        errs.append(result.fail_msg)
6523
        break
6524

    
6525
    if errs:
6526
      self.LogWarning("Some disks failed to copy, aborting")
6527
      try:
6528
        _RemoveDisks(self, instance, target_node=target_node)
6529
      finally:
6530
        self.cfg.ReleaseDRBDMinors(instance.name)
6531
        raise errors.OpExecError("Errors during disk copy: %s" %
6532
                                 (",".join(errs),))
6533

    
6534
    instance.primary_node = target_node
6535
    self.cfg.Update(instance, feedback_fn)
6536

    
6537
    self.LogInfo("Removing the disks on the original node")
6538
    _RemoveDisks(self, instance, target_node=source_node)
6539

    
6540
    # Only start the instance if it's marked as up
6541
    if instance.admin_up:
6542
      self.LogInfo("Starting instance %s on node %s",
6543
                   instance.name, target_node)
6544

    
6545
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6546
                                           ignore_secondaries=True)
6547
      if not disks_ok:
6548
        _ShutdownInstanceDisks(self, instance)
6549
        raise errors.OpExecError("Can't activate the instance's disks")
6550

    
6551
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6552
      msg = result.fail_msg
6553
      if msg:
6554
        _ShutdownInstanceDisks(self, instance)
6555
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6556
                                 (instance.name, target_node, msg))
6557

    
6558

    
6559
class LUNodeMigrate(LogicalUnit):
6560
  """Migrate all instances from a node.
6561

6562
  """
6563
  HPATH = "node-migrate"
6564
  HTYPE = constants.HTYPE_NODE
6565
  REQ_BGL = False
6566

    
6567
  def CheckArguments(self):
6568
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6569

    
6570
  def ExpandNames(self):
6571
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6572

    
6573
    self.needed_locks = {}
6574

    
6575
    # Create tasklets for migrating instances for all instances on this node
6576
    names = []
6577
    tasklets = []
6578

    
6579
    self.lock_all_nodes = False
6580

    
6581
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6582
      logging.debug("Migrating instance %s", inst.name)
6583
      names.append(inst.name)
6584

    
6585
      tasklets.append(TLMigrateInstance(self, inst.name, cleanup=False))
6586

    
6587
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6588
        # We need to lock all nodes, as the iallocator will choose the
6589
        # destination nodes afterwards
6590
        self.lock_all_nodes = True
6591

    
6592
    self.tasklets = tasklets
6593

    
6594
    # Declare node locks
6595
    if self.lock_all_nodes:
6596
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6597
    else:
6598
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6599
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6600

    
6601
    # Declare instance locks
6602
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6603

    
6604
  def DeclareLocks(self, level):
6605
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6606
      self._LockInstancesNodes()
6607

    
6608
  def BuildHooksEnv(self):
6609
    """Build hooks env.
6610

6611
    This runs on the master, the primary and all the secondaries.
6612

6613
    """
6614
    return {
6615
      "NODE_NAME": self.op.node_name,
6616
      }
6617

    
6618
  def BuildHooksNodes(self):
6619
    """Build hooks nodes.
6620

6621
    """
6622
    nl = [self.cfg.GetMasterNode()]
6623
    return (nl, nl)
6624

    
6625

    
6626
class TLMigrateInstance(Tasklet):
6627
  """Tasklet class for instance migration.
6628

6629
  @type live: boolean
6630
  @ivar live: whether the migration will be done live or non-live;
6631
      this variable is initalized only after CheckPrereq has run
6632
  @type cleanup: boolean
6633
  @ivar cleanup: Wheater we cleanup from a failed migration
6634
  @type iallocator: string
6635
  @ivar iallocator: The iallocator used to determine target_node
6636
  @type target_node: string
6637
  @ivar target_node: If given, the target_node to reallocate the instance to
6638
  @type failover: boolean
6639
  @ivar failover: Whether operation results in failover or migration
6640
  @type fallback: boolean
6641
  @ivar fallback: Whether fallback to failover is allowed if migration not
6642
                  possible
6643
  @type ignore_consistency: boolean
6644
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6645
                            and target node
6646
  @type shutdown_timeout: int
6647
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6648

6649
  """
6650
  def __init__(self, lu, instance_name, cleanup=False,
6651
               failover=False, fallback=False,
6652
               ignore_consistency=False,
6653
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6654
    """Initializes this class.
6655

6656
    """
6657
    Tasklet.__init__(self, lu)
6658

    
6659
    # Parameters
6660
    self.instance_name = instance_name
6661
    self.cleanup = cleanup
6662
    self.live = False # will be overridden later
6663
    self.failover = failover
6664
    self.fallback = fallback
6665
    self.ignore_consistency = ignore_consistency
6666
    self.shutdown_timeout = shutdown_timeout
6667

    
6668
  def CheckPrereq(self):
6669
    """Check prerequisites.
6670

6671
    This checks that the instance is in the cluster.
6672

6673
    """
6674
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6675
    instance = self.cfg.GetInstanceInfo(instance_name)
6676
    assert instance is not None
6677
    self.instance = instance
6678

    
6679
    if (not self.cleanup and not instance.admin_up and not self.failover and
6680
        self.fallback):
6681
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6682
                      " to failover")
6683
      self.failover = True
6684

    
6685
    if instance.disk_template not in constants.DTS_MIRRORED:
6686
      if self.failover:
6687
        text = "failovers"
6688
      else:
6689
        text = "migrations"
6690
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6691
                                 " %s" % (instance.disk_template, text),
6692
                                 errors.ECODE_STATE)
6693

    
6694
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6695
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6696

    
6697
      if self.lu.op.iallocator:
6698
        self._RunAllocator()
6699
      else:
6700
        # We set set self.target_node as it is required by
6701
        # BuildHooksEnv
6702
        self.target_node = self.lu.op.target_node
6703

    
6704
      # self.target_node is already populated, either directly or by the
6705
      # iallocator run
6706
      target_node = self.target_node
6707
      if self.target_node == instance.primary_node:
6708
        raise errors.OpPrereqError("Cannot migrate instance %s"
6709
                                   " to its primary (%s)" %
6710
                                   (instance.name, instance.primary_node))
6711

    
6712
      if len(self.lu.tasklets) == 1:
6713
        # It is safe to release locks only when we're the only tasklet
6714
        # in the LU
6715
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6716
                      keep=[instance.primary_node, self.target_node])
6717

    
6718
    else:
6719
      secondary_nodes = instance.secondary_nodes
6720
      if not secondary_nodes:
6721
        raise errors.ConfigurationError("No secondary node but using"
6722
                                        " %s disk template" %
6723
                                        instance.disk_template)
6724
      target_node = secondary_nodes[0]
6725
      if self.lu.op.iallocator or (self.lu.op.target_node and
6726
                                   self.lu.op.target_node != target_node):
6727
        if self.failover:
6728
          text = "failed over"
6729
        else:
6730
          text = "migrated"
6731
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6732
                                   " be %s to arbitrary nodes"
6733
                                   " (neither an iallocator nor a target"
6734
                                   " node can be passed)" %
6735
                                   (instance.disk_template, text),
6736
                                   errors.ECODE_INVAL)
6737

    
6738
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6739

    
6740
    # check memory requirements on the secondary node
6741
    if not self.failover or instance.admin_up:
6742
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6743
                           instance.name, i_be[constants.BE_MEMORY],
6744
                           instance.hypervisor)
6745
    else:
6746
      self.lu.LogInfo("Not checking memory on the secondary node as"
6747
                      " instance will not be started")
6748

    
6749
    # check bridge existance
6750
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6751

    
6752
    if not self.cleanup:
6753
      _CheckNodeNotDrained(self.lu, target_node)
6754
      if not self.failover:
6755
        result = self.rpc.call_instance_migratable(instance.primary_node,
6756
                                                   instance)
6757
        if result.fail_msg and self.fallback:
6758
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6759
                          " failover")
6760
          self.failover = True
6761
        else:
6762
          result.Raise("Can't migrate, please use failover",
6763
                       prereq=True, ecode=errors.ECODE_STATE)
6764

    
6765
    assert not (self.failover and self.cleanup)
6766

    
6767
    if not self.failover:
6768
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6769
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6770
                                   " parameters are accepted",
6771
                                   errors.ECODE_INVAL)
6772
      if self.lu.op.live is not None:
6773
        if self.lu.op.live:
6774
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6775
        else:
6776
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6777
        # reset the 'live' parameter to None so that repeated
6778
        # invocations of CheckPrereq do not raise an exception
6779
        self.lu.op.live = None
6780
      elif self.lu.op.mode is None:
6781
        # read the default value from the hypervisor
6782
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6783
                                                skip_globals=False)
6784
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6785

    
6786
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6787
    else:
6788
      # Failover is never live
6789
      self.live = False
6790

    
6791
  def _RunAllocator(self):
6792
    """Run the allocator based on input opcode.
6793

6794
    """
6795
    ial = IAllocator(self.cfg, self.rpc,
6796
                     mode=constants.IALLOCATOR_MODE_RELOC,
6797
                     name=self.instance_name,
6798
                     # TODO See why hail breaks with a single node below
6799
                     relocate_from=[self.instance.primary_node,
6800
                                    self.instance.primary_node],
6801
                     )
6802

    
6803
    ial.Run(self.lu.op.iallocator)
6804

    
6805
    if not ial.success:
6806
      raise errors.OpPrereqError("Can't compute nodes using"
6807
                                 " iallocator '%s': %s" %
6808
                                 (self.lu.op.iallocator, ial.info),
6809
                                 errors.ECODE_NORES)
6810
    if len(ial.result) != ial.required_nodes:
6811
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6812
                                 " of nodes (%s), required %s" %
6813
                                 (self.lu.op.iallocator, len(ial.result),
6814
                                  ial.required_nodes), errors.ECODE_FAULT)
6815
    self.target_node = ial.result[0]
6816
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6817
                 self.instance_name, self.lu.op.iallocator,
6818
                 utils.CommaJoin(ial.result))
6819

    
6820
  def _WaitUntilSync(self):
6821
    """Poll with custom rpc for disk sync.
6822

6823
    This uses our own step-based rpc call.
6824

6825
    """
6826
    self.feedback_fn("* wait until resync is done")
6827
    all_done = False
6828
    while not all_done:
6829
      all_done = True
6830
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6831
                                            self.nodes_ip,
6832
                                            self.instance.disks)
6833
      min_percent = 100
6834
      for node, nres in result.items():
6835
        nres.Raise("Cannot resync disks on node %s" % node)
6836
        node_done, node_percent = nres.payload
6837
        all_done = all_done and node_done
6838
        if node_percent is not None:
6839
          min_percent = min(min_percent, node_percent)
6840
      if not all_done:
6841
        if min_percent < 100:
6842
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6843
        time.sleep(2)
6844

    
6845
  def _EnsureSecondary(self, node):
6846
    """Demote a node to secondary.
6847

6848
    """
6849
    self.feedback_fn("* switching node %s to secondary mode" % node)
6850

    
6851
    for dev in self.instance.disks:
6852
      self.cfg.SetDiskID(dev, node)
6853

    
6854
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6855
                                          self.instance.disks)
6856
    result.Raise("Cannot change disk to secondary on node %s" % node)
6857

    
6858
  def _GoStandalone(self):
6859
    """Disconnect from the network.
6860

6861
    """
6862
    self.feedback_fn("* changing into standalone mode")
6863
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6864
                                               self.instance.disks)
6865
    for node, nres in result.items():
6866
      nres.Raise("Cannot disconnect disks node %s" % node)
6867

    
6868
  def _GoReconnect(self, multimaster):
6869
    """Reconnect to the network.
6870

6871
    """
6872
    if multimaster:
6873
      msg = "dual-master"
6874
    else:
6875
      msg = "single-master"
6876
    self.feedback_fn("* changing disks into %s mode" % msg)
6877
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6878
                                           self.instance.disks,
6879
                                           self.instance.name, multimaster)
6880
    for node, nres in result.items():
6881
      nres.Raise("Cannot change disks config on node %s" % node)
6882

    
6883
  def _ExecCleanup(self):
6884
    """Try to cleanup after a failed migration.
6885

6886
    The cleanup is done by:
6887
      - check that the instance is running only on one node
6888
        (and update the config if needed)
6889
      - change disks on its secondary node to secondary
6890
      - wait until disks are fully synchronized
6891
      - disconnect from the network
6892
      - change disks into single-master mode
6893
      - wait again until disks are fully synchronized
6894

6895
    """
6896
    instance = self.instance
6897
    target_node = self.target_node
6898
    source_node = self.source_node
6899

    
6900
    # check running on only one node
6901
    self.feedback_fn("* checking where the instance actually runs"
6902
                     " (if this hangs, the hypervisor might be in"
6903
                     " a bad state)")
6904
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6905
    for node, result in ins_l.items():
6906
      result.Raise("Can't contact node %s" % node)
6907

    
6908
    runningon_source = instance.name in ins_l[source_node].payload
6909
    runningon_target = instance.name in ins_l[target_node].payload
6910

    
6911
    if runningon_source and runningon_target:
6912
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6913
                               " or the hypervisor is confused; you will have"
6914
                               " to ensure manually that it runs only on one"
6915
                               " and restart this operation")
6916

    
6917
    if not (runningon_source or runningon_target):
6918
      raise errors.OpExecError("Instance does not seem to be running at all;"
6919
                               " in this case it's safer to repair by"
6920
                               " running 'gnt-instance stop' to ensure disk"
6921
                               " shutdown, and then restarting it")
6922

    
6923
    if runningon_target:
6924
      # the migration has actually succeeded, we need to update the config
6925
      self.feedback_fn("* instance running on secondary node (%s),"
6926
                       " updating config" % target_node)
6927
      instance.primary_node = target_node
6928
      self.cfg.Update(instance, self.feedback_fn)
6929
      demoted_node = source_node
6930
    else:
6931
      self.feedback_fn("* instance confirmed to be running on its"
6932
                       " primary node (%s)" % source_node)
6933
      demoted_node = target_node
6934

    
6935
    if instance.disk_template in constants.DTS_INT_MIRROR:
6936
      self._EnsureSecondary(demoted_node)
6937
      try:
6938
        self._WaitUntilSync()
6939
      except errors.OpExecError:
6940
        # we ignore here errors, since if the device is standalone, it
6941
        # won't be able to sync
6942
        pass
6943
      self._GoStandalone()
6944
      self._GoReconnect(False)
6945
      self._WaitUntilSync()
6946

    
6947
    self.feedback_fn("* done")
6948

    
6949
  def _RevertDiskStatus(self):
6950
    """Try to revert the disk status after a failed migration.
6951

6952
    """
6953
    target_node = self.target_node
6954
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
6955
      return
6956

    
6957
    try:
6958
      self._EnsureSecondary(target_node)
6959
      self._GoStandalone()
6960
      self._GoReconnect(False)
6961
      self._WaitUntilSync()
6962
    except errors.OpExecError, err:
6963
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
6964
                         " please try to recover the instance manually;"
6965
                         " error '%s'" % str(err))
6966

    
6967
  def _AbortMigration(self):
6968
    """Call the hypervisor code to abort a started migration.
6969

6970
    """
6971
    instance = self.instance
6972
    target_node = self.target_node
6973
    migration_info = self.migration_info
6974

    
6975
    abort_result = self.rpc.call_finalize_migration(target_node,
6976
                                                    instance,
6977
                                                    migration_info,
6978
                                                    False)
6979
    abort_msg = abort_result.fail_msg
6980
    if abort_msg:
6981
      logging.error("Aborting migration failed on target node %s: %s",
6982
                    target_node, abort_msg)
6983
      # Don't raise an exception here, as we stil have to try to revert the
6984
      # disk status, even if this step failed.
6985

    
6986
  def _ExecMigration(self):
6987
    """Migrate an instance.
6988

6989
    The migrate is done by:
6990
      - change the disks into dual-master mode
6991
      - wait until disks are fully synchronized again
6992
      - migrate the instance
6993
      - change disks on the new secondary node (the old primary) to secondary
6994
      - wait until disks are fully synchronized
6995
      - change disks into single-master mode
6996

6997
    """
6998
    instance = self.instance
6999
    target_node = self.target_node
7000
    source_node = self.source_node
7001

    
7002
    self.feedback_fn("* checking disk consistency between source and target")
7003
    for dev in instance.disks:
7004
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7005
        raise errors.OpExecError("Disk %s is degraded or not fully"
7006
                                 " synchronized on target node,"
7007
                                 " aborting migration" % dev.iv_name)
7008

    
7009
    # First get the migration information from the remote node
7010
    result = self.rpc.call_migration_info(source_node, instance)
7011
    msg = result.fail_msg
7012
    if msg:
7013
      log_err = ("Failed fetching source migration information from %s: %s" %
7014
                 (source_node, msg))
7015
      logging.error(log_err)
7016
      raise errors.OpExecError(log_err)
7017

    
7018
    self.migration_info = migration_info = result.payload
7019

    
7020
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7021
      # Then switch the disks to master/master mode
7022
      self._EnsureSecondary(target_node)
7023
      self._GoStandalone()
7024
      self._GoReconnect(True)
7025
      self._WaitUntilSync()
7026

    
7027
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7028
    result = self.rpc.call_accept_instance(target_node,
7029
                                           instance,
7030
                                           migration_info,
7031
                                           self.nodes_ip[target_node])
7032

    
7033
    msg = result.fail_msg
7034
    if msg:
7035
      logging.error("Instance pre-migration failed, trying to revert"
7036
                    " disk status: %s", msg)
7037
      self.feedback_fn("Pre-migration failed, aborting")
7038
      self._AbortMigration()
7039
      self._RevertDiskStatus()
7040
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7041
                               (instance.name, msg))
7042

    
7043
    self.feedback_fn("* migrating instance to %s" % target_node)
7044
    result = self.rpc.call_instance_migrate(source_node, instance,
7045
                                            self.nodes_ip[target_node],
7046
                                            self.live)
7047
    msg = result.fail_msg
7048
    if msg:
7049
      logging.error("Instance migration failed, trying to revert"
7050
                    " disk status: %s", msg)
7051
      self.feedback_fn("Migration failed, aborting")
7052
      self._AbortMigration()
7053
      self._RevertDiskStatus()
7054
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7055
                               (instance.name, msg))
7056

    
7057
    instance.primary_node = target_node
7058
    # distribute new instance config to the other nodes
7059
    self.cfg.Update(instance, self.feedback_fn)
7060

    
7061
    result = self.rpc.call_finalize_migration(target_node,
7062
                                              instance,
7063
                                              migration_info,
7064
                                              True)
7065
    msg = result.fail_msg
7066
    if msg:
7067
      logging.error("Instance migration succeeded, but finalization failed:"
7068
                    " %s", msg)
7069
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7070
                               msg)
7071

    
7072
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7073
      self._EnsureSecondary(source_node)
7074
      self._WaitUntilSync()
7075
      self._GoStandalone()
7076
      self._GoReconnect(False)
7077
      self._WaitUntilSync()
7078

    
7079
    self.feedback_fn("* done")
7080

    
7081
  def _ExecFailover(self):
7082
    """Failover an instance.
7083

7084
    The failover is done by shutting it down on its present node and
7085
    starting it on the secondary.
7086

7087
    """
7088
    instance = self.instance
7089
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7090

    
7091
    source_node = instance.primary_node
7092
    target_node = self.target_node
7093

    
7094
    if instance.admin_up:
7095
      self.feedback_fn("* checking disk consistency between source and target")
7096
      for dev in instance.disks:
7097
        # for drbd, these are drbd over lvm
7098
        if not _CheckDiskConsistency(self, dev, target_node, False):
7099
          if not self.ignore_consistency:
7100
            raise errors.OpExecError("Disk %s is degraded on target node,"
7101
                                     " aborting failover" % dev.iv_name)
7102
    else:
7103
      self.feedback_fn("* not checking disk consistency as instance is not"
7104
                       " running")
7105

    
7106
    self.feedback_fn("* shutting down instance on source node")
7107
    logging.info("Shutting down instance %s on node %s",
7108
                 instance.name, source_node)
7109

    
7110
    result = self.rpc.call_instance_shutdown(source_node, instance,
7111
                                             self.shutdown_timeout)
7112
    msg = result.fail_msg
7113
    if msg:
7114
      if self.ignore_consistency or primary_node.offline:
7115
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7116
                           " proceeding anyway; please make sure node"
7117
                           " %s is down; error details: %s",
7118
                           instance.name, source_node, source_node, msg)
7119
      else:
7120
        raise errors.OpExecError("Could not shutdown instance %s on"
7121
                                 " node %s: %s" %
7122
                                 (instance.name, source_node, msg))
7123

    
7124
    self.feedback_fn("* deactivating the instance's disks on source node")
7125
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
7126
      raise errors.OpExecError("Can't shut down the instance's disks.")
7127

    
7128
    instance.primary_node = target_node
7129
    # distribute new instance config to the other nodes
7130
    self.cfg.Update(instance, self.feedback_fn)
7131

    
7132
    # Only start the instance if it's marked as up
7133
    if instance.admin_up:
7134
      self.feedback_fn("* activating the instance's disks on target node")
7135
      logging.info("Starting instance %s on node %s",
7136
                   instance.name, target_node)
7137

    
7138
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7139
                                           ignore_secondaries=True)
7140
      if not disks_ok:
7141
        _ShutdownInstanceDisks(self, instance)
7142
        raise errors.OpExecError("Can't activate the instance's disks")
7143

    
7144
      self.feedback_fn("* starting the instance on the target node")
7145
      result = self.rpc.call_instance_start(target_node, instance, None, None)
7146
      msg = result.fail_msg
7147
      if msg:
7148
        _ShutdownInstanceDisks(self, instance)
7149
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7150
                                 (instance.name, target_node, msg))
7151

    
7152
  def Exec(self, feedback_fn):
7153
    """Perform the migration.
7154

7155
    """
7156
    self.feedback_fn = feedback_fn
7157
    self.source_node = self.instance.primary_node
7158

    
7159
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7160
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7161
      self.target_node = self.instance.secondary_nodes[0]
7162
      # Otherwise self.target_node has been populated either
7163
      # directly, or through an iallocator.
7164

    
7165
    self.all_nodes = [self.source_node, self.target_node]
7166
    self.nodes_ip = {
7167
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7168
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7169
      }
7170

    
7171
    if self.failover:
7172
      feedback_fn("Failover instance %s" % self.instance.name)
7173
      self._ExecFailover()
7174
    else:
7175
      feedback_fn("Migrating instance %s" % self.instance.name)
7176

    
7177
      if self.cleanup:
7178
        return self._ExecCleanup()
7179
      else:
7180
        return self._ExecMigration()
7181

    
7182

    
7183
def _CreateBlockDev(lu, node, instance, device, force_create,
7184
                    info, force_open):
7185
  """Create a tree of block devices on a given node.
7186

7187
  If this device type has to be created on secondaries, create it and
7188
  all its children.
7189

7190
  If not, just recurse to children keeping the same 'force' value.
7191

7192
  @param lu: the lu on whose behalf we execute
7193
  @param node: the node on which to create the device
7194
  @type instance: L{objects.Instance}
7195
  @param instance: the instance which owns the device
7196
  @type device: L{objects.Disk}
7197
  @param device: the device to create
7198
  @type force_create: boolean
7199
  @param force_create: whether to force creation of this device; this
7200
      will be change to True whenever we find a device which has
7201
      CreateOnSecondary() attribute
7202
  @param info: the extra 'metadata' we should attach to the device
7203
      (this will be represented as a LVM tag)
7204
  @type force_open: boolean
7205
  @param force_open: this parameter will be passes to the
7206
      L{backend.BlockdevCreate} function where it specifies
7207
      whether we run on primary or not, and it affects both
7208
      the child assembly and the device own Open() execution
7209

7210
  """
7211
  if device.CreateOnSecondary():
7212
    force_create = True
7213

    
7214
  if device.children:
7215
    for child in device.children:
7216
      _CreateBlockDev(lu, node, instance, child, force_create,
7217
                      info, force_open)
7218

    
7219
  if not force_create:
7220
    return
7221

    
7222
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7223

    
7224

    
7225
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7226
  """Create a single block device on a given node.
7227

7228
  This will not recurse over children of the device, so they must be
7229
  created in advance.
7230

7231
  @param lu: the lu on whose behalf we execute
7232
  @param node: the node on which to create the device
7233
  @type instance: L{objects.Instance}
7234
  @param instance: the instance which owns the device
7235
  @type device: L{objects.Disk}
7236
  @param device: the device to create
7237
  @param info: the extra 'metadata' we should attach to the device
7238
      (this will be represented as a LVM tag)
7239
  @type force_open: boolean
7240
  @param force_open: this parameter will be passes to the
7241
      L{backend.BlockdevCreate} function where it specifies
7242
      whether we run on primary or not, and it affects both
7243
      the child assembly and the device own Open() execution
7244

7245
  """
7246
  lu.cfg.SetDiskID(device, node)
7247
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7248
                                       instance.name, force_open, info)
7249
  result.Raise("Can't create block device %s on"
7250
               " node %s for instance %s" % (device, node, instance.name))
7251
  if device.physical_id is None:
7252
    device.physical_id = result.payload
7253

    
7254

    
7255
def _GenerateUniqueNames(lu, exts):
7256
  """Generate a suitable LV name.
7257

7258
  This will generate a logical volume name for the given instance.
7259

7260
  """
7261
  results = []
7262
  for val in exts:
7263
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7264
    results.append("%s%s" % (new_id, val))
7265
  return results
7266

    
7267

    
7268
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7269
                         iv_name, p_minor, s_minor):
7270
  """Generate a drbd8 device complete with its children.
7271

7272
  """
7273
  assert len(vgnames) == len(names) == 2
7274
  port = lu.cfg.AllocatePort()
7275
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7276
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7277
                          logical_id=(vgnames[0], names[0]))
7278
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7279
                          logical_id=(vgnames[1], names[1]))
7280
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7281
                          logical_id=(primary, secondary, port,
7282
                                      p_minor, s_minor,
7283
                                      shared_secret),
7284
                          children=[dev_data, dev_meta],
7285
                          iv_name=iv_name)
7286
  return drbd_dev
7287

    
7288

    
7289
def _GenerateDiskTemplate(lu, template_name,
7290
                          instance_name, primary_node,
7291
                          secondary_nodes, disk_info,
7292
                          file_storage_dir, file_driver,
7293
                          base_index, feedback_fn):
7294
  """Generate the entire disk layout for a given template type.
7295

7296
  """
7297
  #TODO: compute space requirements
7298

    
7299
  vgname = lu.cfg.GetVGName()
7300
  disk_count = len(disk_info)
7301
  disks = []
7302
  if template_name == constants.DT_DISKLESS:
7303
    pass
7304
  elif template_name == constants.DT_PLAIN:
7305
    if len(secondary_nodes) != 0:
7306
      raise errors.ProgrammerError("Wrong template configuration")
7307

    
7308
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7309
                                      for i in range(disk_count)])
7310
    for idx, disk in enumerate(disk_info):
7311
      disk_index = idx + base_index
7312
      vg = disk.get(constants.IDISK_VG, vgname)
7313
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7314
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7315
                              size=disk[constants.IDISK_SIZE],
7316
                              logical_id=(vg, names[idx]),
7317
                              iv_name="disk/%d" % disk_index,
7318
                              mode=disk[constants.IDISK_MODE])
7319
      disks.append(disk_dev)
7320
  elif template_name == constants.DT_DRBD8:
7321
    if len(secondary_nodes) != 1:
7322
      raise errors.ProgrammerError("Wrong template configuration")
7323
    remote_node = secondary_nodes[0]
7324
    minors = lu.cfg.AllocateDRBDMinor(
7325
      [primary_node, remote_node] * len(disk_info), instance_name)
7326

    
7327
    names = []
7328
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7329
                                               for i in range(disk_count)]):
7330
      names.append(lv_prefix + "_data")
7331
      names.append(lv_prefix + "_meta")
7332
    for idx, disk in enumerate(disk_info):
7333
      disk_index = idx + base_index
7334
      data_vg = disk.get(constants.IDISK_VG, vgname)
7335
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7336
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7337
                                      disk[constants.IDISK_SIZE],
7338
                                      [data_vg, meta_vg],
7339
                                      names[idx * 2:idx * 2 + 2],
7340
                                      "disk/%d" % disk_index,
7341
                                      minors[idx * 2], minors[idx * 2 + 1])
7342
      disk_dev.mode = disk[constants.IDISK_MODE]
7343
      disks.append(disk_dev)
7344
  elif template_name == constants.DT_FILE:
7345
    if len(secondary_nodes) != 0:
7346
      raise errors.ProgrammerError("Wrong template configuration")
7347

    
7348
    opcodes.RequireFileStorage()
7349

    
7350
    for idx, disk in enumerate(disk_info):
7351
      disk_index = idx + base_index
7352
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7353
                              size=disk[constants.IDISK_SIZE],
7354
                              iv_name="disk/%d" % disk_index,
7355
                              logical_id=(file_driver,
7356
                                          "%s/disk%d" % (file_storage_dir,
7357
                                                         disk_index)),
7358
                              mode=disk[constants.IDISK_MODE])
7359
      disks.append(disk_dev)
7360
  elif template_name == constants.DT_SHARED_FILE:
7361
    if len(secondary_nodes) != 0:
7362
      raise errors.ProgrammerError("Wrong template configuration")
7363

    
7364
    opcodes.RequireSharedFileStorage()
7365

    
7366
    for idx, disk in enumerate(disk_info):
7367
      disk_index = idx + base_index
7368
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7369
                              size=disk[constants.IDISK_SIZE],
7370
                              iv_name="disk/%d" % disk_index,
7371
                              logical_id=(file_driver,
7372
                                          "%s/disk%d" % (file_storage_dir,
7373
                                                         disk_index)),
7374
                              mode=disk[constants.IDISK_MODE])
7375
      disks.append(disk_dev)
7376
  elif template_name == constants.DT_BLOCK:
7377
    if len(secondary_nodes) != 0:
7378
      raise errors.ProgrammerError("Wrong template configuration")
7379

    
7380
    for idx, disk in enumerate(disk_info):
7381
      disk_index = idx + base_index
7382
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7383
                              size=disk[constants.IDISK_SIZE],
7384
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7385
                                          disk[constants.IDISK_ADOPT]),
7386
                              iv_name="disk/%d" % disk_index,
7387
                              mode=disk[constants.IDISK_MODE])
7388
      disks.append(disk_dev)
7389

    
7390
  else:
7391
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7392
  return disks
7393

    
7394

    
7395
def _GetInstanceInfoText(instance):
7396
  """Compute that text that should be added to the disk's metadata.
7397

7398
  """
7399
  return "originstname+%s" % instance.name
7400

    
7401

    
7402
def _CalcEta(time_taken, written, total_size):
7403
  """Calculates the ETA based on size written and total size.
7404

7405
  @param time_taken: The time taken so far
7406
  @param written: amount written so far
7407
  @param total_size: The total size of data to be written
7408
  @return: The remaining time in seconds
7409

7410
  """
7411
  avg_time = time_taken / float(written)
7412
  return (total_size - written) * avg_time
7413

    
7414

    
7415
def _WipeDisks(lu, instance):
7416
  """Wipes instance disks.
7417

7418
  @type lu: L{LogicalUnit}
7419
  @param lu: the logical unit on whose behalf we execute
7420
  @type instance: L{objects.Instance}
7421
  @param instance: the instance whose disks we should create
7422
  @return: the success of the wipe
7423

7424
  """
7425
  node = instance.primary_node
7426

    
7427
  for device in instance.disks:
7428
    lu.cfg.SetDiskID(device, node)
7429

    
7430
  logging.info("Pause sync of instance %s disks", instance.name)
7431
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7432

    
7433
  for idx, success in enumerate(result.payload):
7434
    if not success:
7435
      logging.warn("pause-sync of instance %s for disks %d failed",
7436
                   instance.name, idx)
7437

    
7438
  try:
7439
    for idx, device in enumerate(instance.disks):
7440
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7441
      # MAX_WIPE_CHUNK at max
7442
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7443
                            constants.MIN_WIPE_CHUNK_PERCENT)
7444
      # we _must_ make this an int, otherwise rounding errors will
7445
      # occur
7446
      wipe_chunk_size = int(wipe_chunk_size)
7447

    
7448
      lu.LogInfo("* Wiping disk %d", idx)
7449
      logging.info("Wiping disk %d for instance %s, node %s using"
7450
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7451

    
7452
      offset = 0
7453
      size = device.size
7454
      last_output = 0
7455
      start_time = time.time()
7456

    
7457
      while offset < size:
7458
        wipe_size = min(wipe_chunk_size, size - offset)
7459
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7460
                      idx, offset, wipe_size)
7461
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7462
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7463
                     (idx, offset, wipe_size))
7464
        now = time.time()
7465
        offset += wipe_size
7466
        if now - last_output >= 60:
7467
          eta = _CalcEta(now - start_time, offset, size)
7468
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7469
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7470
          last_output = now
7471
  finally:
7472
    logging.info("Resume sync of instance %s disks", instance.name)
7473

    
7474
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7475

    
7476
    for idx, success in enumerate(result.payload):
7477
      if not success:
7478
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7479
                      " look at the status and troubleshoot the issue", idx)
7480
        logging.warn("resume-sync of instance %s for disks %d failed",
7481
                     instance.name, idx)
7482

    
7483

    
7484
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7485
  """Create all disks for an instance.
7486

7487
  This abstracts away some work from AddInstance.
7488

7489
  @type lu: L{LogicalUnit}
7490
  @param lu: the logical unit on whose behalf we execute
7491
  @type instance: L{objects.Instance}
7492
  @param instance: the instance whose disks we should create
7493
  @type to_skip: list
7494
  @param to_skip: list of indices to skip
7495
  @type target_node: string
7496
  @param target_node: if passed, overrides the target node for creation
7497
  @rtype: boolean
7498
  @return: the success of the creation
7499

7500
  """
7501
  info = _GetInstanceInfoText(instance)
7502
  if target_node is None:
7503
    pnode = instance.primary_node
7504
    all_nodes = instance.all_nodes
7505
  else:
7506
    pnode = target_node
7507
    all_nodes = [pnode]
7508

    
7509
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
7510
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7511
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7512

    
7513
    result.Raise("Failed to create directory '%s' on"
7514
                 " node %s" % (file_storage_dir, pnode))
7515

    
7516
  # Note: this needs to be kept in sync with adding of disks in
7517
  # LUInstanceSetParams
7518
  for idx, device in enumerate(instance.disks):
7519
    if to_skip and idx in to_skip:
7520
      continue
7521
    logging.info("Creating volume %s for instance %s",
7522
                 device.iv_name, instance.name)
7523
    #HARDCODE
7524
    for node in all_nodes:
7525
      f_create = node == pnode
7526
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7527

    
7528

    
7529
def _RemoveDisks(lu, instance, target_node=None):
7530
  """Remove all disks for an instance.
7531

7532
  This abstracts away some work from `AddInstance()` and
7533
  `RemoveInstance()`. Note that in case some of the devices couldn't
7534
  be removed, the removal will continue with the other ones (compare
7535
  with `_CreateDisks()`).
7536

7537
  @type lu: L{LogicalUnit}
7538
  @param lu: the logical unit on whose behalf we execute
7539
  @type instance: L{objects.Instance}
7540
  @param instance: the instance whose disks we should remove
7541
  @type target_node: string
7542
  @param target_node: used to override the node on which to remove the disks
7543
  @rtype: boolean
7544
  @return: the success of the removal
7545

7546
  """
7547
  logging.info("Removing block devices for instance %s", instance.name)
7548

    
7549
  all_result = True
7550
  for device in instance.disks:
7551
    if target_node:
7552
      edata = [(target_node, device)]
7553
    else:
7554
      edata = device.ComputeNodeTree(instance.primary_node)
7555
    for node, disk in edata:
7556
      lu.cfg.SetDiskID(disk, node)
7557
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7558
      if msg:
7559
        lu.LogWarning("Could not remove block device %s on node %s,"
7560
                      " continuing anyway: %s", device.iv_name, node, msg)
7561
        all_result = False
7562

    
7563
  if instance.disk_template == constants.DT_FILE:
7564
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7565
    if target_node:
7566
      tgt = target_node
7567
    else:
7568
      tgt = instance.primary_node
7569
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7570
    if result.fail_msg:
7571
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7572
                    file_storage_dir, instance.primary_node, result.fail_msg)
7573
      all_result = False
7574

    
7575
  return all_result
7576

    
7577

    
7578
def _ComputeDiskSizePerVG(disk_template, disks):
7579
  """Compute disk size requirements in the volume group
7580

7581
  """
7582
  def _compute(disks, payload):
7583
    """Universal algorithm.
7584

7585
    """
7586
    vgs = {}
7587
    for disk in disks:
7588
      vgs[disk[constants.IDISK_VG]] = \
7589
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7590

    
7591
    return vgs
7592

    
7593
  # Required free disk space as a function of disk and swap space
7594
  req_size_dict = {
7595
    constants.DT_DISKLESS: {},
7596
    constants.DT_PLAIN: _compute(disks, 0),
7597
    # 128 MB are added for drbd metadata for each disk
7598
    constants.DT_DRBD8: _compute(disks, 128),
7599
    constants.DT_FILE: {},
7600
    constants.DT_SHARED_FILE: {},
7601
  }
7602

    
7603
  if disk_template not in req_size_dict:
7604
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7605
                                 " is unknown" %  disk_template)
7606

    
7607
  return req_size_dict[disk_template]
7608

    
7609

    
7610
def _ComputeDiskSize(disk_template, disks):
7611
  """Compute disk size requirements in the volume group
7612

7613
  """
7614
  # Required free disk space as a function of disk and swap space
7615
  req_size_dict = {
7616
    constants.DT_DISKLESS: None,
7617
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7618
    # 128 MB are added for drbd metadata for each disk
7619
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7620
    constants.DT_FILE: None,
7621
    constants.DT_SHARED_FILE: 0,
7622
    constants.DT_BLOCK: 0,
7623
  }
7624

    
7625
  if disk_template not in req_size_dict:
7626
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7627
                                 " is unknown" %  disk_template)
7628

    
7629
  return req_size_dict[disk_template]
7630

    
7631

    
7632
def _FilterVmNodes(lu, nodenames):
7633
  """Filters out non-vm_capable nodes from a list.
7634

7635
  @type lu: L{LogicalUnit}
7636
  @param lu: the logical unit for which we check
7637
  @type nodenames: list
7638
  @param nodenames: the list of nodes on which we should check
7639
  @rtype: list
7640
  @return: the list of vm-capable nodes
7641

7642
  """
7643
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7644
  return [name for name in nodenames if name not in vm_nodes]
7645

    
7646

    
7647
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7648
  """Hypervisor parameter validation.
7649

7650
  This function abstract the hypervisor parameter validation to be
7651
  used in both instance create and instance modify.
7652

7653
  @type lu: L{LogicalUnit}
7654
  @param lu: the logical unit for which we check
7655
  @type nodenames: list
7656
  @param nodenames: the list of nodes on which we should check
7657
  @type hvname: string
7658
  @param hvname: the name of the hypervisor we should use
7659
  @type hvparams: dict
7660
  @param hvparams: the parameters which we need to check
7661
  @raise errors.OpPrereqError: if the parameters are not valid
7662

7663
  """
7664
  nodenames = _FilterVmNodes(lu, nodenames)
7665
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7666
                                                  hvname,
7667
                                                  hvparams)
7668
  for node in nodenames:
7669
    info = hvinfo[node]
7670
    if info.offline:
7671
      continue
7672
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7673

    
7674

    
7675
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7676
  """OS parameters validation.
7677

7678
  @type lu: L{LogicalUnit}
7679
  @param lu: the logical unit for which we check
7680
  @type required: boolean
7681
  @param required: whether the validation should fail if the OS is not
7682
      found
7683
  @type nodenames: list
7684
  @param nodenames: the list of nodes on which we should check
7685
  @type osname: string
7686
  @param osname: the name of the hypervisor we should use
7687
  @type osparams: dict
7688
  @param osparams: the parameters which we need to check
7689
  @raise errors.OpPrereqError: if the parameters are not valid
7690

7691
  """
7692
  nodenames = _FilterVmNodes(lu, nodenames)
7693
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7694
                                   [constants.OS_VALIDATE_PARAMETERS],
7695
                                   osparams)
7696
  for node, nres in result.items():
7697
    # we don't check for offline cases since this should be run only
7698
    # against the master node and/or an instance's nodes
7699
    nres.Raise("OS Parameters validation failed on node %s" % node)
7700
    if not nres.payload:
7701
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7702
                 osname, node)
7703

    
7704

    
7705
class LUInstanceCreate(LogicalUnit):
7706
  """Create an instance.
7707

7708
  """
7709
  HPATH = "instance-add"
7710
  HTYPE = constants.HTYPE_INSTANCE
7711
  REQ_BGL = False
7712

    
7713
  def CheckArguments(self):
7714
    """Check arguments.
7715

7716
    """
7717
    # do not require name_check to ease forward/backward compatibility
7718
    # for tools
7719
    if self.op.no_install and self.op.start:
7720
      self.LogInfo("No-installation mode selected, disabling startup")
7721
      self.op.start = False
7722
    # validate/normalize the instance name
7723
    self.op.instance_name = \
7724
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7725

    
7726
    if self.op.ip_check and not self.op.name_check:
7727
      # TODO: make the ip check more flexible and not depend on the name check
7728
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7729
                                 " check", errors.ECODE_INVAL)
7730

    
7731
    # check nics' parameter names
7732
    for nic in self.op.nics:
7733
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7734

    
7735
    # check disks. parameter names and consistent adopt/no-adopt strategy
7736
    has_adopt = has_no_adopt = False
7737
    for disk in self.op.disks:
7738
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7739
      if constants.IDISK_ADOPT in disk:
7740
        has_adopt = True
7741
      else:
7742
        has_no_adopt = True
7743
    if has_adopt and has_no_adopt:
7744
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7745
                                 errors.ECODE_INVAL)
7746
    if has_adopt:
7747
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7748
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7749
                                   " '%s' disk template" %
7750
                                   self.op.disk_template,
7751
                                   errors.ECODE_INVAL)
7752
      if self.op.iallocator is not None:
7753
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7754
                                   " iallocator script", errors.ECODE_INVAL)
7755
      if self.op.mode == constants.INSTANCE_IMPORT:
7756
        raise errors.OpPrereqError("Disk adoption not allowed for"
7757
                                   " instance import", errors.ECODE_INVAL)
7758
    else:
7759
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7760
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7761
                                   " but no 'adopt' parameter given" %
7762
                                   self.op.disk_template,
7763
                                   errors.ECODE_INVAL)
7764

    
7765
    self.adopt_disks = has_adopt
7766

    
7767
    # instance name verification
7768
    if self.op.name_check:
7769
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7770
      self.op.instance_name = self.hostname1.name
7771
      # used in CheckPrereq for ip ping check
7772
      self.check_ip = self.hostname1.ip
7773
    else:
7774
      self.check_ip = None
7775

    
7776
    # file storage checks
7777
    if (self.op.file_driver and
7778
        not self.op.file_driver in constants.FILE_DRIVER):
7779
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7780
                                 self.op.file_driver, errors.ECODE_INVAL)
7781

    
7782
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7783
      raise errors.OpPrereqError("File storage directory path not absolute",
7784
                                 errors.ECODE_INVAL)
7785

    
7786
    ### Node/iallocator related checks
7787
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7788

    
7789
    if self.op.pnode is not None:
7790
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7791
        if self.op.snode is None:
7792
          raise errors.OpPrereqError("The networked disk templates need"
7793
                                     " a mirror node", errors.ECODE_INVAL)
7794
      elif self.op.snode:
7795
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7796
                        " template")
7797
        self.op.snode = None
7798

    
7799
    self._cds = _GetClusterDomainSecret()
7800

    
7801
    if self.op.mode == constants.INSTANCE_IMPORT:
7802
      # On import force_variant must be True, because if we forced it at
7803
      # initial install, our only chance when importing it back is that it
7804
      # works again!
7805
      self.op.force_variant = True
7806

    
7807
      if self.op.no_install:
7808
        self.LogInfo("No-installation mode has no effect during import")
7809

    
7810
    elif self.op.mode == constants.INSTANCE_CREATE:
7811
      if self.op.os_type is None:
7812
        raise errors.OpPrereqError("No guest OS specified",
7813
                                   errors.ECODE_INVAL)
7814
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7815
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7816
                                   " installation" % self.op.os_type,
7817
                                   errors.ECODE_STATE)
7818
      if self.op.disk_template is None:
7819
        raise errors.OpPrereqError("No disk template specified",
7820
                                   errors.ECODE_INVAL)
7821

    
7822
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7823
      # Check handshake to ensure both clusters have the same domain secret
7824
      src_handshake = self.op.source_handshake
7825
      if not src_handshake:
7826
        raise errors.OpPrereqError("Missing source handshake",
7827
                                   errors.ECODE_INVAL)
7828

    
7829
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7830
                                                           src_handshake)
7831
      if errmsg:
7832
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7833
                                   errors.ECODE_INVAL)
7834

    
7835
      # Load and check source CA
7836
      self.source_x509_ca_pem = self.op.source_x509_ca
7837
      if not self.source_x509_ca_pem:
7838
        raise errors.OpPrereqError("Missing source X509 CA",
7839
                                   errors.ECODE_INVAL)
7840

    
7841
      try:
7842
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7843
                                                    self._cds)
7844
      except OpenSSL.crypto.Error, err:
7845
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7846
                                   (err, ), errors.ECODE_INVAL)
7847

    
7848
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7849
      if errcode is not None:
7850
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7851
                                   errors.ECODE_INVAL)
7852

    
7853
      self.source_x509_ca = cert
7854

    
7855
      src_instance_name = self.op.source_instance_name
7856
      if not src_instance_name:
7857
        raise errors.OpPrereqError("Missing source instance name",
7858
                                   errors.ECODE_INVAL)
7859

    
7860
      self.source_instance_name = \
7861
          netutils.GetHostname(name=src_instance_name).name
7862

    
7863
    else:
7864
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7865
                                 self.op.mode, errors.ECODE_INVAL)
7866

    
7867
  def ExpandNames(self):
7868
    """ExpandNames for CreateInstance.
7869

7870
    Figure out the right locks for instance creation.
7871

7872
    """
7873
    self.needed_locks = {}
7874

    
7875
    instance_name = self.op.instance_name
7876
    # this is just a preventive check, but someone might still add this
7877
    # instance in the meantime, and creation will fail at lock-add time
7878
    if instance_name in self.cfg.GetInstanceList():
7879
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7880
                                 instance_name, errors.ECODE_EXISTS)
7881

    
7882
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7883

    
7884
    if self.op.iallocator:
7885
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7886
    else:
7887
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7888
      nodelist = [self.op.pnode]
7889
      if self.op.snode is not None:
7890
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7891
        nodelist.append(self.op.snode)
7892
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7893

    
7894
    # in case of import lock the source node too
7895
    if self.op.mode == constants.INSTANCE_IMPORT:
7896
      src_node = self.op.src_node
7897
      src_path = self.op.src_path
7898

    
7899
      if src_path is None:
7900
        self.op.src_path = src_path = self.op.instance_name
7901

    
7902
      if src_node is None:
7903
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7904
        self.op.src_node = None
7905
        if os.path.isabs(src_path):
7906
          raise errors.OpPrereqError("Importing an instance from an absolute"
7907
                                     " path requires a source node option",
7908
                                     errors.ECODE_INVAL)
7909
      else:
7910
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7911
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7912
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7913
        if not os.path.isabs(src_path):
7914
          self.op.src_path = src_path = \
7915
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7916

    
7917
  def _RunAllocator(self):
7918
    """Run the allocator based on input opcode.
7919

7920
    """
7921
    nics = [n.ToDict() for n in self.nics]
7922
    ial = IAllocator(self.cfg, self.rpc,
7923
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7924
                     name=self.op.instance_name,
7925
                     disk_template=self.op.disk_template,
7926
                     tags=[],
7927
                     os=self.op.os_type,
7928
                     vcpus=self.be_full[constants.BE_VCPUS],
7929
                     mem_size=self.be_full[constants.BE_MEMORY],
7930
                     disks=self.disks,
7931
                     nics=nics,
7932
                     hypervisor=self.op.hypervisor,
7933
                     )
7934

    
7935
    ial.Run(self.op.iallocator)
7936

    
7937
    if not ial.success:
7938
      raise errors.OpPrereqError("Can't compute nodes using"
7939
                                 " iallocator '%s': %s" %
7940
                                 (self.op.iallocator, ial.info),
7941
                                 errors.ECODE_NORES)
7942
    if len(ial.result) != ial.required_nodes:
7943
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7944
                                 " of nodes (%s), required %s" %
7945
                                 (self.op.iallocator, len(ial.result),
7946
                                  ial.required_nodes), errors.ECODE_FAULT)
7947
    self.op.pnode = ial.result[0]
7948
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7949
                 self.op.instance_name, self.op.iallocator,
7950
                 utils.CommaJoin(ial.result))
7951
    if ial.required_nodes == 2:
7952
      self.op.snode = ial.result[1]
7953

    
7954
  def BuildHooksEnv(self):
7955
    """Build hooks env.
7956

7957
    This runs on master, primary and secondary nodes of the instance.
7958

7959
    """
7960
    env = {
7961
      "ADD_MODE": self.op.mode,
7962
      }
7963
    if self.op.mode == constants.INSTANCE_IMPORT:
7964
      env["SRC_NODE"] = self.op.src_node
7965
      env["SRC_PATH"] = self.op.src_path
7966
      env["SRC_IMAGES"] = self.src_images
7967

    
7968
    env.update(_BuildInstanceHookEnv(
7969
      name=self.op.instance_name,
7970
      primary_node=self.op.pnode,
7971
      secondary_nodes=self.secondaries,
7972
      status=self.op.start,
7973
      os_type=self.op.os_type,
7974
      memory=self.be_full[constants.BE_MEMORY],
7975
      vcpus=self.be_full[constants.BE_VCPUS],
7976
      nics=_NICListToTuple(self, self.nics),
7977
      disk_template=self.op.disk_template,
7978
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
7979
             for d in self.disks],
7980
      bep=self.be_full,
7981
      hvp=self.hv_full,
7982
      hypervisor_name=self.op.hypervisor,
7983
    ))
7984

    
7985
    return env
7986

    
7987
  def BuildHooksNodes(self):
7988
    """Build hooks nodes.
7989

7990
    """
7991
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
7992
    return nl, nl
7993

    
7994
  def _ReadExportInfo(self):
7995
    """Reads the export information from disk.
7996

7997
    It will override the opcode source node and path with the actual
7998
    information, if these two were not specified before.
7999

8000
    @return: the export information
8001

8002
    """
8003
    assert self.op.mode == constants.INSTANCE_IMPORT
8004

    
8005
    src_node = self.op.src_node
8006
    src_path = self.op.src_path
8007

    
8008
    if src_node is None:
8009
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
8010
      exp_list = self.rpc.call_export_list(locked_nodes)
8011
      found = False
8012
      for node in exp_list:
8013
        if exp_list[node].fail_msg:
8014
          continue
8015
        if src_path in exp_list[node].payload:
8016
          found = True
8017
          self.op.src_node = src_node = node
8018
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8019
                                                       src_path)
8020
          break
8021
      if not found:
8022
        raise errors.OpPrereqError("No export found for relative path %s" %
8023
                                    src_path, errors.ECODE_INVAL)
8024

    
8025
    _CheckNodeOnline(self, src_node)
8026
    result = self.rpc.call_export_info(src_node, src_path)
8027
    result.Raise("No export or invalid export found in dir %s" % src_path)
8028

    
8029
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8030
    if not export_info.has_section(constants.INISECT_EXP):
8031
      raise errors.ProgrammerError("Corrupted export config",
8032
                                   errors.ECODE_ENVIRON)
8033

    
8034
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8035
    if (int(ei_version) != constants.EXPORT_VERSION):
8036
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8037
                                 (ei_version, constants.EXPORT_VERSION),
8038
                                 errors.ECODE_ENVIRON)
8039
    return export_info
8040

    
8041
  def _ReadExportParams(self, einfo):
8042
    """Use export parameters as defaults.
8043

8044
    In case the opcode doesn't specify (as in override) some instance
8045
    parameters, then try to use them from the export information, if
8046
    that declares them.
8047

8048
    """
8049
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8050

    
8051
    if self.op.disk_template is None:
8052
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8053
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8054
                                          "disk_template")
8055
      else:
8056
        raise errors.OpPrereqError("No disk template specified and the export"
8057
                                   " is missing the disk_template information",
8058
                                   errors.ECODE_INVAL)
8059

    
8060
    if not self.op.disks:
8061
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
8062
        disks = []
8063
        # TODO: import the disk iv_name too
8064
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8065
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8066
          disks.append({constants.IDISK_SIZE: disk_sz})
8067
        self.op.disks = disks
8068
      else:
8069
        raise errors.OpPrereqError("No disk info specified and the export"
8070
                                   " is missing the disk information",
8071
                                   errors.ECODE_INVAL)
8072

    
8073
    if (not self.op.nics and
8074
        einfo.has_option(constants.INISECT_INS, "nic_count")):
8075
      nics = []
8076
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8077
        ndict = {}
8078
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8079
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8080
          ndict[name] = v
8081
        nics.append(ndict)
8082
      self.op.nics = nics
8083

    
8084
    if (self.op.hypervisor is None and
8085
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
8086
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8087
    if einfo.has_section(constants.INISECT_HYP):
8088
      # use the export parameters but do not override the ones
8089
      # specified by the user
8090
      for name, value in einfo.items(constants.INISECT_HYP):
8091
        if name not in self.op.hvparams:
8092
          self.op.hvparams[name] = value
8093

    
8094
    if einfo.has_section(constants.INISECT_BEP):
8095
      # use the parameters, without overriding
8096
      for name, value in einfo.items(constants.INISECT_BEP):
8097
        if name not in self.op.beparams:
8098
          self.op.beparams[name] = value
8099
    else:
8100
      # try to read the parameters old style, from the main section
8101
      for name in constants.BES_PARAMETERS:
8102
        if (name not in self.op.beparams and
8103
            einfo.has_option(constants.INISECT_INS, name)):
8104
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8105

    
8106
    if einfo.has_section(constants.INISECT_OSP):
8107
      # use the parameters, without overriding
8108
      for name, value in einfo.items(constants.INISECT_OSP):
8109
        if name not in self.op.osparams:
8110
          self.op.osparams[name] = value
8111

    
8112
  def _RevertToDefaults(self, cluster):
8113
    """Revert the instance parameters to the default values.
8114

8115
    """
8116
    # hvparams
8117
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8118
    for name in self.op.hvparams.keys():
8119
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8120
        del self.op.hvparams[name]
8121
    # beparams
8122
    be_defs = cluster.SimpleFillBE({})
8123
    for name in self.op.beparams.keys():
8124
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8125
        del self.op.beparams[name]
8126
    # nic params
8127
    nic_defs = cluster.SimpleFillNIC({})
8128
    for nic in self.op.nics:
8129
      for name in constants.NICS_PARAMETERS:
8130
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8131
          del nic[name]
8132
    # osparams
8133
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8134
    for name in self.op.osparams.keys():
8135
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8136
        del self.op.osparams[name]
8137

    
8138
  def CheckPrereq(self):
8139
    """Check prerequisites.
8140

8141
    """
8142
    if self.op.mode == constants.INSTANCE_IMPORT:
8143
      export_info = self._ReadExportInfo()
8144
      self._ReadExportParams(export_info)
8145

    
8146
    if (not self.cfg.GetVGName() and
8147
        self.op.disk_template not in constants.DTS_NOT_LVM):
8148
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8149
                                 " instances", errors.ECODE_STATE)
8150

    
8151
    if self.op.hypervisor is None:
8152
      self.op.hypervisor = self.cfg.GetHypervisorType()
8153

    
8154
    cluster = self.cfg.GetClusterInfo()
8155
    enabled_hvs = cluster.enabled_hypervisors
8156
    if self.op.hypervisor not in enabled_hvs:
8157
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8158
                                 " cluster (%s)" % (self.op.hypervisor,
8159
                                  ",".join(enabled_hvs)),
8160
                                 errors.ECODE_STATE)
8161

    
8162
    # check hypervisor parameter syntax (locally)
8163
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8164
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8165
                                      self.op.hvparams)
8166
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8167
    hv_type.CheckParameterSyntax(filled_hvp)
8168
    self.hv_full = filled_hvp
8169
    # check that we don't specify global parameters on an instance
8170
    _CheckGlobalHvParams(self.op.hvparams)
8171

    
8172
    # fill and remember the beparams dict
8173
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8174
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8175

    
8176
    # build os parameters
8177
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8178

    
8179
    # now that hvp/bep are in final format, let's reset to defaults,
8180
    # if told to do so
8181
    if self.op.identify_defaults:
8182
      self._RevertToDefaults(cluster)
8183

    
8184
    # NIC buildup
8185
    self.nics = []
8186
    for idx, nic in enumerate(self.op.nics):
8187
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8188
      nic_mode = nic_mode_req
8189
      if nic_mode is None:
8190
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8191

    
8192
      # in routed mode, for the first nic, the default ip is 'auto'
8193
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8194
        default_ip_mode = constants.VALUE_AUTO
8195
      else:
8196
        default_ip_mode = constants.VALUE_NONE
8197

    
8198
      # ip validity checks
8199
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8200
      if ip is None or ip.lower() == constants.VALUE_NONE:
8201
        nic_ip = None
8202
      elif ip.lower() == constants.VALUE_AUTO:
8203
        if not self.op.name_check:
8204
          raise errors.OpPrereqError("IP address set to auto but name checks"
8205
                                     " have been skipped",
8206
                                     errors.ECODE_INVAL)
8207
        nic_ip = self.hostname1.ip
8208
      else:
8209
        if not netutils.IPAddress.IsValid(ip):
8210
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8211
                                     errors.ECODE_INVAL)
8212
        nic_ip = ip
8213

    
8214
      # TODO: check the ip address for uniqueness
8215
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8216
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8217
                                   errors.ECODE_INVAL)
8218

    
8219
      # MAC address verification
8220
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8221
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8222
        mac = utils.NormalizeAndValidateMac(mac)
8223

    
8224
        try:
8225
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8226
        except errors.ReservationError:
8227
          raise errors.OpPrereqError("MAC address %s already in use"
8228
                                     " in cluster" % mac,
8229
                                     errors.ECODE_NOTUNIQUE)
8230

    
8231
      #  Build nic parameters
8232
      link = nic.get(constants.INIC_LINK, None)
8233
      nicparams = {}
8234
      if nic_mode_req:
8235
        nicparams[constants.NIC_MODE] = nic_mode_req
8236
      if link:
8237
        nicparams[constants.NIC_LINK] = link
8238

    
8239
      check_params = cluster.SimpleFillNIC(nicparams)
8240
      objects.NIC.CheckParameterSyntax(check_params)
8241
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8242

    
8243
    # disk checks/pre-build
8244
    default_vg = self.cfg.GetVGName()
8245
    self.disks = []
8246
    for disk in self.op.disks:
8247
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8248
      if mode not in constants.DISK_ACCESS_SET:
8249
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8250
                                   mode, errors.ECODE_INVAL)
8251
      size = disk.get(constants.IDISK_SIZE, None)
8252
      if size is None:
8253
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8254
      try:
8255
        size = int(size)
8256
      except (TypeError, ValueError):
8257
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8258
                                   errors.ECODE_INVAL)
8259

    
8260
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8261
      new_disk = {
8262
        constants.IDISK_SIZE: size,
8263
        constants.IDISK_MODE: mode,
8264
        constants.IDISK_VG: data_vg,
8265
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8266
        }
8267
      if constants.IDISK_ADOPT in disk:
8268
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8269
      self.disks.append(new_disk)
8270

    
8271
    if self.op.mode == constants.INSTANCE_IMPORT:
8272

    
8273
      # Check that the new instance doesn't have less disks than the export
8274
      instance_disks = len(self.disks)
8275
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8276
      if instance_disks < export_disks:
8277
        raise errors.OpPrereqError("Not enough disks to import."
8278
                                   " (instance: %d, export: %d)" %
8279
                                   (instance_disks, export_disks),
8280
                                   errors.ECODE_INVAL)
8281

    
8282
      disk_images = []
8283
      for idx in range(export_disks):
8284
        option = 'disk%d_dump' % idx
8285
        if export_info.has_option(constants.INISECT_INS, option):
8286
          # FIXME: are the old os-es, disk sizes, etc. useful?
8287
          export_name = export_info.get(constants.INISECT_INS, option)
8288
          image = utils.PathJoin(self.op.src_path, export_name)
8289
          disk_images.append(image)
8290
        else:
8291
          disk_images.append(False)
8292

    
8293
      self.src_images = disk_images
8294

    
8295
      old_name = export_info.get(constants.INISECT_INS, 'name')
8296
      try:
8297
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8298
      except (TypeError, ValueError), err:
8299
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8300
                                   " an integer: %s" % str(err),
8301
                                   errors.ECODE_STATE)
8302
      if self.op.instance_name == old_name:
8303
        for idx, nic in enumerate(self.nics):
8304
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8305
            nic_mac_ini = 'nic%d_mac' % idx
8306
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8307

    
8308
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8309

    
8310
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8311
    if self.op.ip_check:
8312
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8313
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8314
                                   (self.check_ip, self.op.instance_name),
8315
                                   errors.ECODE_NOTUNIQUE)
8316

    
8317
    #### mac address generation
8318
    # By generating here the mac address both the allocator and the hooks get
8319
    # the real final mac address rather than the 'auto' or 'generate' value.
8320
    # There is a race condition between the generation and the instance object
8321
    # creation, which means that we know the mac is valid now, but we're not
8322
    # sure it will be when we actually add the instance. If things go bad
8323
    # adding the instance will abort because of a duplicate mac, and the
8324
    # creation job will fail.
8325
    for nic in self.nics:
8326
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8327
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8328

    
8329
    #### allocator run
8330

    
8331
    if self.op.iallocator is not None:
8332
      self._RunAllocator()
8333

    
8334
    #### node related checks
8335

    
8336
    # check primary node
8337
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8338
    assert self.pnode is not None, \
8339
      "Cannot retrieve locked node %s" % self.op.pnode
8340
    if pnode.offline:
8341
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8342
                                 pnode.name, errors.ECODE_STATE)
8343
    if pnode.drained:
8344
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8345
                                 pnode.name, errors.ECODE_STATE)
8346
    if not pnode.vm_capable:
8347
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8348
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8349

    
8350
    self.secondaries = []
8351

    
8352
    # mirror node verification
8353
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8354
      if self.op.snode == pnode.name:
8355
        raise errors.OpPrereqError("The secondary node cannot be the"
8356
                                   " primary node", errors.ECODE_INVAL)
8357
      _CheckNodeOnline(self, self.op.snode)
8358
      _CheckNodeNotDrained(self, self.op.snode)
8359
      _CheckNodeVmCapable(self, self.op.snode)
8360
      self.secondaries.append(self.op.snode)
8361

    
8362
    nodenames = [pnode.name] + self.secondaries
8363

    
8364
    if not self.adopt_disks:
8365
      # Check lv size requirements, if not adopting
8366
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8367
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8368

    
8369
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8370
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8371
                                disk[constants.IDISK_ADOPT])
8372
                     for disk in self.disks])
8373
      if len(all_lvs) != len(self.disks):
8374
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8375
                                   errors.ECODE_INVAL)
8376
      for lv_name in all_lvs:
8377
        try:
8378
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8379
          # to ReserveLV uses the same syntax
8380
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8381
        except errors.ReservationError:
8382
          raise errors.OpPrereqError("LV named %s used by another instance" %
8383
                                     lv_name, errors.ECODE_NOTUNIQUE)
8384

    
8385
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8386
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8387

    
8388
      node_lvs = self.rpc.call_lv_list([pnode.name],
8389
                                       vg_names.payload.keys())[pnode.name]
8390
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8391
      node_lvs = node_lvs.payload
8392

    
8393
      delta = all_lvs.difference(node_lvs.keys())
8394
      if delta:
8395
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8396
                                   utils.CommaJoin(delta),
8397
                                   errors.ECODE_INVAL)
8398
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8399
      if online_lvs:
8400
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8401
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8402
                                   errors.ECODE_STATE)
8403
      # update the size of disk based on what is found
8404
      for dsk in self.disks:
8405
        dsk[constants.IDISK_SIZE] = \
8406
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8407
                                        dsk[constants.IDISK_ADOPT])][0]))
8408

    
8409
    elif self.op.disk_template == constants.DT_BLOCK:
8410
      # Normalize and de-duplicate device paths
8411
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8412
                       for disk in self.disks])
8413
      if len(all_disks) != len(self.disks):
8414
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8415
                                   errors.ECODE_INVAL)
8416
      baddisks = [d for d in all_disks
8417
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8418
      if baddisks:
8419
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8420
                                   " cannot be adopted" %
8421
                                   (", ".join(baddisks),
8422
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8423
                                   errors.ECODE_INVAL)
8424

    
8425
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8426
                                            list(all_disks))[pnode.name]
8427
      node_disks.Raise("Cannot get block device information from node %s" %
8428
                       pnode.name)
8429
      node_disks = node_disks.payload
8430
      delta = all_disks.difference(node_disks.keys())
8431
      if delta:
8432
        raise errors.OpPrereqError("Missing block device(s): %s" %
8433
                                   utils.CommaJoin(delta),
8434
                                   errors.ECODE_INVAL)
8435
      for dsk in self.disks:
8436
        dsk[constants.IDISK_SIZE] = \
8437
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8438

    
8439
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8440

    
8441
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8442
    # check OS parameters (remotely)
8443
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8444

    
8445
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8446

    
8447
    # memory check on primary node
8448
    if self.op.start:
8449
      _CheckNodeFreeMemory(self, self.pnode.name,
8450
                           "creating instance %s" % self.op.instance_name,
8451
                           self.be_full[constants.BE_MEMORY],
8452
                           self.op.hypervisor)
8453

    
8454
    self.dry_run_result = list(nodenames)
8455

    
8456
  def Exec(self, feedback_fn):
8457
    """Create and add the instance to the cluster.
8458

8459
    """
8460
    instance = self.op.instance_name
8461
    pnode_name = self.pnode.name
8462

    
8463
    ht_kind = self.op.hypervisor
8464
    if ht_kind in constants.HTS_REQ_PORT:
8465
      network_port = self.cfg.AllocatePort()
8466
    else:
8467
      network_port = None
8468

    
8469
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
8470
      # this is needed because os.path.join does not accept None arguments
8471
      if self.op.file_storage_dir is None:
8472
        string_file_storage_dir = ""
8473
      else:
8474
        string_file_storage_dir = self.op.file_storage_dir
8475

    
8476
      # build the full file storage dir path
8477
      if self.op.disk_template == constants.DT_SHARED_FILE:
8478
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8479
      else:
8480
        get_fsd_fn = self.cfg.GetFileStorageDir
8481

    
8482
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
8483
                                        string_file_storage_dir, instance)
8484
    else:
8485
      file_storage_dir = ""
8486

    
8487
    disks = _GenerateDiskTemplate(self,
8488
                                  self.op.disk_template,
8489
                                  instance, pnode_name,
8490
                                  self.secondaries,
8491
                                  self.disks,
8492
                                  file_storage_dir,
8493
                                  self.op.file_driver,
8494
                                  0,
8495
                                  feedback_fn)
8496

    
8497
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8498
                            primary_node=pnode_name,
8499
                            nics=self.nics, disks=disks,
8500
                            disk_template=self.op.disk_template,
8501
                            admin_up=False,
8502
                            network_port=network_port,
8503
                            beparams=self.op.beparams,
8504
                            hvparams=self.op.hvparams,
8505
                            hypervisor=self.op.hypervisor,
8506
                            osparams=self.op.osparams,
8507
                            )
8508

    
8509
    if self.adopt_disks:
8510
      if self.op.disk_template == constants.DT_PLAIN:
8511
        # rename LVs to the newly-generated names; we need to construct
8512
        # 'fake' LV disks with the old data, plus the new unique_id
8513
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8514
        rename_to = []
8515
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8516
          rename_to.append(t_dsk.logical_id)
8517
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8518
          self.cfg.SetDiskID(t_dsk, pnode_name)
8519
        result = self.rpc.call_blockdev_rename(pnode_name,
8520
                                               zip(tmp_disks, rename_to))
8521
        result.Raise("Failed to rename adoped LVs")
8522
    else:
8523
      feedback_fn("* creating instance disks...")
8524
      try:
8525
        _CreateDisks(self, iobj)
8526
      except errors.OpExecError:
8527
        self.LogWarning("Device creation failed, reverting...")
8528
        try:
8529
          _RemoveDisks(self, iobj)
8530
        finally:
8531
          self.cfg.ReleaseDRBDMinors(instance)
8532
          raise
8533

    
8534
    feedback_fn("adding instance %s to cluster config" % instance)
8535

    
8536
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8537

    
8538
    # Declare that we don't want to remove the instance lock anymore, as we've
8539
    # added the instance to the config
8540
    del self.remove_locks[locking.LEVEL_INSTANCE]
8541

    
8542
    if self.op.mode == constants.INSTANCE_IMPORT:
8543
      # Release unused nodes
8544
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8545
    else:
8546
      # Release all nodes
8547
      _ReleaseLocks(self, locking.LEVEL_NODE)
8548

    
8549
    disk_abort = False
8550
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8551
      feedback_fn("* wiping instance disks...")
8552
      try:
8553
        _WipeDisks(self, iobj)
8554
      except errors.OpExecError, err:
8555
        logging.exception("Wiping disks failed")
8556
        self.LogWarning("Wiping instance disks failed (%s)", err)
8557
        disk_abort = True
8558

    
8559
    if disk_abort:
8560
      # Something is already wrong with the disks, don't do anything else
8561
      pass
8562
    elif self.op.wait_for_sync:
8563
      disk_abort = not _WaitForSync(self, iobj)
8564
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8565
      # make sure the disks are not degraded (still sync-ing is ok)
8566
      time.sleep(15)
8567
      feedback_fn("* checking mirrors status")
8568
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8569
    else:
8570
      disk_abort = False
8571

    
8572
    if disk_abort:
8573
      _RemoveDisks(self, iobj)
8574
      self.cfg.RemoveInstance(iobj.name)
8575
      # Make sure the instance lock gets removed
8576
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8577
      raise errors.OpExecError("There are some degraded disks for"
8578
                               " this instance")
8579

    
8580
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8581
      if self.op.mode == constants.INSTANCE_CREATE:
8582
        if not self.op.no_install:
8583
          feedback_fn("* running the instance OS create scripts...")
8584
          # FIXME: pass debug option from opcode to backend
8585
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8586
                                                 self.op.debug_level)
8587
          result.Raise("Could not add os for instance %s"
8588
                       " on node %s" % (instance, pnode_name))
8589

    
8590
      elif self.op.mode == constants.INSTANCE_IMPORT:
8591
        feedback_fn("* running the instance OS import scripts...")
8592

    
8593
        transfers = []
8594

    
8595
        for idx, image in enumerate(self.src_images):
8596
          if not image:
8597
            continue
8598

    
8599
          # FIXME: pass debug option from opcode to backend
8600
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8601
                                             constants.IEIO_FILE, (image, ),
8602
                                             constants.IEIO_SCRIPT,
8603
                                             (iobj.disks[idx], idx),
8604
                                             None)
8605
          transfers.append(dt)
8606

    
8607
        import_result = \
8608
          masterd.instance.TransferInstanceData(self, feedback_fn,
8609
                                                self.op.src_node, pnode_name,
8610
                                                self.pnode.secondary_ip,
8611
                                                iobj, transfers)
8612
        if not compat.all(import_result):
8613
          self.LogWarning("Some disks for instance %s on node %s were not"
8614
                          " imported successfully" % (instance, pnode_name))
8615

    
8616
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8617
        feedback_fn("* preparing remote import...")
8618
        # The source cluster will stop the instance before attempting to make a
8619
        # connection. In some cases stopping an instance can take a long time,
8620
        # hence the shutdown timeout is added to the connection timeout.
8621
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8622
                           self.op.source_shutdown_timeout)
8623
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8624

    
8625
        assert iobj.primary_node == self.pnode.name
8626
        disk_results = \
8627
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8628
                                        self.source_x509_ca,
8629
                                        self._cds, timeouts)
8630
        if not compat.all(disk_results):
8631
          # TODO: Should the instance still be started, even if some disks
8632
          # failed to import (valid for local imports, too)?
8633
          self.LogWarning("Some disks for instance %s on node %s were not"
8634
                          " imported successfully" % (instance, pnode_name))
8635

    
8636
        # Run rename script on newly imported instance
8637
        assert iobj.name == instance
8638
        feedback_fn("Running rename script for %s" % instance)
8639
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8640
                                                   self.source_instance_name,
8641
                                                   self.op.debug_level)
8642
        if result.fail_msg:
8643
          self.LogWarning("Failed to run rename script for %s on node"
8644
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8645

    
8646
      else:
8647
        # also checked in the prereq part
8648
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8649
                                     % self.op.mode)
8650

    
8651
    if self.op.start:
8652
      iobj.admin_up = True
8653
      self.cfg.Update(iobj, feedback_fn)
8654
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8655
      feedback_fn("* starting instance...")
8656
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8657
      result.Raise("Could not start instance")
8658

    
8659
    return list(iobj.all_nodes)
8660

    
8661

    
8662
class LUInstanceConsole(NoHooksLU):
8663
  """Connect to an instance's console.
8664

8665
  This is somewhat special in that it returns the command line that
8666
  you need to run on the master node in order to connect to the
8667
  console.
8668

8669
  """
8670
  REQ_BGL = False
8671

    
8672
  def ExpandNames(self):
8673
    self._ExpandAndLockInstance()
8674

    
8675
  def CheckPrereq(self):
8676
    """Check prerequisites.
8677

8678
    This checks that the instance is in the cluster.
8679

8680
    """
8681
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8682
    assert self.instance is not None, \
8683
      "Cannot retrieve locked instance %s" % self.op.instance_name
8684
    _CheckNodeOnline(self, self.instance.primary_node)
8685

    
8686
  def Exec(self, feedback_fn):
8687
    """Connect to the console of an instance
8688

8689
    """
8690
    instance = self.instance
8691
    node = instance.primary_node
8692

    
8693
    node_insts = self.rpc.call_instance_list([node],
8694
                                             [instance.hypervisor])[node]
8695
    node_insts.Raise("Can't get node information from %s" % node)
8696

    
8697
    if instance.name not in node_insts.payload:
8698
      if instance.admin_up:
8699
        state = constants.INSTST_ERRORDOWN
8700
      else:
8701
        state = constants.INSTST_ADMINDOWN
8702
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8703
                               (instance.name, state))
8704

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

    
8707
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8708

    
8709

    
8710
def _GetInstanceConsole(cluster, instance):
8711
  """Returns console information for an instance.
8712

8713
  @type cluster: L{objects.Cluster}
8714
  @type instance: L{objects.Instance}
8715
  @rtype: dict
8716

8717
  """
8718
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8719
  # beparams and hvparams are passed separately, to avoid editing the
8720
  # instance and then saving the defaults in the instance itself.
8721
  hvparams = cluster.FillHV(instance)
8722
  beparams = cluster.FillBE(instance)
8723
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8724

    
8725
  assert console.instance == instance.name
8726
  assert console.Validate()
8727

    
8728
  return console.ToDict()
8729

    
8730

    
8731
class LUInstanceReplaceDisks(LogicalUnit):
8732
  """Replace the disks of an instance.
8733

8734
  """
8735
  HPATH = "mirrors-replace"
8736
  HTYPE = constants.HTYPE_INSTANCE
8737
  REQ_BGL = False
8738

    
8739
  def CheckArguments(self):
8740
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8741
                                  self.op.iallocator)
8742

    
8743
  def ExpandNames(self):
8744
    self._ExpandAndLockInstance()
8745

    
8746
    assert locking.LEVEL_NODE not in self.needed_locks
8747
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8748

    
8749
    assert self.op.iallocator is None or self.op.remote_node is None, \
8750
      "Conflicting options"
8751

    
8752
    if self.op.remote_node is not None:
8753
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8754

    
8755
      # Warning: do not remove the locking of the new secondary here
8756
      # unless DRBD8.AddChildren is changed to work in parallel;
8757
      # currently it doesn't since parallel invocations of
8758
      # FindUnusedMinor will conflict
8759
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8760
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8761
    else:
8762
      self.needed_locks[locking.LEVEL_NODE] = []
8763
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8764

    
8765
      if self.op.iallocator is not None:
8766
        # iallocator will select a new node in the same group
8767
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8768

    
8769
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8770
                                   self.op.iallocator, self.op.remote_node,
8771
                                   self.op.disks, False, self.op.early_release)
8772

    
8773
    self.tasklets = [self.replacer]
8774

    
8775
  def DeclareLocks(self, level):
8776
    if level == locking.LEVEL_NODEGROUP:
8777
      assert self.op.remote_node is None
8778
      assert self.op.iallocator is not None
8779
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8780

    
8781
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8782
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8783
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8784

    
8785
    elif level == locking.LEVEL_NODE:
8786
      if self.op.iallocator is not None:
8787
        assert self.op.remote_node is None
8788
        assert not self.needed_locks[locking.LEVEL_NODE]
8789

    
8790
        # Lock member nodes of all locked groups
8791
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8792
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8793
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8794
      else:
8795
        self._LockInstancesNodes()
8796

    
8797
  def BuildHooksEnv(self):
8798
    """Build hooks env.
8799

8800
    This runs on the master, the primary and all the secondaries.
8801

8802
    """
8803
    instance = self.replacer.instance
8804
    env = {
8805
      "MODE": self.op.mode,
8806
      "NEW_SECONDARY": self.op.remote_node,
8807
      "OLD_SECONDARY": instance.secondary_nodes[0],
8808
      }
8809
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8810
    return env
8811

    
8812
  def BuildHooksNodes(self):
8813
    """Build hooks nodes.
8814

8815
    """
8816
    instance = self.replacer.instance
8817
    nl = [
8818
      self.cfg.GetMasterNode(),
8819
      instance.primary_node,
8820
      ]
8821
    if self.op.remote_node is not None:
8822
      nl.append(self.op.remote_node)
8823
    return nl, nl
8824

    
8825
  def CheckPrereq(self):
8826
    """Check prerequisites.
8827

8828
    """
8829
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8830
            self.op.iallocator is None)
8831

    
8832
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8833
    if owned_groups:
8834
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8835
      if owned_groups != groups:
8836
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8837
                                 " since lock was acquired, current list is %r,"
8838
                                 " used to be '%s'" %
8839
                                 (self.op.instance_name,
8840
                                  utils.CommaJoin(groups),
8841
                                  utils.CommaJoin(owned_groups)))
8842

    
8843
    return LogicalUnit.CheckPrereq(self)
8844

    
8845

    
8846
class TLReplaceDisks(Tasklet):
8847
  """Replaces disks for an instance.
8848

8849
  Note: Locking is not within the scope of this class.
8850

8851
  """
8852
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8853
               disks, delay_iallocator, early_release):
8854
    """Initializes this class.
8855

8856
    """
8857
    Tasklet.__init__(self, lu)
8858

    
8859
    # Parameters
8860
    self.instance_name = instance_name
8861
    self.mode = mode
8862
    self.iallocator_name = iallocator_name
8863
    self.remote_node = remote_node
8864
    self.disks = disks
8865
    self.delay_iallocator = delay_iallocator
8866
    self.early_release = early_release
8867

    
8868
    # Runtime data
8869
    self.instance = None
8870
    self.new_node = None
8871
    self.target_node = None
8872
    self.other_node = None
8873
    self.remote_node_info = None
8874
    self.node_secondary_ip = None
8875

    
8876
  @staticmethod
8877
  def CheckArguments(mode, remote_node, iallocator):
8878
    """Helper function for users of this class.
8879

8880
    """
8881
    # check for valid parameter combination
8882
    if mode == constants.REPLACE_DISK_CHG:
8883
      if remote_node is None and iallocator is None:
8884
        raise errors.OpPrereqError("When changing the secondary either an"
8885
                                   " iallocator script must be used or the"
8886
                                   " new node given", errors.ECODE_INVAL)
8887

    
8888
      if remote_node is not None and iallocator is not None:
8889
        raise errors.OpPrereqError("Give either the iallocator or the new"
8890
                                   " secondary, not both", errors.ECODE_INVAL)
8891

    
8892
    elif remote_node is not None or iallocator is not None:
8893
      # Not replacing the secondary
8894
      raise errors.OpPrereqError("The iallocator and new node options can"
8895
                                 " only be used when changing the"
8896
                                 " secondary node", errors.ECODE_INVAL)
8897

    
8898
  @staticmethod
8899
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8900
    """Compute a new secondary node using an IAllocator.
8901

8902
    """
8903
    ial = IAllocator(lu.cfg, lu.rpc,
8904
                     mode=constants.IALLOCATOR_MODE_RELOC,
8905
                     name=instance_name,
8906
                     relocate_from=relocate_from)
8907

    
8908
    ial.Run(iallocator_name)
8909

    
8910
    if not ial.success:
8911
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8912
                                 " %s" % (iallocator_name, ial.info),
8913
                                 errors.ECODE_NORES)
8914

    
8915
    if len(ial.result) != ial.required_nodes:
8916
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8917
                                 " of nodes (%s), required %s" %
8918
                                 (iallocator_name,
8919
                                  len(ial.result), ial.required_nodes),
8920
                                 errors.ECODE_FAULT)
8921

    
8922
    remote_node_name = ial.result[0]
8923

    
8924
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8925
               instance_name, remote_node_name)
8926

    
8927
    return remote_node_name
8928

    
8929
  def _FindFaultyDisks(self, node_name):
8930
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8931
                                    node_name, True)
8932

    
8933
  def _CheckDisksActivated(self, instance):
8934
    """Checks if the instance disks are activated.
8935

8936
    @param instance: The instance to check disks
8937
    @return: True if they are activated, False otherwise
8938

8939
    """
8940
    nodes = instance.all_nodes
8941

    
8942
    for idx, dev in enumerate(instance.disks):
8943
      for node in nodes:
8944
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
8945
        self.cfg.SetDiskID(dev, node)
8946

    
8947
        result = self.rpc.call_blockdev_find(node, dev)
8948

    
8949
        if result.offline:
8950
          continue
8951
        elif result.fail_msg or not result.payload:
8952
          return False
8953

    
8954
    return True
8955

    
8956
  def CheckPrereq(self):
8957
    """Check prerequisites.
8958

8959
    This checks that the instance is in the cluster.
8960

8961
    """
8962
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8963
    assert instance is not None, \
8964
      "Cannot retrieve locked instance %s" % self.instance_name
8965

    
8966
    if instance.disk_template != constants.DT_DRBD8:
8967
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8968
                                 " instances", errors.ECODE_INVAL)
8969

    
8970
    if len(instance.secondary_nodes) != 1:
8971
      raise errors.OpPrereqError("The instance has a strange layout,"
8972
                                 " expected one secondary but found %d" %
8973
                                 len(instance.secondary_nodes),
8974
                                 errors.ECODE_FAULT)
8975

    
8976
    if not self.delay_iallocator:
8977
      self._CheckPrereq2()
8978

    
8979
  def _CheckPrereq2(self):
8980
    """Check prerequisites, second part.
8981

8982
    This function should always be part of CheckPrereq. It was separated and is
8983
    now called from Exec because during node evacuation iallocator was only
8984
    called with an unmodified cluster model, not taking planned changes into
8985
    account.
8986

8987
    """
8988
    instance = self.instance
8989
    secondary_node = instance.secondary_nodes[0]
8990

    
8991
    if self.iallocator_name is None:
8992
      remote_node = self.remote_node
8993
    else:
8994
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8995
                                       instance.name, instance.secondary_nodes)
8996

    
8997
    if remote_node is None:
8998
      self.remote_node_info = None
8999
    else:
9000
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
9001
             "Remote node '%s' is not locked" % remote_node
9002

    
9003
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9004
      assert self.remote_node_info is not None, \
9005
        "Cannot retrieve locked node %s" % remote_node
9006

    
9007
    if remote_node == self.instance.primary_node:
9008
      raise errors.OpPrereqError("The specified node is the primary node of"
9009
                                 " the instance", errors.ECODE_INVAL)
9010

    
9011
    if remote_node == secondary_node:
9012
      raise errors.OpPrereqError("The specified node is already the"
9013
                                 " secondary node of the instance",
9014
                                 errors.ECODE_INVAL)
9015

    
9016
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9017
                                    constants.REPLACE_DISK_CHG):
9018
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
9019
                                 errors.ECODE_INVAL)
9020

    
9021
    if self.mode == constants.REPLACE_DISK_AUTO:
9022
      if not self._CheckDisksActivated(instance):
9023
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
9024
                                   " first" % self.instance_name,
9025
                                   errors.ECODE_STATE)
9026
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
9027
      faulty_secondary = self._FindFaultyDisks(secondary_node)
9028

    
9029
      if faulty_primary and faulty_secondary:
9030
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9031
                                   " one node and can not be repaired"
9032
                                   " automatically" % self.instance_name,
9033
                                   errors.ECODE_STATE)
9034

    
9035
      if faulty_primary:
9036
        self.disks = faulty_primary
9037
        self.target_node = instance.primary_node
9038
        self.other_node = secondary_node
9039
        check_nodes = [self.target_node, self.other_node]
9040
      elif faulty_secondary:
9041
        self.disks = faulty_secondary
9042
        self.target_node = secondary_node
9043
        self.other_node = instance.primary_node
9044
        check_nodes = [self.target_node, self.other_node]
9045
      else:
9046
        self.disks = []
9047
        check_nodes = []
9048

    
9049
    else:
9050
      # Non-automatic modes
9051
      if self.mode == constants.REPLACE_DISK_PRI:
9052
        self.target_node = instance.primary_node
9053
        self.other_node = secondary_node
9054
        check_nodes = [self.target_node, self.other_node]
9055

    
9056
      elif self.mode == constants.REPLACE_DISK_SEC:
9057
        self.target_node = secondary_node
9058
        self.other_node = instance.primary_node
9059
        check_nodes = [self.target_node, self.other_node]
9060

    
9061
      elif self.mode == constants.REPLACE_DISK_CHG:
9062
        self.new_node = remote_node
9063
        self.other_node = instance.primary_node
9064
        self.target_node = secondary_node
9065
        check_nodes = [self.new_node, self.other_node]
9066

    
9067
        _CheckNodeNotDrained(self.lu, remote_node)
9068
        _CheckNodeVmCapable(self.lu, remote_node)
9069

    
9070
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
9071
        assert old_node_info is not None
9072
        if old_node_info.offline and not self.early_release:
9073
          # doesn't make sense to delay the release
9074
          self.early_release = True
9075
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9076
                          " early-release mode", secondary_node)
9077

    
9078
      else:
9079
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9080
                                     self.mode)
9081

    
9082
      # If not specified all disks should be replaced
9083
      if not self.disks:
9084
        self.disks = range(len(self.instance.disks))
9085

    
9086
    for node in check_nodes:
9087
      _CheckNodeOnline(self.lu, node)
9088

    
9089
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
9090
                                                          self.other_node,
9091
                                                          self.target_node]
9092
                              if node_name is not None)
9093

    
9094
    # Release unneeded node locks
9095
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9096

    
9097
    # Release any owned node group
9098
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9099
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9100

    
9101
    # Check whether disks are valid
9102
    for disk_idx in self.disks:
9103
      instance.FindDisk(disk_idx)
9104

    
9105
    # Get secondary node IP addresses
9106
    self.node_secondary_ip = \
9107
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
9108
           for node_name in touched_nodes)
9109

    
9110
  def Exec(self, feedback_fn):
9111
    """Execute disk replacement.
9112

9113
    This dispatches the disk replacement to the appropriate handler.
9114

9115
    """
9116
    if self.delay_iallocator:
9117
      self._CheckPrereq2()
9118

    
9119
    if __debug__:
9120
      # Verify owned locks before starting operation
9121
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9122
      assert set(owned_locks) == set(self.node_secondary_ip), \
9123
          ("Incorrect node locks, owning %s, expected %s" %
9124
           (owned_locks, self.node_secondary_ip.keys()))
9125

    
9126
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9127
      assert list(owned_locks) == [self.instance_name], \
9128
          "Instance '%s' not locked" % self.instance_name
9129

    
9130
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9131
          "Should not own any node group lock at this point"
9132

    
9133
    if not self.disks:
9134
      feedback_fn("No disks need replacement")
9135
      return
9136

    
9137
    feedback_fn("Replacing disk(s) %s for %s" %
9138
                (utils.CommaJoin(self.disks), self.instance.name))
9139

    
9140
    activate_disks = (not self.instance.admin_up)
9141

    
9142
    # Activate the instance disks if we're replacing them on a down instance
9143
    if activate_disks:
9144
      _StartInstanceDisks(self.lu, self.instance, True)
9145

    
9146
    try:
9147
      # Should we replace the secondary node?
9148
      if self.new_node is not None:
9149
        fn = self._ExecDrbd8Secondary
9150
      else:
9151
        fn = self._ExecDrbd8DiskOnly
9152

    
9153
      result = fn(feedback_fn)
9154
    finally:
9155
      # Deactivate the instance disks if we're replacing them on a
9156
      # down instance
9157
      if activate_disks:
9158
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9159

    
9160
    if __debug__:
9161
      # Verify owned locks
9162
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9163
      nodes = frozenset(self.node_secondary_ip)
9164
      assert ((self.early_release and not owned_locks) or
9165
              (not self.early_release and not (set(owned_locks) - nodes))), \
9166
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9167
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9168

    
9169
    return result
9170

    
9171
  def _CheckVolumeGroup(self, nodes):
9172
    self.lu.LogInfo("Checking volume groups")
9173

    
9174
    vgname = self.cfg.GetVGName()
9175

    
9176
    # Make sure volume group exists on all involved nodes
9177
    results = self.rpc.call_vg_list(nodes)
9178
    if not results:
9179
      raise errors.OpExecError("Can't list volume groups on the nodes")
9180

    
9181
    for node in nodes:
9182
      res = results[node]
9183
      res.Raise("Error checking node %s" % node)
9184
      if vgname not in res.payload:
9185
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9186
                                 (vgname, node))
9187

    
9188
  def _CheckDisksExistence(self, nodes):
9189
    # Check disk existence
9190
    for idx, dev in enumerate(self.instance.disks):
9191
      if idx not in self.disks:
9192
        continue
9193

    
9194
      for node in nodes:
9195
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9196
        self.cfg.SetDiskID(dev, node)
9197

    
9198
        result = self.rpc.call_blockdev_find(node, dev)
9199

    
9200
        msg = result.fail_msg
9201
        if msg or not result.payload:
9202
          if not msg:
9203
            msg = "disk not found"
9204
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9205
                                   (idx, node, msg))
9206

    
9207
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9208
    for idx, dev in enumerate(self.instance.disks):
9209
      if idx not in self.disks:
9210
        continue
9211

    
9212
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9213
                      (idx, node_name))
9214

    
9215
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9216
                                   ldisk=ldisk):
9217
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9218
                                 " replace disks for instance %s" %
9219
                                 (node_name, self.instance.name))
9220

    
9221
  def _CreateNewStorage(self, node_name):
9222
    iv_names = {}
9223

    
9224
    for idx, dev in enumerate(self.instance.disks):
9225
      if idx not in self.disks:
9226
        continue
9227

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

    
9230
      self.cfg.SetDiskID(dev, node_name)
9231

    
9232
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9233
      names = _GenerateUniqueNames(self.lu, lv_names)
9234

    
9235
      vg_data = dev.children[0].logical_id[0]
9236
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9237
                             logical_id=(vg_data, names[0]))
9238
      vg_meta = dev.children[1].logical_id[0]
9239
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9240
                             logical_id=(vg_meta, names[1]))
9241

    
9242
      new_lvs = [lv_data, lv_meta]
9243
      old_lvs = dev.children
9244
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9245

    
9246
      # we pass force_create=True to force the LVM creation
9247
      for new_lv in new_lvs:
9248
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9249
                        _GetInstanceInfoText(self.instance), False)
9250

    
9251
    return iv_names
9252

    
9253
  def _CheckDevices(self, node_name, iv_names):
9254
    for name, (dev, _, _) in iv_names.iteritems():
9255
      self.cfg.SetDiskID(dev, node_name)
9256

    
9257
      result = self.rpc.call_blockdev_find(node_name, dev)
9258

    
9259
      msg = result.fail_msg
9260
      if msg or not result.payload:
9261
        if not msg:
9262
          msg = "disk not found"
9263
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9264
                                 (name, msg))
9265

    
9266
      if result.payload.is_degraded:
9267
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9268

    
9269
  def _RemoveOldStorage(self, node_name, iv_names):
9270
    for name, (_, old_lvs, _) in iv_names.iteritems():
9271
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9272

    
9273
      for lv in old_lvs:
9274
        self.cfg.SetDiskID(lv, node_name)
9275

    
9276
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9277
        if msg:
9278
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9279
                             hint="remove unused LVs manually")
9280

    
9281
  def _ExecDrbd8DiskOnly(self, feedback_fn):
9282
    """Replace a disk on the primary or secondary for DRBD 8.
9283

9284
    The algorithm for replace is quite complicated:
9285

9286
      1. for each disk to be replaced:
9287

9288
        1. create new LVs on the target node with unique names
9289
        1. detach old LVs from the drbd device
9290
        1. rename old LVs to name_replaced.<time_t>
9291
        1. rename new LVs to old LVs
9292
        1. attach the new LVs (with the old names now) to the drbd device
9293

9294
      1. wait for sync across all devices
9295

9296
      1. for each modified disk:
9297

9298
        1. remove old LVs (which have the name name_replaces.<time_t>)
9299

9300
    Failures are not very well handled.
9301

9302
    """
9303
    steps_total = 6
9304

    
9305
    # Step: check device activation
9306
    self.lu.LogStep(1, steps_total, "Check device existence")
9307
    self._CheckDisksExistence([self.other_node, self.target_node])
9308
    self._CheckVolumeGroup([self.target_node, self.other_node])
9309

    
9310
    # Step: check other node consistency
9311
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9312
    self._CheckDisksConsistency(self.other_node,
9313
                                self.other_node == self.instance.primary_node,
9314
                                False)
9315

    
9316
    # Step: create new storage
9317
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9318
    iv_names = self._CreateNewStorage(self.target_node)
9319

    
9320
    # Step: for each lv, detach+rename*2+attach
9321
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9322
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9323
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9324

    
9325
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9326
                                                     old_lvs)
9327
      result.Raise("Can't detach drbd from local storage on node"
9328
                   " %s for device %s" % (self.target_node, dev.iv_name))
9329
      #dev.children = []
9330
      #cfg.Update(instance)
9331

    
9332
      # ok, we created the new LVs, so now we know we have the needed
9333
      # storage; as such, we proceed on the target node to rename
9334
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9335
      # using the assumption that logical_id == physical_id (which in
9336
      # turn is the unique_id on that node)
9337

    
9338
      # FIXME(iustin): use a better name for the replaced LVs
9339
      temp_suffix = int(time.time())
9340
      ren_fn = lambda d, suff: (d.physical_id[0],
9341
                                d.physical_id[1] + "_replaced-%s" % suff)
9342

    
9343
      # Build the rename list based on what LVs exist on the node
9344
      rename_old_to_new = []
9345
      for to_ren in old_lvs:
9346
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9347
        if not result.fail_msg and result.payload:
9348
          # device exists
9349
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9350

    
9351
      self.lu.LogInfo("Renaming the old LVs on the target node")
9352
      result = self.rpc.call_blockdev_rename(self.target_node,
9353
                                             rename_old_to_new)
9354
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9355

    
9356
      # Now we rename the new LVs to the old LVs
9357
      self.lu.LogInfo("Renaming the new LVs on the target node")
9358
      rename_new_to_old = [(new, old.physical_id)
9359
                           for old, new in zip(old_lvs, new_lvs)]
9360
      result = self.rpc.call_blockdev_rename(self.target_node,
9361
                                             rename_new_to_old)
9362
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9363

    
9364
      for old, new in zip(old_lvs, new_lvs):
9365
        new.logical_id = old.logical_id
9366
        self.cfg.SetDiskID(new, self.target_node)
9367

    
9368
      for disk in old_lvs:
9369
        disk.logical_id = ren_fn(disk, temp_suffix)
9370
        self.cfg.SetDiskID(disk, self.target_node)
9371

    
9372
      # Now that the new lvs have the old name, we can add them to the device
9373
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9374
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9375
                                                  new_lvs)
9376
      msg = result.fail_msg
9377
      if msg:
9378
        for new_lv in new_lvs:
9379
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9380
                                               new_lv).fail_msg
9381
          if msg2:
9382
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9383
                               hint=("cleanup manually the unused logical"
9384
                                     "volumes"))
9385
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9386

    
9387
      dev.children = new_lvs
9388

    
9389
      self.cfg.Update(self.instance, feedback_fn)
9390

    
9391
    cstep = 5
9392
    if self.early_release:
9393
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9394
      cstep += 1
9395
      self._RemoveOldStorage(self.target_node, iv_names)
9396
      # WARNING: we release both node locks here, do not do other RPCs
9397
      # than WaitForSync to the primary node
9398
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9399
                    names=[self.target_node, self.other_node])
9400

    
9401
    # Wait for sync
9402
    # This can fail as the old devices are degraded and _WaitForSync
9403
    # does a combined result over all disks, so we don't check its return value
9404
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9405
    cstep += 1
9406
    _WaitForSync(self.lu, self.instance)
9407

    
9408
    # Check all devices manually
9409
    self._CheckDevices(self.instance.primary_node, iv_names)
9410

    
9411
    # Step: remove old storage
9412
    if not self.early_release:
9413
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9414
      cstep += 1
9415
      self._RemoveOldStorage(self.target_node, iv_names)
9416

    
9417
  def _ExecDrbd8Secondary(self, feedback_fn):
9418
    """Replace the secondary node for DRBD 8.
9419

9420
    The algorithm for replace is quite complicated:
9421
      - for all disks of the instance:
9422
        - create new LVs on the new node with same names
9423
        - shutdown the drbd device on the old secondary
9424
        - disconnect the drbd network on the primary
9425
        - create the drbd device on the new secondary
9426
        - network attach the drbd on the primary, using an artifice:
9427
          the drbd code for Attach() will connect to the network if it
9428
          finds a device which is connected to the good local disks but
9429
          not network enabled
9430
      - wait for sync across all devices
9431
      - remove all disks from the old secondary
9432

9433
    Failures are not very well handled.
9434

9435
    """
9436
    steps_total = 6
9437

    
9438
    # Step: check device activation
9439
    self.lu.LogStep(1, steps_total, "Check device existence")
9440
    self._CheckDisksExistence([self.instance.primary_node])
9441
    self._CheckVolumeGroup([self.instance.primary_node])
9442

    
9443
    # Step: check other node consistency
9444
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9445
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9446

    
9447
    # Step: create new storage
9448
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9449
    for idx, dev in enumerate(self.instance.disks):
9450
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9451
                      (self.new_node, idx))
9452
      # we pass force_create=True to force LVM creation
9453
      for new_lv in dev.children:
9454
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9455
                        _GetInstanceInfoText(self.instance), False)
9456

    
9457
    # Step 4: dbrd minors and drbd setups changes
9458
    # after this, we must manually remove the drbd minors on both the
9459
    # error and the success paths
9460
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9461
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9462
                                         for dev in self.instance.disks],
9463
                                        self.instance.name)
9464
    logging.debug("Allocated minors %r", minors)
9465

    
9466
    iv_names = {}
9467
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9468
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9469
                      (self.new_node, idx))
9470
      # create new devices on new_node; note that we create two IDs:
9471
      # one without port, so the drbd will be activated without
9472
      # networking information on the new node at this stage, and one
9473
      # with network, for the latter activation in step 4
9474
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9475
      if self.instance.primary_node == o_node1:
9476
        p_minor = o_minor1
9477
      else:
9478
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9479
        p_minor = o_minor2
9480

    
9481
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9482
                      p_minor, new_minor, o_secret)
9483
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9484
                    p_minor, new_minor, o_secret)
9485

    
9486
      iv_names[idx] = (dev, dev.children, new_net_id)
9487
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9488
                    new_net_id)
9489
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9490
                              logical_id=new_alone_id,
9491
                              children=dev.children,
9492
                              size=dev.size)
9493
      try:
9494
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9495
                              _GetInstanceInfoText(self.instance), False)
9496
      except errors.GenericError:
9497
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9498
        raise
9499

    
9500
    # We have new devices, shutdown the drbd on the old secondary
9501
    for idx, dev in enumerate(self.instance.disks):
9502
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9503
      self.cfg.SetDiskID(dev, self.target_node)
9504
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9505
      if msg:
9506
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9507
                           "node: %s" % (idx, msg),
9508
                           hint=("Please cleanup this device manually as"
9509
                                 " soon as possible"))
9510

    
9511
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9512
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9513
                                               self.node_secondary_ip,
9514
                                               self.instance.disks)\
9515
                                              [self.instance.primary_node]
9516

    
9517
    msg = result.fail_msg
9518
    if msg:
9519
      # detaches didn't succeed (unlikely)
9520
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9521
      raise errors.OpExecError("Can't detach the disks from the network on"
9522
                               " old node: %s" % (msg,))
9523

    
9524
    # if we managed to detach at least one, we update all the disks of
9525
    # the instance to point to the new secondary
9526
    self.lu.LogInfo("Updating instance configuration")
9527
    for dev, _, new_logical_id in iv_names.itervalues():
9528
      dev.logical_id = new_logical_id
9529
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9530

    
9531
    self.cfg.Update(self.instance, feedback_fn)
9532

    
9533
    # and now perform the drbd attach
9534
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9535
                    " (standalone => connected)")
9536
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9537
                                            self.new_node],
9538
                                           self.node_secondary_ip,
9539
                                           self.instance.disks,
9540
                                           self.instance.name,
9541
                                           False)
9542
    for to_node, to_result in result.items():
9543
      msg = to_result.fail_msg
9544
      if msg:
9545
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9546
                           to_node, msg,
9547
                           hint=("please do a gnt-instance info to see the"
9548
                                 " status of disks"))
9549
    cstep = 5
9550
    if self.early_release:
9551
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9552
      cstep += 1
9553
      self._RemoveOldStorage(self.target_node, iv_names)
9554
      # WARNING: we release all node locks here, do not do other RPCs
9555
      # than WaitForSync to the primary node
9556
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9557
                    names=[self.instance.primary_node,
9558
                           self.target_node,
9559
                           self.new_node])
9560

    
9561
    # Wait for sync
9562
    # This can fail as the old devices are degraded and _WaitForSync
9563
    # does a combined result over all disks, so we don't check its return value
9564
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9565
    cstep += 1
9566
    _WaitForSync(self.lu, self.instance)
9567

    
9568
    # Check all devices manually
9569
    self._CheckDevices(self.instance.primary_node, iv_names)
9570

    
9571
    # Step: remove old storage
9572
    if not self.early_release:
9573
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9574
      self._RemoveOldStorage(self.target_node, iv_names)
9575

    
9576

    
9577
class LURepairNodeStorage(NoHooksLU):
9578
  """Repairs the volume group on a node.
9579

9580
  """
9581
  REQ_BGL = False
9582

    
9583
  def CheckArguments(self):
9584
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9585

    
9586
    storage_type = self.op.storage_type
9587

    
9588
    if (constants.SO_FIX_CONSISTENCY not in
9589
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9590
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9591
                                 " repaired" % storage_type,
9592
                                 errors.ECODE_INVAL)
9593

    
9594
  def ExpandNames(self):
9595
    self.needed_locks = {
9596
      locking.LEVEL_NODE: [self.op.node_name],
9597
      }
9598

    
9599
  def _CheckFaultyDisks(self, instance, node_name):
9600
    """Ensure faulty disks abort the opcode or at least warn."""
9601
    try:
9602
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9603
                                  node_name, True):
9604
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9605
                                   " node '%s'" % (instance.name, node_name),
9606
                                   errors.ECODE_STATE)
9607
    except errors.OpPrereqError, err:
9608
      if self.op.ignore_consistency:
9609
        self.proc.LogWarning(str(err.args[0]))
9610
      else:
9611
        raise
9612

    
9613
  def CheckPrereq(self):
9614
    """Check prerequisites.
9615

9616
    """
9617
    # Check whether any instance on this node has faulty disks
9618
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9619
      if not inst.admin_up:
9620
        continue
9621
      check_nodes = set(inst.all_nodes)
9622
      check_nodes.discard(self.op.node_name)
9623
      for inst_node_name in check_nodes:
9624
        self._CheckFaultyDisks(inst, inst_node_name)
9625

    
9626
  def Exec(self, feedback_fn):
9627
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9628
                (self.op.name, self.op.node_name))
9629

    
9630
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9631
    result = self.rpc.call_storage_execute(self.op.node_name,
9632
                                           self.op.storage_type, st_args,
9633
                                           self.op.name,
9634
                                           constants.SO_FIX_CONSISTENCY)
9635
    result.Raise("Failed to repair storage unit '%s' on %s" %
9636
                 (self.op.name, self.op.node_name))
9637

    
9638

    
9639
class LUNodeEvacStrategy(NoHooksLU):
9640
  """Computes the node evacuation strategy.
9641

9642
  """
9643
  REQ_BGL = False
9644

    
9645
  def CheckArguments(self):
9646
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9647

    
9648
  def ExpandNames(self):
9649
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9650
    self.needed_locks = locks = {}
9651
    if self.op.remote_node is None:
9652
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9653
    else:
9654
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9655
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9656

    
9657
  def Exec(self, feedback_fn):
9658
    if self.op.remote_node is not None:
9659
      instances = []
9660
      for node in self.op.nodes:
9661
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9662
      result = []
9663
      for i in instances:
9664
        if i.primary_node == self.op.remote_node:
9665
          raise errors.OpPrereqError("Node %s is the primary node of"
9666
                                     " instance %s, cannot use it as"
9667
                                     " secondary" %
9668
                                     (self.op.remote_node, i.name),
9669
                                     errors.ECODE_INVAL)
9670
        result.append([i.name, self.op.remote_node])
9671
    else:
9672
      ial = IAllocator(self.cfg, self.rpc,
9673
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9674
                       evac_nodes=self.op.nodes)
9675
      ial.Run(self.op.iallocator, validate=True)
9676
      if not ial.success:
9677
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9678
                                 errors.ECODE_NORES)
9679
      result = ial.result
9680
    return result
9681

    
9682

    
9683
class LUInstanceGrowDisk(LogicalUnit):
9684
  """Grow a disk of an instance.
9685

9686
  """
9687
  HPATH = "disk-grow"
9688
  HTYPE = constants.HTYPE_INSTANCE
9689
  REQ_BGL = False
9690

    
9691
  def ExpandNames(self):
9692
    self._ExpandAndLockInstance()
9693
    self.needed_locks[locking.LEVEL_NODE] = []
9694
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9695

    
9696
  def DeclareLocks(self, level):
9697
    if level == locking.LEVEL_NODE:
9698
      self._LockInstancesNodes()
9699

    
9700
  def BuildHooksEnv(self):
9701
    """Build hooks env.
9702

9703
    This runs on the master, the primary and all the secondaries.
9704

9705
    """
9706
    env = {
9707
      "DISK": self.op.disk,
9708
      "AMOUNT": self.op.amount,
9709
      }
9710
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9711
    return env
9712

    
9713
  def BuildHooksNodes(self):
9714
    """Build hooks nodes.
9715

9716
    """
9717
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9718
    return (nl, nl)
9719

    
9720
  def CheckPrereq(self):
9721
    """Check prerequisites.
9722

9723
    This checks that the instance is in the cluster.
9724

9725
    """
9726
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9727
    assert instance is not None, \
9728
      "Cannot retrieve locked instance %s" % self.op.instance_name
9729
    nodenames = list(instance.all_nodes)
9730
    for node in nodenames:
9731
      _CheckNodeOnline(self, node)
9732

    
9733
    self.instance = instance
9734

    
9735
    if instance.disk_template not in constants.DTS_GROWABLE:
9736
      raise errors.OpPrereqError("Instance's disk layout does not support"
9737
                                 " growing", errors.ECODE_INVAL)
9738

    
9739
    self.disk = instance.FindDisk(self.op.disk)
9740

    
9741
    if instance.disk_template not in (constants.DT_FILE,
9742
                                      constants.DT_SHARED_FILE):
9743
      # TODO: check the free disk space for file, when that feature will be
9744
      # supported
9745
      _CheckNodesFreeDiskPerVG(self, nodenames,
9746
                               self.disk.ComputeGrowth(self.op.amount))
9747

    
9748
  def Exec(self, feedback_fn):
9749
    """Execute disk grow.
9750

9751
    """
9752
    instance = self.instance
9753
    disk = self.disk
9754

    
9755
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9756
    if not disks_ok:
9757
      raise errors.OpExecError("Cannot activate block device to grow")
9758

    
9759
    # First run all grow ops in dry-run mode
9760
    for node in instance.all_nodes:
9761
      self.cfg.SetDiskID(disk, node)
9762
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
9763
      result.Raise("Grow request failed to node %s" % node)
9764

    
9765
    # We know that (as far as we can test) operations across different
9766
    # nodes will succeed, time to run it for real
9767
    for node in instance.all_nodes:
9768
      self.cfg.SetDiskID(disk, node)
9769
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
9770
      result.Raise("Grow request failed to node %s" % node)
9771

    
9772
      # TODO: Rewrite code to work properly
9773
      # DRBD goes into sync mode for a short amount of time after executing the
9774
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9775
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9776
      # time is a work-around.
9777
      time.sleep(5)
9778

    
9779
    disk.RecordGrow(self.op.amount)
9780
    self.cfg.Update(instance, feedback_fn)
9781
    if self.op.wait_for_sync:
9782
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9783
      if disk_abort:
9784
        self.proc.LogWarning("Disk sync-ing has not returned a good"
9785
                             " status; please check the instance")
9786
      if not instance.admin_up:
9787
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9788
    elif not instance.admin_up:
9789
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9790
                           " not supposed to be running because no wait for"
9791
                           " sync mode was requested")
9792

    
9793

    
9794
class LUInstanceQueryData(NoHooksLU):
9795
  """Query runtime instance data.
9796

9797
  """
9798
  REQ_BGL = False
9799

    
9800
  def ExpandNames(self):
9801
    self.needed_locks = {}
9802

    
9803
    # Use locking if requested or when non-static information is wanted
9804
    if not (self.op.static or self.op.use_locking):
9805
      self.LogWarning("Non-static data requested, locks need to be acquired")
9806
      self.op.use_locking = True
9807

    
9808
    if self.op.instances or not self.op.use_locking:
9809
      # Expand instance names right here
9810
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
9811
    else:
9812
      # Will use acquired locks
9813
      self.wanted_names = None
9814

    
9815
    if self.op.use_locking:
9816
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9817

    
9818
      if self.wanted_names is None:
9819
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9820
      else:
9821
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9822

    
9823
      self.needed_locks[locking.LEVEL_NODE] = []
9824
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9825
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9826

    
9827
  def DeclareLocks(self, level):
9828
    if self.op.use_locking and level == locking.LEVEL_NODE:
9829
      self._LockInstancesNodes()
9830

    
9831
  def CheckPrereq(self):
9832
    """Check prerequisites.
9833

9834
    This only checks the optional instance list against the existing names.
9835

9836
    """
9837
    if self.wanted_names is None:
9838
      assert self.op.use_locking, "Locking was not used"
9839
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
9840

    
9841
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
9842
                             for name in self.wanted_names]
9843

    
9844
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9845
    """Returns the status of a block device
9846

9847
    """
9848
    if self.op.static or not node:
9849
      return None
9850

    
9851
    self.cfg.SetDiskID(dev, node)
9852

    
9853
    result = self.rpc.call_blockdev_find(node, dev)
9854
    if result.offline:
9855
      return None
9856

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

    
9859
    status = result.payload
9860
    if status is None:
9861
      return None
9862

    
9863
    return (status.dev_path, status.major, status.minor,
9864
            status.sync_percent, status.estimated_time,
9865
            status.is_degraded, status.ldisk_status)
9866

    
9867
  def _ComputeDiskStatus(self, instance, snode, dev):
9868
    """Compute block device status.
9869

9870
    """
9871
    if dev.dev_type in constants.LDS_DRBD:
9872
      # we change the snode then (otherwise we use the one passed in)
9873
      if dev.logical_id[0] == instance.primary_node:
9874
        snode = dev.logical_id[1]
9875
      else:
9876
        snode = dev.logical_id[0]
9877

    
9878
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9879
                                              instance.name, dev)
9880
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9881

    
9882
    if dev.children:
9883
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9884
                      for child in dev.children]
9885
    else:
9886
      dev_children = []
9887

    
9888
    return {
9889
      "iv_name": dev.iv_name,
9890
      "dev_type": dev.dev_type,
9891
      "logical_id": dev.logical_id,
9892
      "physical_id": dev.physical_id,
9893
      "pstatus": dev_pstatus,
9894
      "sstatus": dev_sstatus,
9895
      "children": dev_children,
9896
      "mode": dev.mode,
9897
      "size": dev.size,
9898
      }
9899

    
9900
  def Exec(self, feedback_fn):
9901
    """Gather and return data"""
9902
    result = {}
9903

    
9904
    cluster = self.cfg.GetClusterInfo()
9905

    
9906
    for instance in self.wanted_instances:
9907
      if not self.op.static:
9908
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9909
                                                  instance.name,
9910
                                                  instance.hypervisor)
9911
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9912
        remote_info = remote_info.payload
9913
        if remote_info and "state" in remote_info:
9914
          remote_state = "up"
9915
        else:
9916
          remote_state = "down"
9917
      else:
9918
        remote_state = None
9919
      if instance.admin_up:
9920
        config_state = "up"
9921
      else:
9922
        config_state = "down"
9923

    
9924
      disks = [self._ComputeDiskStatus(instance, None, device)
9925
               for device in instance.disks]
9926

    
9927
      result[instance.name] = {
9928
        "name": instance.name,
9929
        "config_state": config_state,
9930
        "run_state": remote_state,
9931
        "pnode": instance.primary_node,
9932
        "snodes": instance.secondary_nodes,
9933
        "os": instance.os,
9934
        # this happens to be the same format used for hooks
9935
        "nics": _NICListToTuple(self, instance.nics),
9936
        "disk_template": instance.disk_template,
9937
        "disks": disks,
9938
        "hypervisor": instance.hypervisor,
9939
        "network_port": instance.network_port,
9940
        "hv_instance": instance.hvparams,
9941
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9942
        "be_instance": instance.beparams,
9943
        "be_actual": cluster.FillBE(instance),
9944
        "os_instance": instance.osparams,
9945
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9946
        "serial_no": instance.serial_no,
9947
        "mtime": instance.mtime,
9948
        "ctime": instance.ctime,
9949
        "uuid": instance.uuid,
9950
        }
9951

    
9952
    return result
9953

    
9954

    
9955
class LUInstanceSetParams(LogicalUnit):
9956
  """Modifies an instances's parameters.
9957

9958
  """
9959
  HPATH = "instance-modify"
9960
  HTYPE = constants.HTYPE_INSTANCE
9961
  REQ_BGL = False
9962

    
9963
  def CheckArguments(self):
9964
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9965
            self.op.hvparams or self.op.beparams or self.op.os_name):
9966
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9967

    
9968
    if self.op.hvparams:
9969
      _CheckGlobalHvParams(self.op.hvparams)
9970

    
9971
    # Disk validation
9972
    disk_addremove = 0
9973
    for disk_op, disk_dict in self.op.disks:
9974
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9975
      if disk_op == constants.DDM_REMOVE:
9976
        disk_addremove += 1
9977
        continue
9978
      elif disk_op == constants.DDM_ADD:
9979
        disk_addremove += 1
9980
      else:
9981
        if not isinstance(disk_op, int):
9982
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9983
        if not isinstance(disk_dict, dict):
9984
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9985
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9986

    
9987
      if disk_op == constants.DDM_ADD:
9988
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
9989
        if mode not in constants.DISK_ACCESS_SET:
9990
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9991
                                     errors.ECODE_INVAL)
9992
        size = disk_dict.get(constants.IDISK_SIZE, None)
9993
        if size is None:
9994
          raise errors.OpPrereqError("Required disk parameter size missing",
9995
                                     errors.ECODE_INVAL)
9996
        try:
9997
          size = int(size)
9998
        except (TypeError, ValueError), err:
9999
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10000
                                     str(err), errors.ECODE_INVAL)
10001
        disk_dict[constants.IDISK_SIZE] = size
10002
      else:
10003
        # modification of disk
10004
        if constants.IDISK_SIZE in disk_dict:
10005
          raise errors.OpPrereqError("Disk size change not possible, use"
10006
                                     " grow-disk", errors.ECODE_INVAL)
10007

    
10008
    if disk_addremove > 1:
10009
      raise errors.OpPrereqError("Only one disk add or remove operation"
10010
                                 " supported at a time", errors.ECODE_INVAL)
10011

    
10012
    if self.op.disks and self.op.disk_template is not None:
10013
      raise errors.OpPrereqError("Disk template conversion and other disk"
10014
                                 " changes not supported at the same time",
10015
                                 errors.ECODE_INVAL)
10016

    
10017
    if (self.op.disk_template and
10018
        self.op.disk_template in constants.DTS_INT_MIRROR and
10019
        self.op.remote_node is None):
10020
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
10021
                                 " one requires specifying a secondary node",
10022
                                 errors.ECODE_INVAL)
10023

    
10024
    # NIC validation
10025
    nic_addremove = 0
10026
    for nic_op, nic_dict in self.op.nics:
10027
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10028
      if nic_op == constants.DDM_REMOVE:
10029
        nic_addremove += 1
10030
        continue
10031
      elif nic_op == constants.DDM_ADD:
10032
        nic_addremove += 1
10033
      else:
10034
        if not isinstance(nic_op, int):
10035
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10036
        if not isinstance(nic_dict, dict):
10037
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10038
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10039

    
10040
      # nic_dict should be a dict
10041
      nic_ip = nic_dict.get(constants.INIC_IP, None)
10042
      if nic_ip is not None:
10043
        if nic_ip.lower() == constants.VALUE_NONE:
10044
          nic_dict[constants.INIC_IP] = None
10045
        else:
10046
          if not netutils.IPAddress.IsValid(nic_ip):
10047
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10048
                                       errors.ECODE_INVAL)
10049

    
10050
      nic_bridge = nic_dict.get('bridge', None)
10051
      nic_link = nic_dict.get(constants.INIC_LINK, None)
10052
      if nic_bridge and nic_link:
10053
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10054
                                   " at the same time", errors.ECODE_INVAL)
10055
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10056
        nic_dict['bridge'] = None
10057
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10058
        nic_dict[constants.INIC_LINK] = None
10059

    
10060
      if nic_op == constants.DDM_ADD:
10061
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
10062
        if nic_mac is None:
10063
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10064

    
10065
      if constants.INIC_MAC in nic_dict:
10066
        nic_mac = nic_dict[constants.INIC_MAC]
10067
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10068
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10069

    
10070
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10071
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10072
                                     " modifying an existing nic",
10073
                                     errors.ECODE_INVAL)
10074

    
10075
    if nic_addremove > 1:
10076
      raise errors.OpPrereqError("Only one NIC add or remove operation"
10077
                                 " supported at a time", errors.ECODE_INVAL)
10078

    
10079
  def ExpandNames(self):
10080
    self._ExpandAndLockInstance()
10081
    self.needed_locks[locking.LEVEL_NODE] = []
10082
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10083

    
10084
  def DeclareLocks(self, level):
10085
    if level == locking.LEVEL_NODE:
10086
      self._LockInstancesNodes()
10087
      if self.op.disk_template and self.op.remote_node:
10088
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10089
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10090

    
10091
  def BuildHooksEnv(self):
10092
    """Build hooks env.
10093

10094
    This runs on the master, primary and secondaries.
10095

10096
    """
10097
    args = dict()
10098
    if constants.BE_MEMORY in self.be_new:
10099
      args['memory'] = self.be_new[constants.BE_MEMORY]
10100
    if constants.BE_VCPUS in self.be_new:
10101
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
10102
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10103
    # information at all.
10104
    if self.op.nics:
10105
      args['nics'] = []
10106
      nic_override = dict(self.op.nics)
10107
      for idx, nic in enumerate(self.instance.nics):
10108
        if idx in nic_override:
10109
          this_nic_override = nic_override[idx]
10110
        else:
10111
          this_nic_override = {}
10112
        if constants.INIC_IP in this_nic_override:
10113
          ip = this_nic_override[constants.INIC_IP]
10114
        else:
10115
          ip = nic.ip
10116
        if constants.INIC_MAC in this_nic_override:
10117
          mac = this_nic_override[constants.INIC_MAC]
10118
        else:
10119
          mac = nic.mac
10120
        if idx in self.nic_pnew:
10121
          nicparams = self.nic_pnew[idx]
10122
        else:
10123
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10124
        mode = nicparams[constants.NIC_MODE]
10125
        link = nicparams[constants.NIC_LINK]
10126
        args['nics'].append((ip, mac, mode, link))
10127
      if constants.DDM_ADD in nic_override:
10128
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10129
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10130
        nicparams = self.nic_pnew[constants.DDM_ADD]
10131
        mode = nicparams[constants.NIC_MODE]
10132
        link = nicparams[constants.NIC_LINK]
10133
        args['nics'].append((ip, mac, mode, link))
10134
      elif constants.DDM_REMOVE in nic_override:
10135
        del args['nics'][-1]
10136

    
10137
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10138
    if self.op.disk_template:
10139
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10140

    
10141
    return env
10142

    
10143
  def BuildHooksNodes(self):
10144
    """Build hooks nodes.
10145

10146
    """
10147
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10148
    return (nl, nl)
10149

    
10150
  def CheckPrereq(self):
10151
    """Check prerequisites.
10152

10153
    This only checks the instance list against the existing names.
10154

10155
    """
10156
    # checking the new params on the primary/secondary nodes
10157

    
10158
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10159
    cluster = self.cluster = self.cfg.GetClusterInfo()
10160
    assert self.instance is not None, \
10161
      "Cannot retrieve locked instance %s" % self.op.instance_name
10162
    pnode = instance.primary_node
10163
    nodelist = list(instance.all_nodes)
10164

    
10165
    # OS change
10166
    if self.op.os_name and not self.op.force:
10167
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10168
                      self.op.force_variant)
10169
      instance_os = self.op.os_name
10170
    else:
10171
      instance_os = instance.os
10172

    
10173
    if self.op.disk_template:
10174
      if instance.disk_template == self.op.disk_template:
10175
        raise errors.OpPrereqError("Instance already has disk template %s" %
10176
                                   instance.disk_template, errors.ECODE_INVAL)
10177

    
10178
      if (instance.disk_template,
10179
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10180
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10181
                                   " %s to %s" % (instance.disk_template,
10182
                                                  self.op.disk_template),
10183
                                   errors.ECODE_INVAL)
10184
      _CheckInstanceDown(self, instance, "cannot change disk template")
10185
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10186
        if self.op.remote_node == pnode:
10187
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10188
                                     " as the primary node of the instance" %
10189
                                     self.op.remote_node, errors.ECODE_STATE)
10190
        _CheckNodeOnline(self, self.op.remote_node)
10191
        _CheckNodeNotDrained(self, self.op.remote_node)
10192
        # FIXME: here we assume that the old instance type is DT_PLAIN
10193
        assert instance.disk_template == constants.DT_PLAIN
10194
        disks = [{constants.IDISK_SIZE: d.size,
10195
                  constants.IDISK_VG: d.logical_id[0]}
10196
                 for d in instance.disks]
10197
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10198
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10199

    
10200
    # hvparams processing
10201
    if self.op.hvparams:
10202
      hv_type = instance.hypervisor
10203
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10204
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10205
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10206

    
10207
      # local check
10208
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10209
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10210
      self.hv_new = hv_new # the new actual values
10211
      self.hv_inst = i_hvdict # the new dict (without defaults)
10212
    else:
10213
      self.hv_new = self.hv_inst = {}
10214

    
10215
    # beparams processing
10216
    if self.op.beparams:
10217
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10218
                                   use_none=True)
10219
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10220
      be_new = cluster.SimpleFillBE(i_bedict)
10221
      self.be_new = be_new # the new actual values
10222
      self.be_inst = i_bedict # the new dict (without defaults)
10223
    else:
10224
      self.be_new = self.be_inst = {}
10225
    be_old = cluster.FillBE(instance)
10226

    
10227
    # osparams processing
10228
    if self.op.osparams:
10229
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10230
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10231
      self.os_inst = i_osdict # the new dict (without defaults)
10232
    else:
10233
      self.os_inst = {}
10234

    
10235
    self.warn = []
10236

    
10237
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10238
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10239
      mem_check_list = [pnode]
10240
      if be_new[constants.BE_AUTO_BALANCE]:
10241
        # either we changed auto_balance to yes or it was from before
10242
        mem_check_list.extend(instance.secondary_nodes)
10243
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10244
                                                  instance.hypervisor)
10245
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10246
                                         instance.hypervisor)
10247
      pninfo = nodeinfo[pnode]
10248
      msg = pninfo.fail_msg
10249
      if msg:
10250
        # Assume the primary node is unreachable and go ahead
10251
        self.warn.append("Can't get info from primary node %s: %s" %
10252
                         (pnode,  msg))
10253
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10254
        self.warn.append("Node data from primary node %s doesn't contain"
10255
                         " free memory information" % pnode)
10256
      elif instance_info.fail_msg:
10257
        self.warn.append("Can't get instance runtime information: %s" %
10258
                        instance_info.fail_msg)
10259
      else:
10260
        if instance_info.payload:
10261
          current_mem = int(instance_info.payload['memory'])
10262
        else:
10263
          # Assume instance not running
10264
          # (there is a slight race condition here, but it's not very probable,
10265
          # and we have no other way to check)
10266
          current_mem = 0
10267
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10268
                    pninfo.payload['memory_free'])
10269
        if miss_mem > 0:
10270
          raise errors.OpPrereqError("This change will prevent the instance"
10271
                                     " from starting, due to %d MB of memory"
10272
                                     " missing on its primary node" % miss_mem,
10273
                                     errors.ECODE_NORES)
10274

    
10275
      if be_new[constants.BE_AUTO_BALANCE]:
10276
        for node, nres in nodeinfo.items():
10277
          if node not in instance.secondary_nodes:
10278
            continue
10279
          nres.Raise("Can't get info from secondary node %s" % node,
10280
                     prereq=True, ecode=errors.ECODE_STATE)
10281
          if not isinstance(nres.payload.get('memory_free', None), int):
10282
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10283
                                       " memory information" % node,
10284
                                       errors.ECODE_STATE)
10285
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10286
            raise errors.OpPrereqError("This change will prevent the instance"
10287
                                       " from failover to its secondary node"
10288
                                       " %s, due to not enough memory" % node,
10289
                                       errors.ECODE_STATE)
10290

    
10291
    # NIC processing
10292
    self.nic_pnew = {}
10293
    self.nic_pinst = {}
10294
    for nic_op, nic_dict in self.op.nics:
10295
      if nic_op == constants.DDM_REMOVE:
10296
        if not instance.nics:
10297
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10298
                                     errors.ECODE_INVAL)
10299
        continue
10300
      if nic_op != constants.DDM_ADD:
10301
        # an existing nic
10302
        if not instance.nics:
10303
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10304
                                     " no NICs" % nic_op,
10305
                                     errors.ECODE_INVAL)
10306
        if nic_op < 0 or nic_op >= len(instance.nics):
10307
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10308
                                     " are 0 to %d" %
10309
                                     (nic_op, len(instance.nics) - 1),
10310
                                     errors.ECODE_INVAL)
10311
        old_nic_params = instance.nics[nic_op].nicparams
10312
        old_nic_ip = instance.nics[nic_op].ip
10313
      else:
10314
        old_nic_params = {}
10315
        old_nic_ip = None
10316

    
10317
      update_params_dict = dict([(key, nic_dict[key])
10318
                                 for key in constants.NICS_PARAMETERS
10319
                                 if key in nic_dict])
10320

    
10321
      if 'bridge' in nic_dict:
10322
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10323

    
10324
      new_nic_params = _GetUpdatedParams(old_nic_params,
10325
                                         update_params_dict)
10326
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10327
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10328
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10329
      self.nic_pinst[nic_op] = new_nic_params
10330
      self.nic_pnew[nic_op] = new_filled_nic_params
10331
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10332

    
10333
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10334
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10335
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10336
        if msg:
10337
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10338
          if self.op.force:
10339
            self.warn.append(msg)
10340
          else:
10341
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10342
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10343
        if constants.INIC_IP in nic_dict:
10344
          nic_ip = nic_dict[constants.INIC_IP]
10345
        else:
10346
          nic_ip = old_nic_ip
10347
        if nic_ip is None:
10348
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10349
                                     ' on a routed nic', errors.ECODE_INVAL)
10350
      if constants.INIC_MAC in nic_dict:
10351
        nic_mac = nic_dict[constants.INIC_MAC]
10352
        if nic_mac is None:
10353
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10354
                                     errors.ECODE_INVAL)
10355
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10356
          # otherwise generate the mac
10357
          nic_dict[constants.INIC_MAC] = \
10358
            self.cfg.GenerateMAC(self.proc.GetECId())
10359
        else:
10360
          # or validate/reserve the current one
10361
          try:
10362
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10363
          except errors.ReservationError:
10364
            raise errors.OpPrereqError("MAC address %s already in use"
10365
                                       " in cluster" % nic_mac,
10366
                                       errors.ECODE_NOTUNIQUE)
10367

    
10368
    # DISK processing
10369
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10370
      raise errors.OpPrereqError("Disk operations not supported for"
10371
                                 " diskless instances",
10372
                                 errors.ECODE_INVAL)
10373
    for disk_op, _ in self.op.disks:
10374
      if disk_op == constants.DDM_REMOVE:
10375
        if len(instance.disks) == 1:
10376
          raise errors.OpPrereqError("Cannot remove the last disk of"
10377
                                     " an instance", errors.ECODE_INVAL)
10378
        _CheckInstanceDown(self, instance, "cannot remove disks")
10379

    
10380
      if (disk_op == constants.DDM_ADD and
10381
          len(instance.disks) >= constants.MAX_DISKS):
10382
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10383
                                   " add more" % constants.MAX_DISKS,
10384
                                   errors.ECODE_STATE)
10385
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10386
        # an existing disk
10387
        if disk_op < 0 or disk_op >= len(instance.disks):
10388
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10389
                                     " are 0 to %d" %
10390
                                     (disk_op, len(instance.disks)),
10391
                                     errors.ECODE_INVAL)
10392

    
10393
    return
10394

    
10395
  def _ConvertPlainToDrbd(self, feedback_fn):
10396
    """Converts an instance from plain to drbd.
10397

10398
    """
10399
    feedback_fn("Converting template to drbd")
10400
    instance = self.instance
10401
    pnode = instance.primary_node
10402
    snode = self.op.remote_node
10403

    
10404
    # create a fake disk info for _GenerateDiskTemplate
10405
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10406
                  constants.IDISK_VG: d.logical_id[0]}
10407
                 for d in instance.disks]
10408
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10409
                                      instance.name, pnode, [snode],
10410
                                      disk_info, None, None, 0, feedback_fn)
10411
    info = _GetInstanceInfoText(instance)
10412
    feedback_fn("Creating aditional volumes...")
10413
    # first, create the missing data and meta devices
10414
    for disk in new_disks:
10415
      # unfortunately this is... not too nice
10416
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10417
                            info, True)
10418
      for child in disk.children:
10419
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10420
    # at this stage, all new LVs have been created, we can rename the
10421
    # old ones
10422
    feedback_fn("Renaming original volumes...")
10423
    rename_list = [(o, n.children[0].logical_id)
10424
                   for (o, n) in zip(instance.disks, new_disks)]
10425
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10426
    result.Raise("Failed to rename original LVs")
10427

    
10428
    feedback_fn("Initializing DRBD devices...")
10429
    # all child devices are in place, we can now create the DRBD devices
10430
    for disk in new_disks:
10431
      for node in [pnode, snode]:
10432
        f_create = node == pnode
10433
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10434

    
10435
    # at this point, the instance has been modified
10436
    instance.disk_template = constants.DT_DRBD8
10437
    instance.disks = new_disks
10438
    self.cfg.Update(instance, feedback_fn)
10439

    
10440
    # disks are created, waiting for sync
10441
    disk_abort = not _WaitForSync(self, instance,
10442
                                  oneshot=not self.op.wait_for_sync)
10443
    if disk_abort:
10444
      raise errors.OpExecError("There are some degraded disks for"
10445
                               " this instance, please cleanup manually")
10446

    
10447
  def _ConvertDrbdToPlain(self, feedback_fn):
10448
    """Converts an instance from drbd to plain.
10449

10450
    """
10451
    instance = self.instance
10452
    assert len(instance.secondary_nodes) == 1
10453
    pnode = instance.primary_node
10454
    snode = instance.secondary_nodes[0]
10455
    feedback_fn("Converting template to plain")
10456

    
10457
    old_disks = instance.disks
10458
    new_disks = [d.children[0] for d in old_disks]
10459

    
10460
    # copy over size and mode
10461
    for parent, child in zip(old_disks, new_disks):
10462
      child.size = parent.size
10463
      child.mode = parent.mode
10464

    
10465
    # update instance structure
10466
    instance.disks = new_disks
10467
    instance.disk_template = constants.DT_PLAIN
10468
    self.cfg.Update(instance, feedback_fn)
10469

    
10470
    feedback_fn("Removing volumes on the secondary node...")
10471
    for disk in old_disks:
10472
      self.cfg.SetDiskID(disk, snode)
10473
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10474
      if msg:
10475
        self.LogWarning("Could not remove block device %s on node %s,"
10476
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10477

    
10478
    feedback_fn("Removing unneeded volumes on the primary node...")
10479
    for idx, disk in enumerate(old_disks):
10480
      meta = disk.children[1]
10481
      self.cfg.SetDiskID(meta, pnode)
10482
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10483
      if msg:
10484
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10485
                        " continuing anyway: %s", idx, pnode, msg)
10486

    
10487
  def Exec(self, feedback_fn):
10488
    """Modifies an instance.
10489

10490
    All parameters take effect only at the next restart of the instance.
10491

10492
    """
10493
    # Process here the warnings from CheckPrereq, as we don't have a
10494
    # feedback_fn there.
10495
    for warn in self.warn:
10496
      feedback_fn("WARNING: %s" % warn)
10497

    
10498
    result = []
10499
    instance = self.instance
10500
    # disk changes
10501
    for disk_op, disk_dict in self.op.disks:
10502
      if disk_op == constants.DDM_REMOVE:
10503
        # remove the last disk
10504
        device = instance.disks.pop()
10505
        device_idx = len(instance.disks)
10506
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10507
          self.cfg.SetDiskID(disk, node)
10508
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10509
          if msg:
10510
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10511
                            " continuing anyway", device_idx, node, msg)
10512
        result.append(("disk/%d" % device_idx, "remove"))
10513
      elif disk_op == constants.DDM_ADD:
10514
        # add a new disk
10515
        if instance.disk_template in (constants.DT_FILE,
10516
                                        constants.DT_SHARED_FILE):
10517
          file_driver, file_path = instance.disks[0].logical_id
10518
          file_path = os.path.dirname(file_path)
10519
        else:
10520
          file_driver = file_path = None
10521
        disk_idx_base = len(instance.disks)
10522
        new_disk = _GenerateDiskTemplate(self,
10523
                                         instance.disk_template,
10524
                                         instance.name, instance.primary_node,
10525
                                         instance.secondary_nodes,
10526
                                         [disk_dict],
10527
                                         file_path,
10528
                                         file_driver,
10529
                                         disk_idx_base, feedback_fn)[0]
10530
        instance.disks.append(new_disk)
10531
        info = _GetInstanceInfoText(instance)
10532

    
10533
        logging.info("Creating volume %s for instance %s",
10534
                     new_disk.iv_name, instance.name)
10535
        # Note: this needs to be kept in sync with _CreateDisks
10536
        #HARDCODE
10537
        for node in instance.all_nodes:
10538
          f_create = node == instance.primary_node
10539
          try:
10540
            _CreateBlockDev(self, node, instance, new_disk,
10541
                            f_create, info, f_create)
10542
          except errors.OpExecError, err:
10543
            self.LogWarning("Failed to create volume %s (%s) on"
10544
                            " node %s: %s",
10545
                            new_disk.iv_name, new_disk, node, err)
10546
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10547
                       (new_disk.size, new_disk.mode)))
10548
      else:
10549
        # change a given disk
10550
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10551
        result.append(("disk.mode/%d" % disk_op,
10552
                       disk_dict[constants.IDISK_MODE]))
10553

    
10554
    if self.op.disk_template:
10555
      r_shut = _ShutdownInstanceDisks(self, instance)
10556
      if not r_shut:
10557
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10558
                                 " proceed with disk template conversion")
10559
      mode = (instance.disk_template, self.op.disk_template)
10560
      try:
10561
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10562
      except:
10563
        self.cfg.ReleaseDRBDMinors(instance.name)
10564
        raise
10565
      result.append(("disk_template", self.op.disk_template))
10566

    
10567
    # NIC changes
10568
    for nic_op, nic_dict in self.op.nics:
10569
      if nic_op == constants.DDM_REMOVE:
10570
        # remove the last nic
10571
        del instance.nics[-1]
10572
        result.append(("nic.%d" % len(instance.nics), "remove"))
10573
      elif nic_op == constants.DDM_ADD:
10574
        # mac and bridge should be set, by now
10575
        mac = nic_dict[constants.INIC_MAC]
10576
        ip = nic_dict.get(constants.INIC_IP, None)
10577
        nicparams = self.nic_pinst[constants.DDM_ADD]
10578
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10579
        instance.nics.append(new_nic)
10580
        result.append(("nic.%d" % (len(instance.nics) - 1),
10581
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10582
                       (new_nic.mac, new_nic.ip,
10583
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10584
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10585
                       )))
10586
      else:
10587
        for key in (constants.INIC_MAC, constants.INIC_IP):
10588
          if key in nic_dict:
10589
            setattr(instance.nics[nic_op], key, nic_dict[key])
10590
        if nic_op in self.nic_pinst:
10591
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10592
        for key, val in nic_dict.iteritems():
10593
          result.append(("nic.%s/%d" % (key, nic_op), val))
10594

    
10595
    # hvparams changes
10596
    if self.op.hvparams:
10597
      instance.hvparams = self.hv_inst
10598
      for key, val in self.op.hvparams.iteritems():
10599
        result.append(("hv/%s" % key, val))
10600

    
10601
    # beparams changes
10602
    if self.op.beparams:
10603
      instance.beparams = self.be_inst
10604
      for key, val in self.op.beparams.iteritems():
10605
        result.append(("be/%s" % key, val))
10606

    
10607
    # OS change
10608
    if self.op.os_name:
10609
      instance.os = self.op.os_name
10610

    
10611
    # osparams changes
10612
    if self.op.osparams:
10613
      instance.osparams = self.os_inst
10614
      for key, val in self.op.osparams.iteritems():
10615
        result.append(("os/%s" % key, val))
10616

    
10617
    self.cfg.Update(instance, feedback_fn)
10618

    
10619
    return result
10620

    
10621
  _DISK_CONVERSIONS = {
10622
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10623
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10624
    }
10625

    
10626

    
10627
class LUBackupQuery(NoHooksLU):
10628
  """Query the exports list
10629

10630
  """
10631
  REQ_BGL = False
10632

    
10633
  def ExpandNames(self):
10634
    self.needed_locks = {}
10635
    self.share_locks[locking.LEVEL_NODE] = 1
10636
    if not self.op.nodes:
10637
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10638
    else:
10639
      self.needed_locks[locking.LEVEL_NODE] = \
10640
        _GetWantedNodes(self, self.op.nodes)
10641

    
10642
  def Exec(self, feedback_fn):
10643
    """Compute the list of all the exported system images.
10644

10645
    @rtype: dict
10646
    @return: a dictionary with the structure node->(export-list)
10647
        where export-list is a list of the instances exported on
10648
        that node.
10649

10650
    """
10651
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10652
    rpcresult = self.rpc.call_export_list(self.nodes)
10653
    result = {}
10654
    for node in rpcresult:
10655
      if rpcresult[node].fail_msg:
10656
        result[node] = False
10657
      else:
10658
        result[node] = rpcresult[node].payload
10659

    
10660
    return result
10661

    
10662

    
10663
class LUBackupPrepare(NoHooksLU):
10664
  """Prepares an instance for an export and returns useful information.
10665

10666
  """
10667
  REQ_BGL = False
10668

    
10669
  def ExpandNames(self):
10670
    self._ExpandAndLockInstance()
10671

    
10672
  def CheckPrereq(self):
10673
    """Check prerequisites.
10674

10675
    """
10676
    instance_name = self.op.instance_name
10677

    
10678
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10679
    assert self.instance is not None, \
10680
          "Cannot retrieve locked instance %s" % self.op.instance_name
10681
    _CheckNodeOnline(self, self.instance.primary_node)
10682

    
10683
    self._cds = _GetClusterDomainSecret()
10684

    
10685
  def Exec(self, feedback_fn):
10686
    """Prepares an instance for an export.
10687

10688
    """
10689
    instance = self.instance
10690

    
10691
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10692
      salt = utils.GenerateSecret(8)
10693

    
10694
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10695
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10696
                                              constants.RIE_CERT_VALIDITY)
10697
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10698

    
10699
      (name, cert_pem) = result.payload
10700

    
10701
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10702
                                             cert_pem)
10703

    
10704
      return {
10705
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10706
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10707
                          salt),
10708
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10709
        }
10710

    
10711
    return None
10712

    
10713

    
10714
class LUBackupExport(LogicalUnit):
10715
  """Export an instance to an image in the cluster.
10716

10717
  """
10718
  HPATH = "instance-export"
10719
  HTYPE = constants.HTYPE_INSTANCE
10720
  REQ_BGL = False
10721

    
10722
  def CheckArguments(self):
10723
    """Check the arguments.
10724

10725
    """
10726
    self.x509_key_name = self.op.x509_key_name
10727
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10728

    
10729
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10730
      if not self.x509_key_name:
10731
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10732
                                   errors.ECODE_INVAL)
10733

    
10734
      if not self.dest_x509_ca_pem:
10735
        raise errors.OpPrereqError("Missing destination X509 CA",
10736
                                   errors.ECODE_INVAL)
10737

    
10738
  def ExpandNames(self):
10739
    self._ExpandAndLockInstance()
10740

    
10741
    # Lock all nodes for local exports
10742
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10743
      # FIXME: lock only instance primary and destination node
10744
      #
10745
      # Sad but true, for now we have do lock all nodes, as we don't know where
10746
      # the previous export might be, and in this LU we search for it and
10747
      # remove it from its current node. In the future we could fix this by:
10748
      #  - making a tasklet to search (share-lock all), then create the
10749
      #    new one, then one to remove, after
10750
      #  - removing the removal operation altogether
10751
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10752

    
10753
  def DeclareLocks(self, level):
10754
    """Last minute lock declaration."""
10755
    # All nodes are locked anyway, so nothing to do here.
10756

    
10757
  def BuildHooksEnv(self):
10758
    """Build hooks env.
10759

10760
    This will run on the master, primary node and target node.
10761

10762
    """
10763
    env = {
10764
      "EXPORT_MODE": self.op.mode,
10765
      "EXPORT_NODE": self.op.target_node,
10766
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10767
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10768
      # TODO: Generic function for boolean env variables
10769
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10770
      }
10771

    
10772
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10773

    
10774
    return env
10775

    
10776
  def BuildHooksNodes(self):
10777
    """Build hooks nodes.
10778

10779
    """
10780
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10781

    
10782
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10783
      nl.append(self.op.target_node)
10784

    
10785
    return (nl, nl)
10786

    
10787
  def CheckPrereq(self):
10788
    """Check prerequisites.
10789

10790
    This checks that the instance and node names are valid.
10791

10792
    """
10793
    instance_name = self.op.instance_name
10794

    
10795
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10796
    assert self.instance is not None, \
10797
          "Cannot retrieve locked instance %s" % self.op.instance_name
10798
    _CheckNodeOnline(self, self.instance.primary_node)
10799

    
10800
    if (self.op.remove_instance and self.instance.admin_up and
10801
        not self.op.shutdown):
10802
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10803
                                 " down before")
10804

    
10805
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10806
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10807
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10808
      assert self.dst_node is not None
10809

    
10810
      _CheckNodeOnline(self, self.dst_node.name)
10811
      _CheckNodeNotDrained(self, self.dst_node.name)
10812

    
10813
      self._cds = None
10814
      self.dest_disk_info = None
10815
      self.dest_x509_ca = None
10816

    
10817
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10818
      self.dst_node = None
10819

    
10820
      if len(self.op.target_node) != len(self.instance.disks):
10821
        raise errors.OpPrereqError(("Received destination information for %s"
10822
                                    " disks, but instance %s has %s disks") %
10823
                                   (len(self.op.target_node), instance_name,
10824
                                    len(self.instance.disks)),
10825
                                   errors.ECODE_INVAL)
10826

    
10827
      cds = _GetClusterDomainSecret()
10828

    
10829
      # Check X509 key name
10830
      try:
10831
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10832
      except (TypeError, ValueError), err:
10833
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10834

    
10835
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10836
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10837
                                   errors.ECODE_INVAL)
10838

    
10839
      # Load and verify CA
10840
      try:
10841
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10842
      except OpenSSL.crypto.Error, err:
10843
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10844
                                   (err, ), errors.ECODE_INVAL)
10845

    
10846
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10847
      if errcode is not None:
10848
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10849
                                   (msg, ), errors.ECODE_INVAL)
10850

    
10851
      self.dest_x509_ca = cert
10852

    
10853
      # Verify target information
10854
      disk_info = []
10855
      for idx, disk_data in enumerate(self.op.target_node):
10856
        try:
10857
          (host, port, magic) = \
10858
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10859
        except errors.GenericError, err:
10860
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10861
                                     (idx, err), errors.ECODE_INVAL)
10862

    
10863
        disk_info.append((host, port, magic))
10864

    
10865
      assert len(disk_info) == len(self.op.target_node)
10866
      self.dest_disk_info = disk_info
10867

    
10868
    else:
10869
      raise errors.ProgrammerError("Unhandled export mode %r" %
10870
                                   self.op.mode)
10871

    
10872
    # instance disk type verification
10873
    # TODO: Implement export support for file-based disks
10874
    for disk in self.instance.disks:
10875
      if disk.dev_type == constants.LD_FILE:
10876
        raise errors.OpPrereqError("Export not supported for instances with"
10877
                                   " file-based disks", errors.ECODE_INVAL)
10878

    
10879
  def _CleanupExports(self, feedback_fn):
10880
    """Removes exports of current instance from all other nodes.
10881

10882
    If an instance in a cluster with nodes A..D was exported to node C, its
10883
    exports will be removed from the nodes A, B and D.
10884

10885
    """
10886
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10887

    
10888
    nodelist = self.cfg.GetNodeList()
10889
    nodelist.remove(self.dst_node.name)
10890

    
10891
    # on one-node clusters nodelist will be empty after the removal
10892
    # if we proceed the backup would be removed because OpBackupQuery
10893
    # substitutes an empty list with the full cluster node list.
10894
    iname = self.instance.name
10895
    if nodelist:
10896
      feedback_fn("Removing old exports for instance %s" % iname)
10897
      exportlist = self.rpc.call_export_list(nodelist)
10898
      for node in exportlist:
10899
        if exportlist[node].fail_msg:
10900
          continue
10901
        if iname in exportlist[node].payload:
10902
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10903
          if msg:
10904
            self.LogWarning("Could not remove older export for instance %s"
10905
                            " on node %s: %s", iname, node, msg)
10906

    
10907
  def Exec(self, feedback_fn):
10908
    """Export an instance to an image in the cluster.
10909

10910
    """
10911
    assert self.op.mode in constants.EXPORT_MODES
10912

    
10913
    instance = self.instance
10914
    src_node = instance.primary_node
10915

    
10916
    if self.op.shutdown:
10917
      # shutdown the instance, but not the disks
10918
      feedback_fn("Shutting down instance %s" % instance.name)
10919
      result = self.rpc.call_instance_shutdown(src_node, instance,
10920
                                               self.op.shutdown_timeout)
10921
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10922
      result.Raise("Could not shutdown instance %s on"
10923
                   " node %s" % (instance.name, src_node))
10924

    
10925
    # set the disks ID correctly since call_instance_start needs the
10926
    # correct drbd minor to create the symlinks
10927
    for disk in instance.disks:
10928
      self.cfg.SetDiskID(disk, src_node)
10929

    
10930
    activate_disks = (not instance.admin_up)
10931

    
10932
    if activate_disks:
10933
      # Activate the instance disks if we'exporting a stopped instance
10934
      feedback_fn("Activating disks for %s" % instance.name)
10935
      _StartInstanceDisks(self, instance, None)
10936

    
10937
    try:
10938
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10939
                                                     instance)
10940

    
10941
      helper.CreateSnapshots()
10942
      try:
10943
        if (self.op.shutdown and instance.admin_up and
10944
            not self.op.remove_instance):
10945
          assert not activate_disks
10946
          feedback_fn("Starting instance %s" % instance.name)
10947
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10948
          msg = result.fail_msg
10949
          if msg:
10950
            feedback_fn("Failed to start instance: %s" % msg)
10951
            _ShutdownInstanceDisks(self, instance)
10952
            raise errors.OpExecError("Could not start instance: %s" % msg)
10953

    
10954
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10955
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10956
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10957
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10958
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10959

    
10960
          (key_name, _, _) = self.x509_key_name
10961

    
10962
          dest_ca_pem = \
10963
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10964
                                            self.dest_x509_ca)
10965

    
10966
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10967
                                                     key_name, dest_ca_pem,
10968
                                                     timeouts)
10969
      finally:
10970
        helper.Cleanup()
10971

    
10972
      # Check for backwards compatibility
10973
      assert len(dresults) == len(instance.disks)
10974
      assert compat.all(isinstance(i, bool) for i in dresults), \
10975
             "Not all results are boolean: %r" % dresults
10976

    
10977
    finally:
10978
      if activate_disks:
10979
        feedback_fn("Deactivating disks for %s" % instance.name)
10980
        _ShutdownInstanceDisks(self, instance)
10981

    
10982
    if not (compat.all(dresults) and fin_resu):
10983
      failures = []
10984
      if not fin_resu:
10985
        failures.append("export finalization")
10986
      if not compat.all(dresults):
10987
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10988
                               if not dsk)
10989
        failures.append("disk export: disk(s) %s" % fdsk)
10990

    
10991
      raise errors.OpExecError("Export failed, errors in %s" %
10992
                               utils.CommaJoin(failures))
10993

    
10994
    # At this point, the export was successful, we can cleanup/finish
10995

    
10996
    # Remove instance if requested
10997
    if self.op.remove_instance:
10998
      feedback_fn("Removing instance %s" % instance.name)
10999
      _RemoveInstance(self, feedback_fn, instance,
11000
                      self.op.ignore_remove_failures)
11001

    
11002
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11003
      self._CleanupExports(feedback_fn)
11004

    
11005
    return fin_resu, dresults
11006

    
11007

    
11008
class LUBackupRemove(NoHooksLU):
11009
  """Remove exports related to the named instance.
11010

11011
  """
11012
  REQ_BGL = False
11013

    
11014
  def ExpandNames(self):
11015
    self.needed_locks = {}
11016
    # We need all nodes to be locked in order for RemoveExport to work, but we
11017
    # don't need to lock the instance itself, as nothing will happen to it (and
11018
    # we can remove exports also for a removed instance)
11019
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11020

    
11021
  def Exec(self, feedback_fn):
11022
    """Remove any export.
11023

11024
    """
11025
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11026
    # If the instance was not found we'll try with the name that was passed in.
11027
    # This will only work if it was an FQDN, though.
11028
    fqdn_warn = False
11029
    if not instance_name:
11030
      fqdn_warn = True
11031
      instance_name = self.op.instance_name
11032

    
11033
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
11034
    exportlist = self.rpc.call_export_list(locked_nodes)
11035
    found = False
11036
    for node in exportlist:
11037
      msg = exportlist[node].fail_msg
11038
      if msg:
11039
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11040
        continue
11041
      if instance_name in exportlist[node].payload:
11042
        found = True
11043
        result = self.rpc.call_export_remove(node, instance_name)
11044
        msg = result.fail_msg
11045
        if msg:
11046
          logging.error("Could not remove export for instance %s"
11047
                        " on node %s: %s", instance_name, node, msg)
11048

    
11049
    if fqdn_warn and not found:
11050
      feedback_fn("Export not found. If trying to remove an export belonging"
11051
                  " to a deleted instance please use its Fully Qualified"
11052
                  " Domain Name.")
11053

    
11054

    
11055
class LUGroupAdd(LogicalUnit):
11056
  """Logical unit for creating node groups.
11057

11058
  """
11059
  HPATH = "group-add"
11060
  HTYPE = constants.HTYPE_GROUP
11061
  REQ_BGL = False
11062

    
11063
  def ExpandNames(self):
11064
    # We need the new group's UUID here so that we can create and acquire the
11065
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11066
    # that it should not check whether the UUID exists in the configuration.
11067
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11068
    self.needed_locks = {}
11069
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11070

    
11071
  def CheckPrereq(self):
11072
    """Check prerequisites.
11073

11074
    This checks that the given group name is not an existing node group
11075
    already.
11076

11077
    """
11078
    try:
11079
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11080
    except errors.OpPrereqError:
11081
      pass
11082
    else:
11083
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11084
                                 " node group (UUID: %s)" %
11085
                                 (self.op.group_name, existing_uuid),
11086
                                 errors.ECODE_EXISTS)
11087

    
11088
    if self.op.ndparams:
11089
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11090

    
11091
  def BuildHooksEnv(self):
11092
    """Build hooks env.
11093

11094
    """
11095
    return {
11096
      "GROUP_NAME": self.op.group_name,
11097
      }
11098

    
11099
  def BuildHooksNodes(self):
11100
    """Build hooks nodes.
11101

11102
    """
11103
    mn = self.cfg.GetMasterNode()
11104
    return ([mn], [mn])
11105

    
11106
  def Exec(self, feedback_fn):
11107
    """Add the node group to the cluster.
11108

11109
    """
11110
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11111
                                  uuid=self.group_uuid,
11112
                                  alloc_policy=self.op.alloc_policy,
11113
                                  ndparams=self.op.ndparams)
11114

    
11115
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11116
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11117

    
11118

    
11119
class LUGroupAssignNodes(NoHooksLU):
11120
  """Logical unit for assigning nodes to groups.
11121

11122
  """
11123
  REQ_BGL = False
11124

    
11125
  def ExpandNames(self):
11126
    # These raise errors.OpPrereqError on their own:
11127
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11128
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11129

    
11130
    # We want to lock all the affected nodes and groups. We have readily
11131
    # available the list of nodes, and the *destination* group. To gather the
11132
    # list of "source" groups, we need to fetch node information later on.
11133
    self.needed_locks = {
11134
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11135
      locking.LEVEL_NODE: self.op.nodes,
11136
      }
11137

    
11138
  def DeclareLocks(self, level):
11139
    if level == locking.LEVEL_NODEGROUP:
11140
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11141

    
11142
      # Try to get all affected nodes' groups without having the group or node
11143
      # lock yet. Needs verification later in the code flow.
11144
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11145

    
11146
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11147

    
11148
  def CheckPrereq(self):
11149
    """Check prerequisites.
11150

11151
    """
11152
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11153
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11154
            frozenset(self.op.nodes))
11155

    
11156
    expected_locks = (set([self.group_uuid]) |
11157
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11158
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11159
    if actual_locks != expected_locks:
11160
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11161
                               " current groups are '%s', used to be '%s'" %
11162
                               (utils.CommaJoin(expected_locks),
11163
                                utils.CommaJoin(actual_locks)))
11164

    
11165
    self.node_data = self.cfg.GetAllNodesInfo()
11166
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11167
    instance_data = self.cfg.GetAllInstancesInfo()
11168

    
11169
    if self.group is None:
11170
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11171
                               (self.op.group_name, self.group_uuid))
11172

    
11173
    (new_splits, previous_splits) = \
11174
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11175
                                             for node in self.op.nodes],
11176
                                            self.node_data, instance_data)
11177

    
11178
    if new_splits:
11179
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11180

    
11181
      if not self.op.force:
11182
        raise errors.OpExecError("The following instances get split by this"
11183
                                 " change and --force was not given: %s" %
11184
                                 fmt_new_splits)
11185
      else:
11186
        self.LogWarning("This operation will split the following instances: %s",
11187
                        fmt_new_splits)
11188

    
11189
        if previous_splits:
11190
          self.LogWarning("In addition, these already-split instances continue"
11191
                          " to be split across groups: %s",
11192
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11193

    
11194
  def Exec(self, feedback_fn):
11195
    """Assign nodes to a new group.
11196

11197
    """
11198
    for node in self.op.nodes:
11199
      self.node_data[node].group = self.group_uuid
11200

    
11201
    # FIXME: Depends on side-effects of modifying the result of
11202
    # C{cfg.GetAllNodesInfo}
11203

    
11204
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11205

    
11206
  @staticmethod
11207
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11208
    """Check for split instances after a node assignment.
11209

11210
    This method considers a series of node assignments as an atomic operation,
11211
    and returns information about split instances after applying the set of
11212
    changes.
11213

11214
    In particular, it returns information about newly split instances, and
11215
    instances that were already split, and remain so after the change.
11216

11217
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11218
    considered.
11219

11220
    @type changes: list of (node_name, new_group_uuid) pairs.
11221
    @param changes: list of node assignments to consider.
11222
    @param node_data: a dict with data for all nodes
11223
    @param instance_data: a dict with all instances to consider
11224
    @rtype: a two-tuple
11225
    @return: a list of instances that were previously okay and result split as a
11226
      consequence of this change, and a list of instances that were previously
11227
      split and this change does not fix.
11228

11229
    """
11230
    changed_nodes = dict((node, group) for node, group in changes
11231
                         if node_data[node].group != group)
11232

    
11233
    all_split_instances = set()
11234
    previously_split_instances = set()
11235

    
11236
    def InstanceNodes(instance):
11237
      return [instance.primary_node] + list(instance.secondary_nodes)
11238

    
11239
    for inst in instance_data.values():
11240
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11241
        continue
11242

    
11243
      instance_nodes = InstanceNodes(inst)
11244

    
11245
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11246
        previously_split_instances.add(inst.name)
11247

    
11248
      if len(set(changed_nodes.get(node, node_data[node].group)
11249
                 for node in instance_nodes)) > 1:
11250
        all_split_instances.add(inst.name)
11251

    
11252
    return (list(all_split_instances - previously_split_instances),
11253
            list(previously_split_instances & all_split_instances))
11254

    
11255

    
11256
class _GroupQuery(_QueryBase):
11257
  FIELDS = query.GROUP_FIELDS
11258

    
11259
  def ExpandNames(self, lu):
11260
    lu.needed_locks = {}
11261

    
11262
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11263
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11264

    
11265
    if not self.names:
11266
      self.wanted = [name_to_uuid[name]
11267
                     for name in utils.NiceSort(name_to_uuid.keys())]
11268
    else:
11269
      # Accept names to be either names or UUIDs.
11270
      missing = []
11271
      self.wanted = []
11272
      all_uuid = frozenset(self._all_groups.keys())
11273

    
11274
      for name in self.names:
11275
        if name in all_uuid:
11276
          self.wanted.append(name)
11277
        elif name in name_to_uuid:
11278
          self.wanted.append(name_to_uuid[name])
11279
        else:
11280
          missing.append(name)
11281

    
11282
      if missing:
11283
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11284
                                   utils.CommaJoin(missing),
11285
                                   errors.ECODE_NOENT)
11286

    
11287
  def DeclareLocks(self, lu, level):
11288
    pass
11289

    
11290
  def _GetQueryData(self, lu):
11291
    """Computes the list of node groups and their attributes.
11292

11293
    """
11294
    do_nodes = query.GQ_NODE in self.requested_data
11295
    do_instances = query.GQ_INST in self.requested_data
11296

    
11297
    group_to_nodes = None
11298
    group_to_instances = None
11299

    
11300
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11301
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11302
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11303
    # instance->node. Hence, we will need to process nodes even if we only need
11304
    # instance information.
11305
    if do_nodes or do_instances:
11306
      all_nodes = lu.cfg.GetAllNodesInfo()
11307
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11308
      node_to_group = {}
11309

    
11310
      for node in all_nodes.values():
11311
        if node.group in group_to_nodes:
11312
          group_to_nodes[node.group].append(node.name)
11313
          node_to_group[node.name] = node.group
11314

    
11315
      if do_instances:
11316
        all_instances = lu.cfg.GetAllInstancesInfo()
11317
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11318

    
11319
        for instance in all_instances.values():
11320
          node = instance.primary_node
11321
          if node in node_to_group:
11322
            group_to_instances[node_to_group[node]].append(instance.name)
11323

    
11324
        if not do_nodes:
11325
          # Do not pass on node information if it was not requested.
11326
          group_to_nodes = None
11327

    
11328
    return query.GroupQueryData([self._all_groups[uuid]
11329
                                 for uuid in self.wanted],
11330
                                group_to_nodes, group_to_instances)
11331

    
11332

    
11333
class LUGroupQuery(NoHooksLU):
11334
  """Logical unit for querying node groups.
11335

11336
  """
11337
  REQ_BGL = False
11338

    
11339
  def CheckArguments(self):
11340
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11341
                          self.op.output_fields, False)
11342

    
11343
  def ExpandNames(self):
11344
    self.gq.ExpandNames(self)
11345

    
11346
  def Exec(self, feedback_fn):
11347
    return self.gq.OldStyleQuery(self)
11348

    
11349

    
11350
class LUGroupSetParams(LogicalUnit):
11351
  """Modifies the parameters of a node group.
11352

11353
  """
11354
  HPATH = "group-modify"
11355
  HTYPE = constants.HTYPE_GROUP
11356
  REQ_BGL = False
11357

    
11358
  def CheckArguments(self):
11359
    all_changes = [
11360
      self.op.ndparams,
11361
      self.op.alloc_policy,
11362
      ]
11363

    
11364
    if all_changes.count(None) == len(all_changes):
11365
      raise errors.OpPrereqError("Please pass at least one modification",
11366
                                 errors.ECODE_INVAL)
11367

    
11368
  def ExpandNames(self):
11369
    # This raises errors.OpPrereqError on its own:
11370
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11371

    
11372
    self.needed_locks = {
11373
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11374
      }
11375

    
11376
  def CheckPrereq(self):
11377
    """Check prerequisites.
11378

11379
    """
11380
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11381

    
11382
    if self.group is None:
11383
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11384
                               (self.op.group_name, self.group_uuid))
11385

    
11386
    if self.op.ndparams:
11387
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11388
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11389
      self.new_ndparams = new_ndparams
11390

    
11391
  def BuildHooksEnv(self):
11392
    """Build hooks env.
11393

11394
    """
11395
    return {
11396
      "GROUP_NAME": self.op.group_name,
11397
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11398
      }
11399

    
11400
  def BuildHooksNodes(self):
11401
    """Build hooks nodes.
11402

11403
    """
11404
    mn = self.cfg.GetMasterNode()
11405
    return ([mn], [mn])
11406

    
11407
  def Exec(self, feedback_fn):
11408
    """Modifies the node group.
11409

11410
    """
11411
    result = []
11412

    
11413
    if self.op.ndparams:
11414
      self.group.ndparams = self.new_ndparams
11415
      result.append(("ndparams", str(self.group.ndparams)))
11416

    
11417
    if self.op.alloc_policy:
11418
      self.group.alloc_policy = self.op.alloc_policy
11419

    
11420
    self.cfg.Update(self.group, feedback_fn)
11421
    return result
11422

    
11423

    
11424

    
11425
class LUGroupRemove(LogicalUnit):
11426
  HPATH = "group-remove"
11427
  HTYPE = constants.HTYPE_GROUP
11428
  REQ_BGL = False
11429

    
11430
  def ExpandNames(self):
11431
    # This will raises errors.OpPrereqError on its own:
11432
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11433
    self.needed_locks = {
11434
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11435
      }
11436

    
11437
  def CheckPrereq(self):
11438
    """Check prerequisites.
11439

11440
    This checks that the given group name exists as a node group, that is
11441
    empty (i.e., contains no nodes), and that is not the last group of the
11442
    cluster.
11443

11444
    """
11445
    # Verify that the group is empty.
11446
    group_nodes = [node.name
11447
                   for node in self.cfg.GetAllNodesInfo().values()
11448
                   if node.group == self.group_uuid]
11449

    
11450
    if group_nodes:
11451
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11452
                                 " nodes: %s" %
11453
                                 (self.op.group_name,
11454
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11455
                                 errors.ECODE_STATE)
11456

    
11457
    # Verify the cluster would not be left group-less.
11458
    if len(self.cfg.GetNodeGroupList()) == 1:
11459
      raise errors.OpPrereqError("Group '%s' is the only group,"
11460
                                 " cannot be removed" %
11461
                                 self.op.group_name,
11462
                                 errors.ECODE_STATE)
11463

    
11464
  def BuildHooksEnv(self):
11465
    """Build hooks env.
11466

11467
    """
11468
    return {
11469
      "GROUP_NAME": self.op.group_name,
11470
      }
11471

    
11472
  def BuildHooksNodes(self):
11473
    """Build hooks nodes.
11474

11475
    """
11476
    mn = self.cfg.GetMasterNode()
11477
    return ([mn], [mn])
11478

    
11479
  def Exec(self, feedback_fn):
11480
    """Remove the node group.
11481

11482
    """
11483
    try:
11484
      self.cfg.RemoveNodeGroup(self.group_uuid)
11485
    except errors.ConfigurationError:
11486
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11487
                               (self.op.group_name, self.group_uuid))
11488

    
11489
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11490

    
11491

    
11492
class LUGroupRename(LogicalUnit):
11493
  HPATH = "group-rename"
11494
  HTYPE = constants.HTYPE_GROUP
11495
  REQ_BGL = False
11496

    
11497
  def ExpandNames(self):
11498
    # This raises errors.OpPrereqError on its own:
11499
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11500

    
11501
    self.needed_locks = {
11502
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11503
      }
11504

    
11505
  def CheckPrereq(self):
11506
    """Check prerequisites.
11507

11508
    Ensures requested new name is not yet used.
11509

11510
    """
11511
    try:
11512
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11513
    except errors.OpPrereqError:
11514
      pass
11515
    else:
11516
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11517
                                 " node group (UUID: %s)" %
11518
                                 (self.op.new_name, new_name_uuid),
11519
                                 errors.ECODE_EXISTS)
11520

    
11521
  def BuildHooksEnv(self):
11522
    """Build hooks env.
11523

11524
    """
11525
    return {
11526
      "OLD_NAME": self.op.group_name,
11527
      "NEW_NAME": self.op.new_name,
11528
      }
11529

    
11530
  def BuildHooksNodes(self):
11531
    """Build hooks nodes.
11532

11533
    """
11534
    mn = self.cfg.GetMasterNode()
11535

    
11536
    all_nodes = self.cfg.GetAllNodesInfo()
11537
    all_nodes.pop(mn, None)
11538

    
11539
    run_nodes = [mn]
11540
    run_nodes.extend(node.name for node in all_nodes.values()
11541
                     if node.group == self.group_uuid)
11542

    
11543
    return (run_nodes, run_nodes)
11544

    
11545
  def Exec(self, feedback_fn):
11546
    """Rename the node group.
11547

11548
    """
11549
    group = self.cfg.GetNodeGroup(self.group_uuid)
11550

    
11551
    if group is None:
11552
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11553
                               (self.op.group_name, self.group_uuid))
11554

    
11555
    group.name = self.op.new_name
11556
    self.cfg.Update(group, feedback_fn)
11557

    
11558
    return self.op.new_name
11559

    
11560

    
11561
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11562
  """Generic tags LU.
11563

11564
  This is an abstract class which is the parent of all the other tags LUs.
11565

11566
  """
11567
  def ExpandNames(self):
11568
    self.group_uuid = None
11569
    self.needed_locks = {}
11570
    if self.op.kind == constants.TAG_NODE:
11571
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11572
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11573
    elif self.op.kind == constants.TAG_INSTANCE:
11574
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11575
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11576
    elif self.op.kind == constants.TAG_NODEGROUP:
11577
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
11578

    
11579
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11580
    # not possible to acquire the BGL based on opcode parameters)
11581

    
11582
  def CheckPrereq(self):
11583
    """Check prerequisites.
11584

11585
    """
11586
    if self.op.kind == constants.TAG_CLUSTER:
11587
      self.target = self.cfg.GetClusterInfo()
11588
    elif self.op.kind == constants.TAG_NODE:
11589
      self.target = self.cfg.GetNodeInfo(self.op.name)
11590
    elif self.op.kind == constants.TAG_INSTANCE:
11591
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11592
    elif self.op.kind == constants.TAG_NODEGROUP:
11593
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
11594
    else:
11595
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11596
                                 str(self.op.kind), errors.ECODE_INVAL)
11597

    
11598

    
11599
class LUTagsGet(TagsLU):
11600
  """Returns the tags of a given object.
11601

11602
  """
11603
  REQ_BGL = False
11604

    
11605
  def ExpandNames(self):
11606
    TagsLU.ExpandNames(self)
11607

    
11608
    # Share locks as this is only a read operation
11609
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11610

    
11611
  def Exec(self, feedback_fn):
11612
    """Returns the tag list.
11613

11614
    """
11615
    return list(self.target.GetTags())
11616

    
11617

    
11618
class LUTagsSearch(NoHooksLU):
11619
  """Searches the tags for a given pattern.
11620

11621
  """
11622
  REQ_BGL = False
11623

    
11624
  def ExpandNames(self):
11625
    self.needed_locks = {}
11626

    
11627
  def CheckPrereq(self):
11628
    """Check prerequisites.
11629

11630
    This checks the pattern passed for validity by compiling it.
11631

11632
    """
11633
    try:
11634
      self.re = re.compile(self.op.pattern)
11635
    except re.error, err:
11636
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11637
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11638

    
11639
  def Exec(self, feedback_fn):
11640
    """Returns the tag list.
11641

11642
    """
11643
    cfg = self.cfg
11644
    tgts = [("/cluster", cfg.GetClusterInfo())]
11645
    ilist = cfg.GetAllInstancesInfo().values()
11646
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11647
    nlist = cfg.GetAllNodesInfo().values()
11648
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11649
    tgts.extend(("/nodegroup/%s" % n.name, n)
11650
                for n in cfg.GetAllNodeGroupsInfo().values())
11651
    results = []
11652
    for path, target in tgts:
11653
      for tag in target.GetTags():
11654
        if self.re.search(tag):
11655
          results.append((path, tag))
11656
    return results
11657

    
11658

    
11659
class LUTagsSet(TagsLU):
11660
  """Sets a tag on a given object.
11661

11662
  """
11663
  REQ_BGL = False
11664

    
11665
  def CheckPrereq(self):
11666
    """Check prerequisites.
11667

11668
    This checks the type and length of the tag name and value.
11669

11670
    """
11671
    TagsLU.CheckPrereq(self)
11672
    for tag in self.op.tags:
11673
      objects.TaggableObject.ValidateTag(tag)
11674

    
11675
  def Exec(self, feedback_fn):
11676
    """Sets the tag.
11677

11678
    """
11679
    try:
11680
      for tag in self.op.tags:
11681
        self.target.AddTag(tag)
11682
    except errors.TagError, err:
11683
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11684
    self.cfg.Update(self.target, feedback_fn)
11685

    
11686

    
11687
class LUTagsDel(TagsLU):
11688
  """Delete a list of tags from a given object.
11689

11690
  """
11691
  REQ_BGL = False
11692

    
11693
  def CheckPrereq(self):
11694
    """Check prerequisites.
11695

11696
    This checks that we have the given tag.
11697

11698
    """
11699
    TagsLU.CheckPrereq(self)
11700
    for tag in self.op.tags:
11701
      objects.TaggableObject.ValidateTag(tag)
11702
    del_tags = frozenset(self.op.tags)
11703
    cur_tags = self.target.GetTags()
11704

    
11705
    diff_tags = del_tags - cur_tags
11706
    if diff_tags:
11707
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11708
      raise errors.OpPrereqError("Tag(s) %s not found" %
11709
                                 (utils.CommaJoin(diff_names), ),
11710
                                 errors.ECODE_NOENT)
11711

    
11712
  def Exec(self, feedback_fn):
11713
    """Remove the tag from the object.
11714

11715
    """
11716
    for tag in self.op.tags:
11717
      self.target.RemoveTag(tag)
11718
    self.cfg.Update(self.target, feedback_fn)
11719

    
11720

    
11721
class LUTestDelay(NoHooksLU):
11722
  """Sleep for a specified amount of time.
11723

11724
  This LU sleeps on the master and/or nodes for a specified amount of
11725
  time.
11726

11727
  """
11728
  REQ_BGL = False
11729

    
11730
  def ExpandNames(self):
11731
    """Expand names and set required locks.
11732

11733
    This expands the node list, if any.
11734

11735
    """
11736
    self.needed_locks = {}
11737
    if self.op.on_nodes:
11738
      # _GetWantedNodes can be used here, but is not always appropriate to use
11739
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11740
      # more information.
11741
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11742
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11743

    
11744
  def _TestDelay(self):
11745
    """Do the actual sleep.
11746

11747
    """
11748
    if self.op.on_master:
11749
      if not utils.TestDelay(self.op.duration):
11750
        raise errors.OpExecError("Error during master delay test")
11751
    if self.op.on_nodes:
11752
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11753
      for node, node_result in result.items():
11754
        node_result.Raise("Failure during rpc call to node %s" % node)
11755

    
11756
  def Exec(self, feedback_fn):
11757
    """Execute the test delay opcode, with the wanted repetitions.
11758

11759
    """
11760
    if self.op.repeat == 0:
11761
      self._TestDelay()
11762
    else:
11763
      top_value = self.op.repeat - 1
11764
      for i in range(self.op.repeat):
11765
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11766
        self._TestDelay()
11767

    
11768

    
11769
class LUTestJqueue(NoHooksLU):
11770
  """Utility LU to test some aspects of the job queue.
11771

11772
  """
11773
  REQ_BGL = False
11774

    
11775
  # Must be lower than default timeout for WaitForJobChange to see whether it
11776
  # notices changed jobs
11777
  _CLIENT_CONNECT_TIMEOUT = 20.0
11778
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11779

    
11780
  @classmethod
11781
  def _NotifyUsingSocket(cls, cb, errcls):
11782
    """Opens a Unix socket and waits for another program to connect.
11783

11784
    @type cb: callable
11785
    @param cb: Callback to send socket name to client
11786
    @type errcls: class
11787
    @param errcls: Exception class to use for errors
11788

11789
    """
11790
    # Using a temporary directory as there's no easy way to create temporary
11791
    # sockets without writing a custom loop around tempfile.mktemp and
11792
    # socket.bind
11793
    tmpdir = tempfile.mkdtemp()
11794
    try:
11795
      tmpsock = utils.PathJoin(tmpdir, "sock")
11796

    
11797
      logging.debug("Creating temporary socket at %s", tmpsock)
11798
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11799
      try:
11800
        sock.bind(tmpsock)
11801
        sock.listen(1)
11802

    
11803
        # Send details to client
11804
        cb(tmpsock)
11805

    
11806
        # Wait for client to connect before continuing
11807
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11808
        try:
11809
          (conn, _) = sock.accept()
11810
        except socket.error, err:
11811
          raise errcls("Client didn't connect in time (%s)" % err)
11812
      finally:
11813
        sock.close()
11814
    finally:
11815
      # Remove as soon as client is connected
11816
      shutil.rmtree(tmpdir)
11817

    
11818
    # Wait for client to close
11819
    try:
11820
      try:
11821
        # pylint: disable-msg=E1101
11822
        # Instance of '_socketobject' has no ... member
11823
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11824
        conn.recv(1)
11825
      except socket.error, err:
11826
        raise errcls("Client failed to confirm notification (%s)" % err)
11827
    finally:
11828
      conn.close()
11829

    
11830
  def _SendNotification(self, test, arg, sockname):
11831
    """Sends a notification to the client.
11832

11833
    @type test: string
11834
    @param test: Test name
11835
    @param arg: Test argument (depends on test)
11836
    @type sockname: string
11837
    @param sockname: Socket path
11838

11839
    """
11840
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11841

    
11842
  def _Notify(self, prereq, test, arg):
11843
    """Notifies the client of a test.
11844

11845
    @type prereq: bool
11846
    @param prereq: Whether this is a prereq-phase test
11847
    @type test: string
11848
    @param test: Test name
11849
    @param arg: Test argument (depends on test)
11850

11851
    """
11852
    if prereq:
11853
      errcls = errors.OpPrereqError
11854
    else:
11855
      errcls = errors.OpExecError
11856

    
11857
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11858
                                                  test, arg),
11859
                                   errcls)
11860

    
11861
  def CheckArguments(self):
11862
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11863
    self.expandnames_calls = 0
11864

    
11865
  def ExpandNames(self):
11866
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11867
    if checkargs_calls < 1:
11868
      raise errors.ProgrammerError("CheckArguments was not called")
11869

    
11870
    self.expandnames_calls += 1
11871

    
11872
    if self.op.notify_waitlock:
11873
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11874

    
11875
    self.LogInfo("Expanding names")
11876

    
11877
    # Get lock on master node (just to get a lock, not for a particular reason)
11878
    self.needed_locks = {
11879
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11880
      }
11881

    
11882
  def Exec(self, feedback_fn):
11883
    if self.expandnames_calls < 1:
11884
      raise errors.ProgrammerError("ExpandNames was not called")
11885

    
11886
    if self.op.notify_exec:
11887
      self._Notify(False, constants.JQT_EXEC, None)
11888

    
11889
    self.LogInfo("Executing")
11890

    
11891
    if self.op.log_messages:
11892
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11893
      for idx, msg in enumerate(self.op.log_messages):
11894
        self.LogInfo("Sending log message %s", idx + 1)
11895
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11896
        # Report how many test messages have been sent
11897
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11898

    
11899
    if self.op.fail:
11900
      raise errors.OpExecError("Opcode failure was requested")
11901

    
11902
    return True
11903

    
11904

    
11905
class IAllocator(object):
11906
  """IAllocator framework.
11907

11908
  An IAllocator instance has three sets of attributes:
11909
    - cfg that is needed to query the cluster
11910
    - input data (all members of the _KEYS class attribute are required)
11911
    - four buffer attributes (in|out_data|text), that represent the
11912
      input (to the external script) in text and data structure format,
11913
      and the output from it, again in two formats
11914
    - the result variables from the script (success, info, nodes) for
11915
      easy usage
11916

11917
  """
11918
  # pylint: disable-msg=R0902
11919
  # lots of instance attributes
11920

    
11921
  def __init__(self, cfg, rpc, mode, **kwargs):
11922
    self.cfg = cfg
11923
    self.rpc = rpc
11924
    # init buffer variables
11925
    self.in_text = self.out_text = self.in_data = self.out_data = None
11926
    # init all input fields so that pylint is happy
11927
    self.mode = mode
11928
    self.mem_size = self.disks = self.disk_template = None
11929
    self.os = self.tags = self.nics = self.vcpus = None
11930
    self.hypervisor = None
11931
    self.relocate_from = None
11932
    self.name = None
11933
    self.evac_nodes = None
11934
    self.instances = None
11935
    self.reloc_mode = None
11936
    self.target_groups = None
11937
    # computed fields
11938
    self.required_nodes = None
11939
    # init result fields
11940
    self.success = self.info = self.result = None
11941

    
11942
    try:
11943
      (fn, keyset, self._result_check) = self._MODE_DATA[self.mode]
11944
    except KeyError:
11945
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11946
                                   " IAllocator" % self.mode)
11947

    
11948
    for key in kwargs:
11949
      if key not in keyset:
11950
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11951
                                     " IAllocator" % key)
11952
      setattr(self, key, kwargs[key])
11953

    
11954
    for key in keyset:
11955
      if key not in kwargs:
11956
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11957
                                     " IAllocator" % key)
11958
    self._BuildInputData(compat.partial(fn, self))
11959

    
11960
  def _ComputeClusterData(self):
11961
    """Compute the generic allocator input data.
11962

11963
    This is the data that is independent of the actual operation.
11964

11965
    """
11966
    cfg = self.cfg
11967
    cluster_info = cfg.GetClusterInfo()
11968
    # cluster data
11969
    data = {
11970
      "version": constants.IALLOCATOR_VERSION,
11971
      "cluster_name": cfg.GetClusterName(),
11972
      "cluster_tags": list(cluster_info.GetTags()),
11973
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11974
      # we don't have job IDs
11975
      }
11976
    ninfo = cfg.GetAllNodesInfo()
11977
    iinfo = cfg.GetAllInstancesInfo().values()
11978
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11979

    
11980
    # node data
11981
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11982

    
11983
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11984
      hypervisor_name = self.hypervisor
11985
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11986
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11987
    elif self.mode in (constants.IALLOCATOR_MODE_MEVAC,
11988
                       constants.IALLOCATOR_MODE_MRELOC):
11989
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11990

    
11991
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11992
                                        hypervisor_name)
11993
    node_iinfo = \
11994
      self.rpc.call_all_instances_info(node_list,
11995
                                       cluster_info.enabled_hypervisors)
11996

    
11997
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11998

    
11999
    config_ndata = self._ComputeBasicNodeData(ninfo)
12000
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12001
                                                 i_list, config_ndata)
12002
    assert len(data["nodes"]) == len(ninfo), \
12003
        "Incomplete node data computed"
12004

    
12005
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12006

    
12007
    self.in_data = data
12008

    
12009
  @staticmethod
12010
  def _ComputeNodeGroupData(cfg):
12011
    """Compute node groups data.
12012

12013
    """
12014
    ng = dict((guuid, {
12015
      "name": gdata.name,
12016
      "alloc_policy": gdata.alloc_policy,
12017
      })
12018
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12019

    
12020
    return ng
12021

    
12022
  @staticmethod
12023
  def _ComputeBasicNodeData(node_cfg):
12024
    """Compute global node data.
12025

12026
    @rtype: dict
12027
    @returns: a dict of name: (node dict, node config)
12028

12029
    """
12030
    # fill in static (config-based) values
12031
    node_results = dict((ninfo.name, {
12032
      "tags": list(ninfo.GetTags()),
12033
      "primary_ip": ninfo.primary_ip,
12034
      "secondary_ip": ninfo.secondary_ip,
12035
      "offline": ninfo.offline,
12036
      "drained": ninfo.drained,
12037
      "master_candidate": ninfo.master_candidate,
12038
      "group": ninfo.group,
12039
      "master_capable": ninfo.master_capable,
12040
      "vm_capable": ninfo.vm_capable,
12041
      })
12042
      for ninfo in node_cfg.values())
12043

    
12044
    return node_results
12045

    
12046
  @staticmethod
12047
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
12048
                              node_results):
12049
    """Compute global node data.
12050

12051
    @param node_results: the basic node structures as filled from the config
12052

12053
    """
12054
    # make a copy of the current dict
12055
    node_results = dict(node_results)
12056
    for nname, nresult in node_data.items():
12057
      assert nname in node_results, "Missing basic data for node %s" % nname
12058
      ninfo = node_cfg[nname]
12059

    
12060
      if not (ninfo.offline or ninfo.drained):
12061
        nresult.Raise("Can't get data for node %s" % nname)
12062
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
12063
                                nname)
12064
        remote_info = nresult.payload
12065

    
12066
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
12067
                     'vg_size', 'vg_free', 'cpu_total']:
12068
          if attr not in remote_info:
12069
            raise errors.OpExecError("Node '%s' didn't return attribute"
12070
                                     " '%s'" % (nname, attr))
12071
          if not isinstance(remote_info[attr], int):
12072
            raise errors.OpExecError("Node '%s' returned invalid value"
12073
                                     " for '%s': %s" %
12074
                                     (nname, attr, remote_info[attr]))
12075
        # compute memory used by primary instances
12076
        i_p_mem = i_p_up_mem = 0
12077
        for iinfo, beinfo in i_list:
12078
          if iinfo.primary_node == nname:
12079
            i_p_mem += beinfo[constants.BE_MEMORY]
12080
            if iinfo.name not in node_iinfo[nname].payload:
12081
              i_used_mem = 0
12082
            else:
12083
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
12084
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
12085
            remote_info['memory_free'] -= max(0, i_mem_diff)
12086

    
12087
            if iinfo.admin_up:
12088
              i_p_up_mem += beinfo[constants.BE_MEMORY]
12089

    
12090
        # compute memory used by instances
12091
        pnr_dyn = {
12092
          "total_memory": remote_info['memory_total'],
12093
          "reserved_memory": remote_info['memory_dom0'],
12094
          "free_memory": remote_info['memory_free'],
12095
          "total_disk": remote_info['vg_size'],
12096
          "free_disk": remote_info['vg_free'],
12097
          "total_cpus": remote_info['cpu_total'],
12098
          "i_pri_memory": i_p_mem,
12099
          "i_pri_up_memory": i_p_up_mem,
12100
          }
12101
        pnr_dyn.update(node_results[nname])
12102
        node_results[nname] = pnr_dyn
12103

    
12104
    return node_results
12105

    
12106
  @staticmethod
12107
  def _ComputeInstanceData(cluster_info, i_list):
12108
    """Compute global instance data.
12109

12110
    """
12111
    instance_data = {}
12112
    for iinfo, beinfo in i_list:
12113
      nic_data = []
12114
      for nic in iinfo.nics:
12115
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
12116
        nic_dict = {
12117
          "mac": nic.mac,
12118
          "ip": nic.ip,
12119
          "mode": filled_params[constants.NIC_MODE],
12120
          "link": filled_params[constants.NIC_LINK],
12121
          }
12122
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
12123
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
12124
        nic_data.append(nic_dict)
12125
      pir = {
12126
        "tags": list(iinfo.GetTags()),
12127
        "admin_up": iinfo.admin_up,
12128
        "vcpus": beinfo[constants.BE_VCPUS],
12129
        "memory": beinfo[constants.BE_MEMORY],
12130
        "os": iinfo.os,
12131
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12132
        "nics": nic_data,
12133
        "disks": [{constants.IDISK_SIZE: dsk.size,
12134
                   constants.IDISK_MODE: dsk.mode}
12135
                  for dsk in iinfo.disks],
12136
        "disk_template": iinfo.disk_template,
12137
        "hypervisor": iinfo.hypervisor,
12138
        }
12139
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12140
                                                 pir["disks"])
12141
      instance_data[iinfo.name] = pir
12142

    
12143
    return instance_data
12144

    
12145
  def _AddNewInstance(self):
12146
    """Add new instance data to allocator structure.
12147

12148
    This in combination with _AllocatorGetClusterData will create the
12149
    correct structure needed as input for the allocator.
12150

12151
    The checks for the completeness of the opcode must have already been
12152
    done.
12153

12154
    """
12155
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12156

    
12157
    if self.disk_template in constants.DTS_INT_MIRROR:
12158
      self.required_nodes = 2
12159
    else:
12160
      self.required_nodes = 1
12161

    
12162
    request = {
12163
      "name": self.name,
12164
      "disk_template": self.disk_template,
12165
      "tags": self.tags,
12166
      "os": self.os,
12167
      "vcpus": self.vcpus,
12168
      "memory": self.mem_size,
12169
      "disks": self.disks,
12170
      "disk_space_total": disk_space,
12171
      "nics": self.nics,
12172
      "required_nodes": self.required_nodes,
12173
      }
12174

    
12175
    return request
12176

    
12177
  def _AddRelocateInstance(self):
12178
    """Add relocate instance data to allocator structure.
12179

12180
    This in combination with _IAllocatorGetClusterData will create the
12181
    correct structure needed as input for the allocator.
12182

12183
    The checks for the completeness of the opcode must have already been
12184
    done.
12185

12186
    """
12187
    instance = self.cfg.GetInstanceInfo(self.name)
12188
    if instance is None:
12189
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12190
                                   " IAllocator" % self.name)
12191

    
12192
    if instance.disk_template not in constants.DTS_MIRRORED:
12193
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12194
                                 errors.ECODE_INVAL)
12195

    
12196
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12197
        len(instance.secondary_nodes) != 1:
12198
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12199
                                 errors.ECODE_STATE)
12200

    
12201
    self.required_nodes = 1
12202
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12203
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12204

    
12205
    request = {
12206
      "name": self.name,
12207
      "disk_space_total": disk_space,
12208
      "required_nodes": self.required_nodes,
12209
      "relocate_from": self.relocate_from,
12210
      }
12211
    return request
12212

    
12213
  def _AddEvacuateNodes(self):
12214
    """Add evacuate nodes data to allocator structure.
12215

12216
    """
12217
    request = {
12218
      "evac_nodes": self.evac_nodes
12219
      }
12220
    return request
12221

    
12222
  def _AddMultiRelocate(self):
12223
    """Get data for multi-relocate requests.
12224

12225
    """
12226
    return {
12227
      "instances": self.instances,
12228
      "reloc_mode": self.reloc_mode,
12229
      "target_groups": self.target_groups,
12230
      }
12231

    
12232
  def _BuildInputData(self, fn):
12233
    """Build input data structures.
12234

12235
    """
12236
    self._ComputeClusterData()
12237

    
12238
    request = fn()
12239
    request["type"] = self.mode
12240
    self.in_data["request"] = request
12241

    
12242
    self.in_text = serializer.Dump(self.in_data)
12243

    
12244
  _MODE_DATA = {
12245
    constants.IALLOCATOR_MODE_ALLOC:
12246
      (_AddNewInstance,
12247
       ["name", "mem_size", "disks", "disk_template", "os", "tags", "nics",
12248
        "vcpus", "hypervisor"], ht.TList),
12249
    constants.IALLOCATOR_MODE_RELOC:
12250
      (_AddRelocateInstance, ["name", "relocate_from"], ht.TList),
12251
    constants.IALLOCATOR_MODE_MEVAC:
12252
      (_AddEvacuateNodes, ["evac_nodes"],
12253
       ht.TListOf(ht.TAnd(ht.TIsLength(2),
12254
                          ht.TListOf(ht.TString)))),
12255
    constants.IALLOCATOR_MODE_MRELOC:
12256
      (_AddMultiRelocate, ["instances", "reloc_mode", "target_groups"],
12257
       ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12258
         # pylint: disable-msg=E1101
12259
         # Class '...' has no 'OP_ID' member
12260
         "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12261
                              opcodes.OpInstanceMigrate.OP_ID,
12262
                              opcodes.OpInstanceReplaceDisks.OP_ID])
12263
         })))),
12264
    }
12265

    
12266
  def Run(self, name, validate=True, call_fn=None):
12267
    """Run an instance allocator and return the results.
12268

12269
    """
12270
    if call_fn is None:
12271
      call_fn = self.rpc.call_iallocator_runner
12272

    
12273
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12274
    result.Raise("Failure while running the iallocator script")
12275

    
12276
    self.out_text = result.payload
12277
    if validate:
12278
      self._ValidateResult()
12279

    
12280
  def _ValidateResult(self):
12281
    """Process the allocator results.
12282

12283
    This will process and if successful save the result in
12284
    self.out_data and the other parameters.
12285

12286
    """
12287
    try:
12288
      rdict = serializer.Load(self.out_text)
12289
    except Exception, err:
12290
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12291

    
12292
    if not isinstance(rdict, dict):
12293
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12294

    
12295
    # TODO: remove backwards compatiblity in later versions
12296
    if "nodes" in rdict and "result" not in rdict:
12297
      rdict["result"] = rdict["nodes"]
12298
      del rdict["nodes"]
12299

    
12300
    for key in "success", "info", "result":
12301
      if key not in rdict:
12302
        raise errors.OpExecError("Can't parse iallocator results:"
12303
                                 " missing key '%s'" % key)
12304
      setattr(self, key, rdict[key])
12305

    
12306
    if not self._result_check(self.result):
12307
      raise errors.OpExecError("Iallocator returned invalid result,"
12308
                               " expected %s, got %s" %
12309
                               (self._result_check, self.result),
12310
                               errors.ECODE_INVAL)
12311

    
12312
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12313
                     constants.IALLOCATOR_MODE_MEVAC):
12314
      node2group = dict((name, ndata["group"])
12315
                        for (name, ndata) in self.in_data["nodes"].items())
12316

    
12317
      fn = compat.partial(self._NodesToGroups, node2group,
12318
                          self.in_data["nodegroups"])
12319

    
12320
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12321
        assert self.relocate_from is not None
12322
        assert self.required_nodes == 1
12323

    
12324
        request_groups = fn(self.relocate_from)
12325
        result_groups = fn(rdict["result"])
12326

    
12327
        if result_groups != request_groups:
12328
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12329
                                   " differ from original groups (%s)" %
12330
                                   (utils.CommaJoin(result_groups),
12331
                                    utils.CommaJoin(request_groups)))
12332
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12333
        request_groups = fn(self.evac_nodes)
12334
        for (instance_name, secnode) in self.result:
12335
          result_groups = fn([secnode])
12336
          if result_groups != request_groups:
12337
            raise errors.OpExecError("Iallocator returned new secondary node"
12338
                                     " '%s' (group '%s') for instance '%s'"
12339
                                     " which is not in original group '%s'" %
12340
                                     (secnode, utils.CommaJoin(result_groups),
12341
                                      instance_name,
12342
                                      utils.CommaJoin(request_groups)))
12343
      else:
12344
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12345

    
12346
    self.out_data = rdict
12347

    
12348
  @staticmethod
12349
  def _NodesToGroups(node2group, groups, nodes):
12350
    """Returns a list of unique group names for a list of nodes.
12351

12352
    @type node2group: dict
12353
    @param node2group: Map from node name to group UUID
12354
    @type groups: dict
12355
    @param groups: Group information
12356
    @type nodes: list
12357
    @param nodes: Node names
12358

12359
    """
12360
    result = set()
12361

    
12362
    for node in nodes:
12363
      try:
12364
        group_uuid = node2group[node]
12365
      except KeyError:
12366
        # Ignore unknown node
12367
        pass
12368
      else:
12369
        try:
12370
          group = groups[group_uuid]
12371
        except KeyError:
12372
          # Can't find group, let's use UUID
12373
          group_name = group_uuid
12374
        else:
12375
          group_name = group["name"]
12376

    
12377
        result.add(group_name)
12378

    
12379
    return sorted(result)
12380

    
12381

    
12382
class LUTestAllocator(NoHooksLU):
12383
  """Run allocator tests.
12384

12385
  This LU runs the allocator tests
12386

12387
  """
12388
  def CheckPrereq(self):
12389
    """Check prerequisites.
12390

12391
    This checks the opcode parameters depending on the director and mode test.
12392

12393
    """
12394
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12395
      for attr in ["mem_size", "disks", "disk_template",
12396
                   "os", "tags", "nics", "vcpus"]:
12397
        if not hasattr(self.op, attr):
12398
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12399
                                     attr, errors.ECODE_INVAL)
12400
      iname = self.cfg.ExpandInstanceName(self.op.name)
12401
      if iname is not None:
12402
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12403
                                   iname, errors.ECODE_EXISTS)
12404
      if not isinstance(self.op.nics, list):
12405
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12406
                                   errors.ECODE_INVAL)
12407
      if not isinstance(self.op.disks, list):
12408
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12409
                                   errors.ECODE_INVAL)
12410
      for row in self.op.disks:
12411
        if (not isinstance(row, dict) or
12412
            "size" not in row or
12413
            not isinstance(row["size"], int) or
12414
            "mode" not in row or
12415
            row["mode"] not in ['r', 'w']):
12416
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12417
                                     " parameter", errors.ECODE_INVAL)
12418
      if self.op.hypervisor is None:
12419
        self.op.hypervisor = self.cfg.GetHypervisorType()
12420
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12421
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12422
      self.op.name = fname
12423
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12424
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12425
      if not hasattr(self.op, "evac_nodes"):
12426
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12427
                                   " opcode input", errors.ECODE_INVAL)
12428
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12429
      if self.op.instances:
12430
        self.op.instances = _GetWantedInstances(self, self.op.instances)
12431
      else:
12432
        raise errors.OpPrereqError("Missing instances to relocate",
12433
                                   errors.ECODE_INVAL)
12434
    else:
12435
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12436
                                 self.op.mode, errors.ECODE_INVAL)
12437

    
12438
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12439
      if self.op.allocator is None:
12440
        raise errors.OpPrereqError("Missing allocator name",
12441
                                   errors.ECODE_INVAL)
12442
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12443
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12444
                                 self.op.direction, errors.ECODE_INVAL)
12445

    
12446
  def Exec(self, feedback_fn):
12447
    """Run the allocator test.
12448

12449
    """
12450
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12451
      ial = IAllocator(self.cfg, self.rpc,
12452
                       mode=self.op.mode,
12453
                       name=self.op.name,
12454
                       mem_size=self.op.mem_size,
12455
                       disks=self.op.disks,
12456
                       disk_template=self.op.disk_template,
12457
                       os=self.op.os,
12458
                       tags=self.op.tags,
12459
                       nics=self.op.nics,
12460
                       vcpus=self.op.vcpus,
12461
                       hypervisor=self.op.hypervisor,
12462
                       )
12463
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12464
      ial = IAllocator(self.cfg, self.rpc,
12465
                       mode=self.op.mode,
12466
                       name=self.op.name,
12467
                       relocate_from=list(self.relocate_from),
12468
                       )
12469
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12470
      ial = IAllocator(self.cfg, self.rpc,
12471
                       mode=self.op.mode,
12472
                       evac_nodes=self.op.evac_nodes)
12473
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12474
      ial = IAllocator(self.cfg, self.rpc,
12475
                       mode=self.op.mode,
12476
                       instances=self.op.instances,
12477
                       reloc_mode=self.op.reloc_mode,
12478
                       target_groups=self.op.target_groups)
12479
    else:
12480
      raise errors.ProgrammerError("Uncatched mode %s in"
12481
                                   " LUTestAllocator.Exec", self.op.mode)
12482

    
12483
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
12484
      result = ial.in_text
12485
    else:
12486
      ial.Run(self.op.allocator, validate=False)
12487
      result = ial.out_text
12488
    return result
12489

    
12490

    
12491
#: Query type implementations
12492
_QUERY_IMPL = {
12493
  constants.QR_INSTANCE: _InstanceQuery,
12494
  constants.QR_NODE: _NodeQuery,
12495
  constants.QR_GROUP: _GroupQuery,
12496
  constants.QR_OS: _OsQuery,
12497
  }
12498

    
12499
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
12500

    
12501

    
12502
def _GetQueryImplementation(name):
12503
  """Returns the implemtnation for a query type.
12504

12505
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
12506

12507
  """
12508
  try:
12509
    return _QUERY_IMPL[name]
12510
  except KeyError:
12511
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
12512
                               errors.ECODE_INVAL)