Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ cf692cd0

History | View | Annotate | Download (434.8 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 LUClusterVerify.
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 (LUClusterVerify.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 (LUClusterVerify.ETYPE_WARNING, fnamemsg)
1283
  elif errcode == utils.CERT_ERROR:
1284
    return (LUClusterVerify.ETYPE_ERROR, fnamemsg)
1285

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

    
1288

    
1289
class LUClusterVerify(LogicalUnit):
1290
  """Verifies the cluster status.
1291

1292
  """
1293
  HPATH = "cluster-verify"
1294
  HTYPE = constants.HTYPE_CLUSTER
1295
  REQ_BGL = False
1296

    
1297
  TCLUSTER = "cluster"
1298
  TNODE = "node"
1299
  TINSTANCE = "instance"
1300

    
1301
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1302
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1303
  ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1304
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1305
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1306
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1307
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1308
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1309
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1310
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1311
  ENODEDRBD = (TNODE, "ENODEDRBD")
1312
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1313
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1314
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1315
  ENODEHV = (TNODE, "ENODEHV")
1316
  ENODELVM = (TNODE, "ENODELVM")
1317
  ENODEN1 = (TNODE, "ENODEN1")
1318
  ENODENET = (TNODE, "ENODENET")
1319
  ENODEOS = (TNODE, "ENODEOS")
1320
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1321
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1322
  ENODERPC = (TNODE, "ENODERPC")
1323
  ENODESSH = (TNODE, "ENODESSH")
1324
  ENODEVERSION = (TNODE, "ENODEVERSION")
1325
  ENODESETUP = (TNODE, "ENODESETUP")
1326
  ENODETIME = (TNODE, "ENODETIME")
1327
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1328

    
1329
  ETYPE_FIELD = "code"
1330
  ETYPE_ERROR = "ERROR"
1331
  ETYPE_WARNING = "WARNING"
1332

    
1333
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1334

    
1335
  class NodeImage(object):
1336
    """A class representing the logical and physical status of a node.
1337

1338
    @type name: string
1339
    @ivar name: the node name to which this object refers
1340
    @ivar volumes: a structure as returned from
1341
        L{ganeti.backend.GetVolumeList} (runtime)
1342
    @ivar instances: a list of running instances (runtime)
1343
    @ivar pinst: list of configured primary instances (config)
1344
    @ivar sinst: list of configured secondary instances (config)
1345
    @ivar sbp: dictionary of {primary-node: list of instances} for all
1346
        instances for which this node is secondary (config)
1347
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1348
    @ivar dfree: free disk, as reported by the node (runtime)
1349
    @ivar offline: the offline status (config)
1350
    @type rpc_fail: boolean
1351
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1352
        not whether the individual keys were correct) (runtime)
1353
    @type lvm_fail: boolean
1354
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1355
    @type hyp_fail: boolean
1356
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1357
    @type ghost: boolean
1358
    @ivar ghost: whether this is a known node or not (config)
1359
    @type os_fail: boolean
1360
    @ivar os_fail: whether the RPC call didn't return valid OS data
1361
    @type oslist: list
1362
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1363
    @type vm_capable: boolean
1364
    @ivar vm_capable: whether the node can host instances
1365

1366
    """
1367
    def __init__(self, offline=False, name=None, vm_capable=True):
1368
      self.name = name
1369
      self.volumes = {}
1370
      self.instances = []
1371
      self.pinst = []
1372
      self.sinst = []
1373
      self.sbp = {}
1374
      self.mfree = 0
1375
      self.dfree = 0
1376
      self.offline = offline
1377
      self.vm_capable = vm_capable
1378
      self.rpc_fail = False
1379
      self.lvm_fail = False
1380
      self.hyp_fail = False
1381
      self.ghost = False
1382
      self.os_fail = False
1383
      self.oslist = {}
1384

    
1385
  def ExpandNames(self):
1386
    self.needed_locks = {
1387
      locking.LEVEL_NODE: locking.ALL_SET,
1388
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1389
    }
1390
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1391

    
1392
  def CheckPrereq(self):
1393
    self.all_node_info = self.cfg.GetAllNodesInfo()
1394
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1395
    self.my_node_names = utils.NiceSort(list(self.all_node_info))
1396
    self.my_node_info = self.all_node_info
1397
    self.my_inst_names = utils.NiceSort(list(self.all_inst_info))
1398
    self.my_inst_info = self.all_inst_info
1399

    
1400
  def _Error(self, ecode, item, msg, *args, **kwargs):
1401
    """Format an error message.
1402

1403
    Based on the opcode's error_codes parameter, either format a
1404
    parseable error code, or a simpler error string.
1405

1406
    This must be called only from Exec and functions called from Exec.
1407

1408
    """
1409
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1410
    itype, etxt = ecode
1411
    # first complete the msg
1412
    if args:
1413
      msg = msg % args
1414
    # then format the whole message
1415
    if self.op.error_codes:
1416
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1417
    else:
1418
      if item:
1419
        item = " " + item
1420
      else:
1421
        item = ""
1422
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1423
    # and finally report it via the feedback_fn
1424
    self._feedback_fn("  - %s" % msg)
1425

    
1426
  def _ErrorIf(self, cond, *args, **kwargs):
1427
    """Log an error message if the passed condition is True.
1428

1429
    """
1430
    cond = bool(cond) or self.op.debug_simulate_errors
1431
    if cond:
1432
      self._Error(*args, **kwargs)
1433
    # do not mark the operation as failed for WARN cases only
1434
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1435
      self.bad = self.bad or cond
1436

    
1437
  def _VerifyNode(self, ninfo, nresult):
1438
    """Perform some basic validation on data returned from a node.
1439

1440
      - check the result data structure is well formed and has all the
1441
        mandatory fields
1442
      - check ganeti version
1443

1444
    @type ninfo: L{objects.Node}
1445
    @param ninfo: the node to check
1446
    @param nresult: the results from the node
1447
    @rtype: boolean
1448
    @return: whether overall this call was successful (and we can expect
1449
         reasonable values in the respose)
1450

1451
    """
1452
    node = ninfo.name
1453
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1454

    
1455
    # main result, nresult should be a non-empty dict
1456
    test = not nresult or not isinstance(nresult, dict)
1457
    _ErrorIf(test, self.ENODERPC, node,
1458
                  "unable to verify node: no data returned")
1459
    if test:
1460
      return False
1461

    
1462
    # compares ganeti version
1463
    local_version = constants.PROTOCOL_VERSION
1464
    remote_version = nresult.get("version", None)
1465
    test = not (remote_version and
1466
                isinstance(remote_version, (list, tuple)) and
1467
                len(remote_version) == 2)
1468
    _ErrorIf(test, self.ENODERPC, node,
1469
             "connection to node returned invalid data")
1470
    if test:
1471
      return False
1472

    
1473
    test = local_version != remote_version[0]
1474
    _ErrorIf(test, self.ENODEVERSION, node,
1475
             "incompatible protocol versions: master %s,"
1476
             " node %s", local_version, remote_version[0])
1477
    if test:
1478
      return False
1479

    
1480
    # node seems compatible, we can actually try to look into its results
1481

    
1482
    # full package version
1483
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1484
                  self.ENODEVERSION, node,
1485
                  "software version mismatch: master %s, node %s",
1486
                  constants.RELEASE_VERSION, remote_version[1],
1487
                  code=self.ETYPE_WARNING)
1488

    
1489
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1490
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1491
      for hv_name, hv_result in hyp_result.iteritems():
1492
        test = hv_result is not None
1493
        _ErrorIf(test, self.ENODEHV, node,
1494
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1495

    
1496
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1497
    if ninfo.vm_capable and isinstance(hvp_result, list):
1498
      for item, hv_name, hv_result in hvp_result:
1499
        _ErrorIf(True, self.ENODEHV, node,
1500
                 "hypervisor %s parameter verify failure (source %s): %s",
1501
                 hv_name, item, hv_result)
1502

    
1503
    test = nresult.get(constants.NV_NODESETUP,
1504
                       ["Missing NODESETUP results"])
1505
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1506
             "; ".join(test))
1507

    
1508
    return True
1509

    
1510
  def _VerifyNodeTime(self, ninfo, nresult,
1511
                      nvinfo_starttime, nvinfo_endtime):
1512
    """Check the node time.
1513

1514
    @type ninfo: L{objects.Node}
1515
    @param ninfo: the node to check
1516
    @param nresult: the remote results for the node
1517
    @param nvinfo_starttime: the start time of the RPC call
1518
    @param nvinfo_endtime: the end time of the RPC call
1519

1520
    """
1521
    node = ninfo.name
1522
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1523

    
1524
    ntime = nresult.get(constants.NV_TIME, None)
1525
    try:
1526
      ntime_merged = utils.MergeTime(ntime)
1527
    except (ValueError, TypeError):
1528
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1529
      return
1530

    
1531
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1532
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1533
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1534
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1535
    else:
1536
      ntime_diff = None
1537

    
1538
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1539
             "Node time diverges by at least %s from master node time",
1540
             ntime_diff)
1541

    
1542
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1543
    """Check the node LVM results.
1544

1545
    @type ninfo: L{objects.Node}
1546
    @param ninfo: the node to check
1547
    @param nresult: the remote results for the node
1548
    @param vg_name: the configured VG name
1549

1550
    """
1551
    if vg_name is None:
1552
      return
1553

    
1554
    node = ninfo.name
1555
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1556

    
1557
    # checks vg existence and size > 20G
1558
    vglist = nresult.get(constants.NV_VGLIST, None)
1559
    test = not vglist
1560
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1561
    if not test:
1562
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1563
                                            constants.MIN_VG_SIZE)
1564
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1565

    
1566
    # check pv names
1567
    pvlist = nresult.get(constants.NV_PVLIST, None)
1568
    test = pvlist is None
1569
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1570
    if not test:
1571
      # check that ':' is not present in PV names, since it's a
1572
      # special character for lvcreate (denotes the range of PEs to
1573
      # use on the PV)
1574
      for _, pvname, owner_vg in pvlist:
1575
        test = ":" in pvname
1576
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1577
                 " '%s' of VG '%s'", pvname, owner_vg)
1578

    
1579
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1580
    """Check the node bridges.
1581

1582
    @type ninfo: L{objects.Node}
1583
    @param ninfo: the node to check
1584
    @param nresult: the remote results for the node
1585
    @param bridges: the expected list of bridges
1586

1587
    """
1588
    if not bridges:
1589
      return
1590

    
1591
    node = ninfo.name
1592
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1593

    
1594
    missing = nresult.get(constants.NV_BRIDGES, None)
1595
    test = not isinstance(missing, list)
1596
    _ErrorIf(test, self.ENODENET, node,
1597
             "did not return valid bridge information")
1598
    if not test:
1599
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1600
               utils.CommaJoin(sorted(missing)))
1601

    
1602
  def _VerifyNodeNetwork(self, ninfo, nresult):
1603
    """Check the node network connectivity results.
1604

1605
    @type ninfo: L{objects.Node}
1606
    @param ninfo: the node to check
1607
    @param nresult: the remote results for the node
1608

1609
    """
1610
    node = ninfo.name
1611
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1612

    
1613
    test = constants.NV_NODELIST not in nresult
1614
    _ErrorIf(test, self.ENODESSH, node,
1615
             "node hasn't returned node ssh connectivity data")
1616
    if not test:
1617
      if nresult[constants.NV_NODELIST]:
1618
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1619
          _ErrorIf(True, self.ENODESSH, node,
1620
                   "ssh communication with node '%s': %s", a_node, a_msg)
1621

    
1622
    test = constants.NV_NODENETTEST not in nresult
1623
    _ErrorIf(test, self.ENODENET, node,
1624
             "node hasn't returned node tcp connectivity data")
1625
    if not test:
1626
      if nresult[constants.NV_NODENETTEST]:
1627
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1628
        for anode in nlist:
1629
          _ErrorIf(True, self.ENODENET, node,
1630
                   "tcp communication with node '%s': %s",
1631
                   anode, nresult[constants.NV_NODENETTEST][anode])
1632

    
1633
    test = constants.NV_MASTERIP not in nresult
1634
    _ErrorIf(test, self.ENODENET, node,
1635
             "node hasn't returned node master IP reachability data")
1636
    if not test:
1637
      if not nresult[constants.NV_MASTERIP]:
1638
        if node == self.master_node:
1639
          msg = "the master node cannot reach the master IP (not configured?)"
1640
        else:
1641
          msg = "cannot reach the master IP"
1642
        _ErrorIf(True, self.ENODENET, node, msg)
1643

    
1644
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1645
                      diskstatus):
1646
    """Verify an instance.
1647

1648
    This function checks to see if the required block devices are
1649
    available on the instance's node.
1650

1651
    """
1652
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1653
    node_current = instanceconfig.primary_node
1654

    
1655
    node_vol_should = {}
1656
    instanceconfig.MapLVsByNode(node_vol_should)
1657

    
1658
    for node in node_vol_should:
1659
      n_img = node_image[node]
1660
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1661
        # ignore missing volumes on offline or broken nodes
1662
        continue
1663
      for volume in node_vol_should[node]:
1664
        test = volume not in n_img.volumes
1665
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1666
                 "volume %s missing on node %s", volume, node)
1667

    
1668
    if instanceconfig.admin_up:
1669
      pri_img = node_image[node_current]
1670
      test = instance not in pri_img.instances and not pri_img.offline
1671
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1672
               "instance not running on its primary node %s",
1673
               node_current)
1674

    
1675
    for node, n_img in node_image.items():
1676
      if node != node_current:
1677
        test = instance in n_img.instances
1678
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1679
                 "instance should not run on node %s", node)
1680

    
1681
    diskdata = [(nname, success, status, idx)
1682
                for (nname, disks) in diskstatus.items()
1683
                for idx, (success, status) in enumerate(disks)]
1684

    
1685
    for nname, success, bdev_status, idx in diskdata:
1686
      # the 'ghost node' construction in Exec() ensures that we have a
1687
      # node here
1688
      snode = node_image[nname]
1689
      bad_snode = snode.ghost or snode.offline
1690
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1691
               self.EINSTANCEFAULTYDISK, instance,
1692
               "couldn't retrieve status for disk/%s on %s: %s",
1693
               idx, nname, bdev_status)
1694
      _ErrorIf((instanceconfig.admin_up and success and
1695
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1696
               self.EINSTANCEFAULTYDISK, instance,
1697
               "disk/%s on %s is faulty", idx, nname)
1698

    
1699
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1700
    """Verify if there are any unknown volumes in the cluster.
1701

1702
    The .os, .swap and backup volumes are ignored. All other volumes are
1703
    reported as unknown.
1704

1705
    @type reserved: L{ganeti.utils.FieldSet}
1706
    @param reserved: a FieldSet of reserved volume names
1707

1708
    """
1709
    for node, n_img in node_image.items():
1710
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1711
        # skip non-healthy nodes
1712
        continue
1713
      for volume in n_img.volumes:
1714
        test = ((node not in node_vol_should or
1715
                volume not in node_vol_should[node]) and
1716
                not reserved.Matches(volume))
1717
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1718
                      "volume %s is unknown", volume)
1719

    
1720
  def _VerifyOrphanInstances(self, instancelist, node_image):
1721
    """Verify the list of running instances.
1722

1723
    This checks what instances are running but unknown to the cluster.
1724

1725
    """
1726
    for node, n_img in node_image.items():
1727
      for o_inst in n_img.instances:
1728
        test = o_inst not in instancelist
1729
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1730
                      "instance %s on node %s should not exist", o_inst, node)
1731

    
1732
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1733
    """Verify N+1 Memory Resilience.
1734

1735
    Check that if one single node dies we can still start all the
1736
    instances it was primary for.
1737

1738
    """
1739
    cluster_info = self.cfg.GetClusterInfo()
1740
    for node, n_img in node_image.items():
1741
      # This code checks that every node which is now listed as
1742
      # secondary has enough memory to host all instances it is
1743
      # supposed to should a single other node in the cluster fail.
1744
      # FIXME: not ready for failover to an arbitrary node
1745
      # FIXME: does not support file-backed instances
1746
      # WARNING: we currently take into account down instances as well
1747
      # as up ones, considering that even if they're down someone
1748
      # might want to start them even in the event of a node failure.
1749
      if n_img.offline:
1750
        # we're skipping offline nodes from the N+1 warning, since
1751
        # most likely we don't have good memory infromation from them;
1752
        # we already list instances living on such nodes, and that's
1753
        # enough warning
1754
        continue
1755
      for prinode, instances in n_img.sbp.items():
1756
        needed_mem = 0
1757
        for instance in instances:
1758
          bep = cluster_info.FillBE(instance_cfg[instance])
1759
          if bep[constants.BE_AUTO_BALANCE]:
1760
            needed_mem += bep[constants.BE_MEMORY]
1761
        test = n_img.mfree < needed_mem
1762
        self._ErrorIf(test, self.ENODEN1, node,
1763
                      "not enough memory to accomodate instance failovers"
1764
                      " should node %s fail (%dMiB needed, %dMiB available)",
1765
                      prinode, needed_mem, n_img.mfree)
1766

    
1767
  @classmethod
1768
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1769
                   (files_all, files_all_opt, files_mc, files_vm)):
1770
    """Verifies file checksums collected from all nodes.
1771

1772
    @param errorif: Callback for reporting errors
1773
    @param nodeinfo: List of L{objects.Node} objects
1774
    @param master_node: Name of master node
1775
    @param all_nvinfo: RPC results
1776

1777
    """
1778
    node_names = frozenset(node.name for node in nodeinfo)
1779

    
1780
    assert master_node in node_names
1781
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1782
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1783
           "Found file listed in more than one file list"
1784

    
1785
    # Define functions determining which nodes to consider for a file
1786
    file2nodefn = dict([(filename, fn)
1787
      for (files, fn) in [(files_all, None),
1788
                          (files_all_opt, None),
1789
                          (files_mc, lambda node: (node.master_candidate or
1790
                                                   node.name == master_node)),
1791
                          (files_vm, lambda node: node.vm_capable)]
1792
      for filename in files])
1793

    
1794
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1795

    
1796
    for node in nodeinfo:
1797
      nresult = all_nvinfo[node.name]
1798

    
1799
      if nresult.fail_msg or not nresult.payload:
1800
        node_files = None
1801
      else:
1802
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1803

    
1804
      test = not (node_files and isinstance(node_files, dict))
1805
      errorif(test, cls.ENODEFILECHECK, node.name,
1806
              "Node did not return file checksum data")
1807
      if test:
1808
        continue
1809

    
1810
      for (filename, checksum) in node_files.items():
1811
        # Check if the file should be considered for a node
1812
        fn = file2nodefn[filename]
1813
        if fn is None or fn(node):
1814
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
1815

    
1816
    for (filename, checksums) in fileinfo.items():
1817
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
1818

    
1819
      # Nodes having the file
1820
      with_file = frozenset(node_name
1821
                            for nodes in fileinfo[filename].values()
1822
                            for node_name in nodes)
1823

    
1824
      # Nodes missing file
1825
      missing_file = node_names - with_file
1826

    
1827
      if filename in files_all_opt:
1828
        # All or no nodes
1829
        errorif(missing_file and missing_file != node_names,
1830
                cls.ECLUSTERFILECHECK, None,
1831
                "File %s is optional, but it must exist on all or no nodes (not"
1832
                " found on %s)",
1833
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
1834
      else:
1835
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
1836
                "File %s is missing from node(s) %s", filename,
1837
                utils.CommaJoin(utils.NiceSort(missing_file)))
1838

    
1839
      # See if there are multiple versions of the file
1840
      test = len(checksums) > 1
1841
      if test:
1842
        variants = ["variant %s on %s" %
1843
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
1844
                    for (idx, (checksum, nodes)) in
1845
                      enumerate(sorted(checksums.items()))]
1846
      else:
1847
        variants = []
1848

    
1849
      errorif(test, cls.ECLUSTERFILECHECK, None,
1850
              "File %s found with %s different checksums (%s)",
1851
              filename, len(checksums), "; ".join(variants))
1852

    
1853
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1854
                      drbd_map):
1855
    """Verifies and the node DRBD status.
1856

1857
    @type ninfo: L{objects.Node}
1858
    @param ninfo: the node to check
1859
    @param nresult: the remote results for the node
1860
    @param instanceinfo: the dict of instances
1861
    @param drbd_helper: the configured DRBD usermode helper
1862
    @param drbd_map: the DRBD map as returned by
1863
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1864

1865
    """
1866
    node = ninfo.name
1867
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1868

    
1869
    if drbd_helper:
1870
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1871
      test = (helper_result == None)
1872
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1873
               "no drbd usermode helper returned")
1874
      if helper_result:
1875
        status, payload = helper_result
1876
        test = not status
1877
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1878
                 "drbd usermode helper check unsuccessful: %s", payload)
1879
        test = status and (payload != drbd_helper)
1880
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1881
                 "wrong drbd usermode helper: %s", payload)
1882

    
1883
    # compute the DRBD minors
1884
    node_drbd = {}
1885
    for minor, instance in drbd_map[node].items():
1886
      test = instance not in instanceinfo
1887
      _ErrorIf(test, self.ECLUSTERCFG, None,
1888
               "ghost instance '%s' in temporary DRBD map", instance)
1889
        # ghost instance should not be running, but otherwise we
1890
        # don't give double warnings (both ghost instance and
1891
        # unallocated minor in use)
1892
      if test:
1893
        node_drbd[minor] = (instance, False)
1894
      else:
1895
        instance = instanceinfo[instance]
1896
        node_drbd[minor] = (instance.name, instance.admin_up)
1897

    
1898
    # and now check them
1899
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1900
    test = not isinstance(used_minors, (tuple, list))
1901
    _ErrorIf(test, self.ENODEDRBD, node,
1902
             "cannot parse drbd status file: %s", str(used_minors))
1903
    if test:
1904
      # we cannot check drbd status
1905
      return
1906

    
1907
    for minor, (iname, must_exist) in node_drbd.items():
1908
      test = minor not in used_minors and must_exist
1909
      _ErrorIf(test, self.ENODEDRBD, node,
1910
               "drbd minor %d of instance %s is not active", minor, iname)
1911
    for minor in used_minors:
1912
      test = minor not in node_drbd
1913
      _ErrorIf(test, self.ENODEDRBD, node,
1914
               "unallocated drbd minor %d is in use", minor)
1915

    
1916
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1917
    """Builds the node OS structures.
1918

1919
    @type ninfo: L{objects.Node}
1920
    @param ninfo: the node to check
1921
    @param nresult: the remote results for the node
1922
    @param nimg: the node image object
1923

1924
    """
1925
    node = ninfo.name
1926
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1927

    
1928
    remote_os = nresult.get(constants.NV_OSLIST, None)
1929
    test = (not isinstance(remote_os, list) or
1930
            not compat.all(isinstance(v, list) and len(v) == 7
1931
                           for v in remote_os))
1932

    
1933
    _ErrorIf(test, self.ENODEOS, node,
1934
             "node hasn't returned valid OS data")
1935

    
1936
    nimg.os_fail = test
1937

    
1938
    if test:
1939
      return
1940

    
1941
    os_dict = {}
1942

    
1943
    for (name, os_path, status, diagnose,
1944
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1945

    
1946
      if name not in os_dict:
1947
        os_dict[name] = []
1948

    
1949
      # parameters is a list of lists instead of list of tuples due to
1950
      # JSON lacking a real tuple type, fix it:
1951
      parameters = [tuple(v) for v in parameters]
1952
      os_dict[name].append((os_path, status, diagnose,
1953
                            set(variants), set(parameters), set(api_ver)))
1954

    
1955
    nimg.oslist = os_dict
1956

    
1957
  def _VerifyNodeOS(self, ninfo, nimg, base):
1958
    """Verifies the node OS list.
1959

1960
    @type ninfo: L{objects.Node}
1961
    @param ninfo: the node to check
1962
    @param nimg: the node image object
1963
    @param base: the 'template' node we match against (e.g. from the master)
1964

1965
    """
1966
    node = ninfo.name
1967
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1968

    
1969
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1970

    
1971
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
1972
    for os_name, os_data in nimg.oslist.items():
1973
      assert os_data, "Empty OS status for OS %s?!" % os_name
1974
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1975
      _ErrorIf(not f_status, self.ENODEOS, node,
1976
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1977
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1978
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1979
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1980
      # this will catched in backend too
1981
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1982
               and not f_var, self.ENODEOS, node,
1983
               "OS %s with API at least %d does not declare any variant",
1984
               os_name, constants.OS_API_V15)
1985
      # comparisons with the 'base' image
1986
      test = os_name not in base.oslist
1987
      _ErrorIf(test, self.ENODEOS, node,
1988
               "Extra OS %s not present on reference node (%s)",
1989
               os_name, base.name)
1990
      if test:
1991
        continue
1992
      assert base.oslist[os_name], "Base node has empty OS status?"
1993
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1994
      if not b_status:
1995
        # base OS is invalid, skipping
1996
        continue
1997
      for kind, a, b in [("API version", f_api, b_api),
1998
                         ("variants list", f_var, b_var),
1999
                         ("parameters", beautify_params(f_param),
2000
                          beautify_params(b_param))]:
2001
        _ErrorIf(a != b, self.ENODEOS, node,
2002
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2003
                 kind, os_name, base.name,
2004
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2005

    
2006
    # check any missing OSes
2007
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2008
    _ErrorIf(missing, self.ENODEOS, node,
2009
             "OSes present on reference node %s but missing on this node: %s",
2010
             base.name, utils.CommaJoin(missing))
2011

    
2012
  def _VerifyOob(self, ninfo, nresult):
2013
    """Verifies out of band functionality of a node.
2014

2015
    @type ninfo: L{objects.Node}
2016
    @param ninfo: the node to check
2017
    @param nresult: the remote results for the node
2018

2019
    """
2020
    node = ninfo.name
2021
    # We just have to verify the paths on master and/or master candidates
2022
    # as the oob helper is invoked on the master
2023
    if ((ninfo.master_candidate or ninfo.master_capable) and
2024
        constants.NV_OOB_PATHS in nresult):
2025
      for path_result in nresult[constants.NV_OOB_PATHS]:
2026
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2027

    
2028
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2029
    """Verifies and updates the node volume data.
2030

2031
    This function will update a L{NodeImage}'s internal structures
2032
    with data from the remote call.
2033

2034
    @type ninfo: L{objects.Node}
2035
    @param ninfo: the node to check
2036
    @param nresult: the remote results for the node
2037
    @param nimg: the node image object
2038
    @param vg_name: the configured VG name
2039

2040
    """
2041
    node = ninfo.name
2042
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2043

    
2044
    nimg.lvm_fail = True
2045
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2046
    if vg_name is None:
2047
      pass
2048
    elif isinstance(lvdata, basestring):
2049
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2050
               utils.SafeEncode(lvdata))
2051
    elif not isinstance(lvdata, dict):
2052
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2053
    else:
2054
      nimg.volumes = lvdata
2055
      nimg.lvm_fail = False
2056

    
2057
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2058
    """Verifies and updates the node instance list.
2059

2060
    If the listing was successful, then updates this node's instance
2061
    list. Otherwise, it marks the RPC call as failed for the instance
2062
    list key.
2063

2064
    @type ninfo: L{objects.Node}
2065
    @param ninfo: the node to check
2066
    @param nresult: the remote results for the node
2067
    @param nimg: the node image object
2068

2069
    """
2070
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2071
    test = not isinstance(idata, list)
2072
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2073
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2074
    if test:
2075
      nimg.hyp_fail = True
2076
    else:
2077
      nimg.instances = idata
2078

    
2079
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2080
    """Verifies and computes a node information map
2081

2082
    @type ninfo: L{objects.Node}
2083
    @param ninfo: the node to check
2084
    @param nresult: the remote results for the node
2085
    @param nimg: the node image object
2086
    @param vg_name: the configured VG name
2087

2088
    """
2089
    node = ninfo.name
2090
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2091

    
2092
    # try to read free memory (from the hypervisor)
2093
    hv_info = nresult.get(constants.NV_HVINFO, None)
2094
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2095
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2096
    if not test:
2097
      try:
2098
        nimg.mfree = int(hv_info["memory_free"])
2099
      except (ValueError, TypeError):
2100
        _ErrorIf(True, self.ENODERPC, node,
2101
                 "node returned invalid nodeinfo, check hypervisor")
2102

    
2103
    # FIXME: devise a free space model for file based instances as well
2104
    if vg_name is not None:
2105
      test = (constants.NV_VGLIST not in nresult or
2106
              vg_name not in nresult[constants.NV_VGLIST])
2107
      _ErrorIf(test, self.ENODELVM, node,
2108
               "node didn't return data for the volume group '%s'"
2109
               " - it is either missing or broken", vg_name)
2110
      if not test:
2111
        try:
2112
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2113
        except (ValueError, TypeError):
2114
          _ErrorIf(True, self.ENODERPC, node,
2115
                   "node returned invalid LVM info, check LVM status")
2116

    
2117
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2118
    """Gets per-disk status information for all instances.
2119

2120
    @type nodelist: list of strings
2121
    @param nodelist: Node names
2122
    @type node_image: dict of (name, L{objects.Node})
2123
    @param node_image: Node objects
2124
    @type instanceinfo: dict of (name, L{objects.Instance})
2125
    @param instanceinfo: Instance objects
2126
    @rtype: {instance: {node: [(succes, payload)]}}
2127
    @return: a dictionary of per-instance dictionaries with nodes as
2128
        keys and disk information as values; the disk information is a
2129
        list of tuples (success, payload)
2130

2131
    """
2132
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2133

    
2134
    node_disks = {}
2135
    node_disks_devonly = {}
2136
    diskless_instances = set()
2137
    diskless = constants.DT_DISKLESS
2138

    
2139
    for nname in nodelist:
2140
      node_instances = list(itertools.chain(node_image[nname].pinst,
2141
                                            node_image[nname].sinst))
2142
      diskless_instances.update(inst for inst in node_instances
2143
                                if instanceinfo[inst].disk_template == diskless)
2144
      disks = [(inst, disk)
2145
               for inst in node_instances
2146
               for disk in instanceinfo[inst].disks]
2147

    
2148
      if not disks:
2149
        # No need to collect data
2150
        continue
2151

    
2152
      node_disks[nname] = disks
2153

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

    
2158
      for dev in devonly:
2159
        self.cfg.SetDiskID(dev, nname)
2160

    
2161
      node_disks_devonly[nname] = devonly
2162

    
2163
    assert len(node_disks) == len(node_disks_devonly)
2164

    
2165
    # Collect data from all nodes with disks
2166
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2167
                                                          node_disks_devonly)
2168

    
2169
    assert len(result) == len(node_disks)
2170

    
2171
    instdisk = {}
2172

    
2173
    for (nname, nres) in result.items():
2174
      disks = node_disks[nname]
2175

    
2176
      if nres.offline:
2177
        # No data from this node
2178
        data = len(disks) * [(False, "node offline")]
2179
      else:
2180
        msg = nres.fail_msg
2181
        _ErrorIf(msg, self.ENODERPC, nname,
2182
                 "while getting disk information: %s", msg)
2183
        if msg:
2184
          # No data from this node
2185
          data = len(disks) * [(False, msg)]
2186
        else:
2187
          data = []
2188
          for idx, i in enumerate(nres.payload):
2189
            if isinstance(i, (tuple, list)) and len(i) == 2:
2190
              data.append(i)
2191
            else:
2192
              logging.warning("Invalid result from node %s, entry %d: %s",
2193
                              nname, idx, i)
2194
              data.append((False, "Invalid result from the remote node"))
2195

    
2196
      for ((inst, _), status) in zip(disks, data):
2197
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2198

    
2199
    # Add empty entries for diskless instances.
2200
    for inst in diskless_instances:
2201
      assert inst not in instdisk
2202
      instdisk[inst] = {}
2203

    
2204
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2205
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2206
                      compat.all(isinstance(s, (tuple, list)) and
2207
                                 len(s) == 2 for s in statuses)
2208
                      for inst, nnames in instdisk.items()
2209
                      for nname, statuses in nnames.items())
2210
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2211

    
2212
    return instdisk
2213

    
2214
  def _VerifyHVP(self, hvp_data):
2215
    """Verifies locally the syntax of the hypervisor parameters.
2216

2217
    """
2218
    for item, hv_name, hv_params in hvp_data:
2219
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
2220
             (item, hv_name))
2221
      try:
2222
        hv_class = hypervisor.GetHypervisor(hv_name)
2223
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2224
        hv_class.CheckParameterSyntax(hv_params)
2225
      except errors.GenericError, err:
2226
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
2227

    
2228
  def BuildHooksEnv(self):
2229
    """Build hooks env.
2230

2231
    Cluster-Verify hooks just ran in the post phase and their failure makes
2232
    the output be logged in the verify output and the verification to fail.
2233

2234
    """
2235
    env = {
2236
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2237
      }
2238

    
2239
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2240
               for node in self.my_node_info.values())
2241

    
2242
    return env
2243

    
2244
  def BuildHooksNodes(self):
2245
    """Build hooks nodes.
2246

2247
    """
2248
    assert self.my_node_names, ("Node list not gathered,"
2249
      " has CheckPrereq been executed?")
2250
    return ([], self.my_node_names)
2251

    
2252
  def Exec(self, feedback_fn):
2253
    """Verify integrity of cluster, performing various test on nodes.
2254

2255
    """
2256
    # This method has too many local variables. pylint: disable-msg=R0914
2257
    self.bad = False
2258
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2259
    verbose = self.op.verbose
2260
    self._feedback_fn = feedback_fn
2261
    feedback_fn("* Verifying global settings")
2262
    for msg in self.cfg.VerifyConfig():
2263
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2264

    
2265
    # Check the cluster certificates
2266
    for cert_filename in constants.ALL_CERT_FILES:
2267
      (errcode, msg) = _VerifyCertificate(cert_filename)
2268
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2269

    
2270
    vg_name = self.cfg.GetVGName()
2271
    drbd_helper = self.cfg.GetDRBDHelper()
2272
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2273
    cluster = self.cfg.GetClusterInfo()
2274
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2275
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2276

    
2277
    i_non_redundant = [] # Non redundant instances
2278
    i_non_a_balanced = [] # Non auto-balanced instances
2279
    n_offline = 0 # Count of offline nodes
2280
    n_drained = 0 # Count of nodes being drained
2281
    node_vol_should = {}
2282

    
2283
    # FIXME: verify OS list
2284

    
2285
    # File verification
2286
    filemap = _ComputeAncillaryFiles(cluster, False)
2287

    
2288
    # do local checksums
2289
    master_node = self.master_node = self.cfg.GetMasterNode()
2290
    master_ip = self.cfg.GetMasterIP()
2291

    
2292
    # Compute the set of hypervisor parameters
2293
    hvp_data = []
2294
    for hv_name in hypervisors:
2295
      hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
2296
    for os_name, os_hvp in cluster.os_hvp.items():
2297
      for hv_name, hv_params in os_hvp.items():
2298
        if not hv_params:
2299
          continue
2300
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
2301
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
2302
    # TODO: collapse identical parameter values in a single one
2303
    for instance in self.all_inst_info.values():
2304
      if not instance.hvparams:
2305
        continue
2306
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
2307
                       cluster.FillHV(instance)))
2308
    # and verify them locally
2309
    self._VerifyHVP(hvp_data)
2310

    
2311
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2312
    node_verify_param = {
2313
      constants.NV_FILELIST:
2314
        utils.UniqueSequence(filename
2315
                             for files in filemap
2316
                             for filename in files),
2317
      constants.NV_NODELIST: [node.name for node in self.all_node_info.values()
2318
                              if not node.offline],
2319
      constants.NV_HYPERVISOR: hypervisors,
2320
      constants.NV_HVPARAMS: hvp_data,
2321
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2322
                                 for node in node_data_list
2323
                                 if not node.offline],
2324
      constants.NV_INSTANCELIST: hypervisors,
2325
      constants.NV_VERSION: None,
2326
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2327
      constants.NV_NODESETUP: None,
2328
      constants.NV_TIME: None,
2329
      constants.NV_MASTERIP: (master_node, master_ip),
2330
      constants.NV_OSLIST: None,
2331
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2332
      }
2333

    
2334
    if vg_name is not None:
2335
      node_verify_param[constants.NV_VGLIST] = None
2336
      node_verify_param[constants.NV_LVLIST] = vg_name
2337
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2338
      node_verify_param[constants.NV_DRBDLIST] = None
2339

    
2340
    if drbd_helper:
2341
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2342

    
2343
    # bridge checks
2344
    # FIXME: this needs to be changed per node-group, not cluster-wide
2345
    bridges = set()
2346
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2347
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2348
      bridges.add(default_nicpp[constants.NIC_LINK])
2349
    for instance in instanceinfo.values():
2350
      for nic in instance.nics:
2351
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2352
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2353
          bridges.add(full_nic[constants.NIC_LINK])
2354

    
2355
    if bridges:
2356
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2357

    
2358
    # Build our expected cluster state
2359
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2360
                                                 name=node.name,
2361
                                                 vm_capable=node.vm_capable))
2362
                      for node in node_data_list)
2363

    
2364
    # Gather OOB paths
2365
    oob_paths = []
2366
    for node in self.all_node_info.values():
2367
      path = _SupportsOob(self.cfg, node)
2368
      if path and path not in oob_paths:
2369
        oob_paths.append(path)
2370

    
2371
    if oob_paths:
2372
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2373

    
2374
    for instance in self.my_inst_names:
2375
      inst_config = self.my_inst_info[instance]
2376

    
2377
      for nname in inst_config.all_nodes:
2378
        if nname not in node_image:
2379
          # ghost node
2380
          gnode = self.NodeImage(name=nname)
2381
          gnode.ghost = True
2382
          node_image[nname] = gnode
2383

    
2384
      inst_config.MapLVsByNode(node_vol_should)
2385

    
2386
      pnode = inst_config.primary_node
2387
      node_image[pnode].pinst.append(instance)
2388

    
2389
      for snode in inst_config.secondary_nodes:
2390
        nimg = node_image[snode]
2391
        nimg.sinst.append(instance)
2392
        if pnode not in nimg.sbp:
2393
          nimg.sbp[pnode] = []
2394
        nimg.sbp[pnode].append(instance)
2395

    
2396
    # At this point, we have the in-memory data structures complete,
2397
    # except for the runtime information, which we'll gather next
2398

    
2399
    # Due to the way our RPC system works, exact response times cannot be
2400
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2401
    # time before and after executing the request, we can at least have a time
2402
    # window.
2403
    nvinfo_starttime = time.time()
2404
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2405
                                           node_verify_param,
2406
                                           self.cfg.GetClusterName())
2407
    nvinfo_endtime = time.time()
2408

    
2409
    all_drbd_map = self.cfg.ComputeDRBDMap()
2410

    
2411
    feedback_fn("* Gathering disk information (%s nodes)" %
2412
                len(self.my_node_names))
2413
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2414
                                     self.my_inst_info)
2415

    
2416
    feedback_fn("* Verifying configuration file consistency")
2417
    self._VerifyFiles(_ErrorIf, self.my_node_info.values(), master_node,
2418
                      all_nvinfo, filemap)
2419

    
2420
    feedback_fn("* Verifying node status")
2421

    
2422
    refos_img = None
2423

    
2424
    for node_i in node_data_list:
2425
      node = node_i.name
2426
      nimg = node_image[node]
2427

    
2428
      if node_i.offline:
2429
        if verbose:
2430
          feedback_fn("* Skipping offline node %s" % (node,))
2431
        n_offline += 1
2432
        continue
2433

    
2434
      if node == master_node:
2435
        ntype = "master"
2436
      elif node_i.master_candidate:
2437
        ntype = "master candidate"
2438
      elif node_i.drained:
2439
        ntype = "drained"
2440
        n_drained += 1
2441
      else:
2442
        ntype = "regular"
2443
      if verbose:
2444
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2445

    
2446
      msg = all_nvinfo[node].fail_msg
2447
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2448
      if msg:
2449
        nimg.rpc_fail = True
2450
        continue
2451

    
2452
      nresult = all_nvinfo[node].payload
2453

    
2454
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2455
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2456
      self._VerifyNodeNetwork(node_i, nresult)
2457
      self._VerifyOob(node_i, nresult)
2458

    
2459
      if nimg.vm_capable:
2460
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2461
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2462
                             all_drbd_map)
2463

    
2464
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2465
        self._UpdateNodeInstances(node_i, nresult, nimg)
2466
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2467
        self._UpdateNodeOS(node_i, nresult, nimg)
2468
        if not nimg.os_fail:
2469
          if refos_img is None:
2470
            refos_img = nimg
2471
          self._VerifyNodeOS(node_i, nimg, refos_img)
2472
        self._VerifyNodeBridges(node_i, nresult, bridges)
2473

    
2474
    feedback_fn("* Verifying instance status")
2475
    for instance in self.my_inst_names:
2476
      if verbose:
2477
        feedback_fn("* Verifying instance %s" % instance)
2478
      inst_config = self.my_inst_info[instance]
2479
      self._VerifyInstance(instance, inst_config, node_image,
2480
                           instdisk[instance])
2481
      inst_nodes_offline = []
2482

    
2483
      pnode = inst_config.primary_node
2484
      pnode_img = node_image[pnode]
2485
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2486
               self.ENODERPC, pnode, "instance %s, connection to"
2487
               " primary node failed", instance)
2488

    
2489
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2490
               self.EINSTANCEBADNODE, instance,
2491
               "instance is marked as running and lives on offline node %s",
2492
               inst_config.primary_node)
2493

    
2494
      # If the instance is non-redundant we cannot survive losing its primary
2495
      # node, so we are not N+1 compliant. On the other hand we have no disk
2496
      # templates with more than one secondary so that situation is not well
2497
      # supported either.
2498
      # FIXME: does not support file-backed instances
2499
      if not inst_config.secondary_nodes:
2500
        i_non_redundant.append(instance)
2501

    
2502
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2503
               instance, "instance has multiple secondary nodes: %s",
2504
               utils.CommaJoin(inst_config.secondary_nodes),
2505
               code=self.ETYPE_WARNING)
2506

    
2507
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2508
        pnode = inst_config.primary_node
2509
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2510
        instance_groups = {}
2511

    
2512
        for node in instance_nodes:
2513
          instance_groups.setdefault(self.all_node_info[node].group,
2514
                                     []).append(node)
2515

    
2516
        pretty_list = [
2517
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2518
          # Sort so that we always list the primary node first.
2519
          for group, nodes in sorted(instance_groups.items(),
2520
                                     key=lambda (_, nodes): pnode in nodes,
2521
                                     reverse=True)]
2522

    
2523
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2524
                      instance, "instance has primary and secondary nodes in"
2525
                      " different groups: %s", utils.CommaJoin(pretty_list),
2526
                      code=self.ETYPE_WARNING)
2527

    
2528
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2529
        i_non_a_balanced.append(instance)
2530

    
2531
      for snode in inst_config.secondary_nodes:
2532
        s_img = node_image[snode]
2533
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2534
                 "instance %s, connection to secondary node failed", instance)
2535

    
2536
        if s_img.offline:
2537
          inst_nodes_offline.append(snode)
2538

    
2539
      # warn that the instance lives on offline nodes
2540
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2541
               "instance has offline secondary node(s) %s",
2542
               utils.CommaJoin(inst_nodes_offline))
2543
      # ... or ghost/non-vm_capable nodes
2544
      for node in inst_config.all_nodes:
2545
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2546
                 "instance lives on ghost node %s", node)
2547
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2548
                 instance, "instance lives on non-vm_capable node %s", node)
2549

    
2550
    feedback_fn("* Verifying orphan volumes")
2551
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2552
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2553

    
2554
    feedback_fn("* Verifying orphan instances")
2555
    self._VerifyOrphanInstances(set(self.all_inst_info.keys()), node_image)
2556

    
2557
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2558
      feedback_fn("* Verifying N+1 Memory redundancy")
2559
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2560

    
2561
    feedback_fn("* Other Notes")
2562
    if i_non_redundant:
2563
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2564
                  % len(i_non_redundant))
2565

    
2566
    if i_non_a_balanced:
2567
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2568
                  % len(i_non_a_balanced))
2569

    
2570
    if n_offline:
2571
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2572

    
2573
    if n_drained:
2574
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2575

    
2576
    return not self.bad
2577

    
2578
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2579
    """Analyze the post-hooks' result
2580

2581
    This method analyses the hook result, handles it, and sends some
2582
    nicely-formatted feedback back to the user.
2583

2584
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2585
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2586
    @param hooks_results: the results of the multi-node hooks rpc call
2587
    @param feedback_fn: function used send feedback back to the caller
2588
    @param lu_result: previous Exec result
2589
    @return: the new Exec result, based on the previous result
2590
        and hook results
2591

2592
    """
2593
    # We only really run POST phase hooks, and are only interested in
2594
    # their results
2595
    if phase == constants.HOOKS_PHASE_POST:
2596
      # Used to change hooks' output to proper indentation
2597
      feedback_fn("* Hooks Results")
2598
      assert hooks_results, "invalid result from hooks"
2599

    
2600
      for node_name in hooks_results:
2601
        res = hooks_results[node_name]
2602
        msg = res.fail_msg
2603
        test = msg and not res.offline
2604
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2605
                      "Communication failure in hooks execution: %s", msg)
2606
        if res.offline or msg:
2607
          # No need to investigate payload if node is offline or gave an error.
2608
          # override manually lu_result here as _ErrorIf only
2609
          # overrides self.bad
2610
          lu_result = 1
2611
          continue
2612
        for script, hkr, output in res.payload:
2613
          test = hkr == constants.HKR_FAIL
2614
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2615
                        "Script %s failed, output:", script)
2616
          if test:
2617
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2618
            feedback_fn("%s" % output)
2619
            lu_result = 0
2620

    
2621
      return lu_result
2622

    
2623

    
2624
class LUClusterVerifyDisks(NoHooksLU):
2625
  """Verifies the cluster disks status.
2626

2627
  """
2628
  REQ_BGL = False
2629

    
2630
  def ExpandNames(self):
2631
    self.needed_locks = {
2632
      locking.LEVEL_NODE: locking.ALL_SET,
2633
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2634
    }
2635
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2636

    
2637
  def Exec(self, feedback_fn):
2638
    """Verify integrity of cluster disks.
2639

2640
    @rtype: tuple of three items
2641
    @return: a tuple of (dict of node-to-node_error, list of instances
2642
        which need activate-disks, dict of instance: (node, volume) for
2643
        missing volumes
2644

2645
    """
2646
    result = res_nodes, res_instances, res_missing = {}, [], {}
2647

    
2648
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2649
    instances = self.cfg.GetAllInstancesInfo().values()
2650

    
2651
    nv_dict = {}
2652
    for inst in instances:
2653
      inst_lvs = {}
2654
      if not inst.admin_up:
2655
        continue
2656
      inst.MapLVsByNode(inst_lvs)
2657
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2658
      for node, vol_list in inst_lvs.iteritems():
2659
        for vol in vol_list:
2660
          nv_dict[(node, vol)] = inst
2661

    
2662
    if not nv_dict:
2663
      return result
2664

    
2665
    node_lvs = self.rpc.call_lv_list(nodes, [])
2666
    for node, node_res in node_lvs.items():
2667
      if node_res.offline:
2668
        continue
2669
      msg = node_res.fail_msg
2670
      if msg:
2671
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2672
        res_nodes[node] = msg
2673
        continue
2674

    
2675
      lvs = node_res.payload
2676
      for lv_name, (_, _, lv_online) in lvs.items():
2677
        inst = nv_dict.pop((node, lv_name), None)
2678
        if (not lv_online and inst is not None
2679
            and inst.name not in res_instances):
2680
          res_instances.append(inst.name)
2681

    
2682
    # any leftover items in nv_dict are missing LVs, let's arrange the
2683
    # data better
2684
    for key, inst in nv_dict.iteritems():
2685
      if inst.name not in res_missing:
2686
        res_missing[inst.name] = []
2687
      res_missing[inst.name].append(key)
2688

    
2689
    return result
2690

    
2691

    
2692
class LUClusterRepairDiskSizes(NoHooksLU):
2693
  """Verifies the cluster disks sizes.
2694

2695
  """
2696
  REQ_BGL = False
2697

    
2698
  def ExpandNames(self):
2699
    if self.op.instances:
2700
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2701
      self.needed_locks = {
2702
        locking.LEVEL_NODE: [],
2703
        locking.LEVEL_INSTANCE: self.wanted_names,
2704
        }
2705
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2706
    else:
2707
      self.wanted_names = None
2708
      self.needed_locks = {
2709
        locking.LEVEL_NODE: locking.ALL_SET,
2710
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2711
        }
2712
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2713

    
2714
  def DeclareLocks(self, level):
2715
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2716
      self._LockInstancesNodes(primary_only=True)
2717

    
2718
  def CheckPrereq(self):
2719
    """Check prerequisites.
2720

2721
    This only checks the optional instance list against the existing names.
2722

2723
    """
2724
    if self.wanted_names is None:
2725
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2726

    
2727
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2728
                             in self.wanted_names]
2729

    
2730
  def _EnsureChildSizes(self, disk):
2731
    """Ensure children of the disk have the needed disk size.
2732

2733
    This is valid mainly for DRBD8 and fixes an issue where the
2734
    children have smaller disk size.
2735

2736
    @param disk: an L{ganeti.objects.Disk} object
2737

2738
    """
2739
    if disk.dev_type == constants.LD_DRBD8:
2740
      assert disk.children, "Empty children for DRBD8?"
2741
      fchild = disk.children[0]
2742
      mismatch = fchild.size < disk.size
2743
      if mismatch:
2744
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2745
                     fchild.size, disk.size)
2746
        fchild.size = disk.size
2747

    
2748
      # and we recurse on this child only, not on the metadev
2749
      return self._EnsureChildSizes(fchild) or mismatch
2750
    else:
2751
      return False
2752

    
2753
  def Exec(self, feedback_fn):
2754
    """Verify the size of cluster disks.
2755

2756
    """
2757
    # TODO: check child disks too
2758
    # TODO: check differences in size between primary/secondary nodes
2759
    per_node_disks = {}
2760
    for instance in self.wanted_instances:
2761
      pnode = instance.primary_node
2762
      if pnode not in per_node_disks:
2763
        per_node_disks[pnode] = []
2764
      for idx, disk in enumerate(instance.disks):
2765
        per_node_disks[pnode].append((instance, idx, disk))
2766

    
2767
    changed = []
2768
    for node, dskl in per_node_disks.items():
2769
      newl = [v[2].Copy() for v in dskl]
2770
      for dsk in newl:
2771
        self.cfg.SetDiskID(dsk, node)
2772
      result = self.rpc.call_blockdev_getsize(node, newl)
2773
      if result.fail_msg:
2774
        self.LogWarning("Failure in blockdev_getsize call to node"
2775
                        " %s, ignoring", node)
2776
        continue
2777
      if len(result.payload) != len(dskl):
2778
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2779
                        " result.payload=%s", node, len(dskl), result.payload)
2780
        self.LogWarning("Invalid result from node %s, ignoring node results",
2781
                        node)
2782
        continue
2783
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2784
        if size is None:
2785
          self.LogWarning("Disk %d of instance %s did not return size"
2786
                          " information, ignoring", idx, instance.name)
2787
          continue
2788
        if not isinstance(size, (int, long)):
2789
          self.LogWarning("Disk %d of instance %s did not return valid"
2790
                          " size information, ignoring", idx, instance.name)
2791
          continue
2792
        size = size >> 20
2793
        if size != disk.size:
2794
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2795
                       " correcting: recorded %d, actual %d", idx,
2796
                       instance.name, disk.size, size)
2797
          disk.size = size
2798
          self.cfg.Update(instance, feedback_fn)
2799
          changed.append((instance.name, idx, size))
2800
        if self._EnsureChildSizes(disk):
2801
          self.cfg.Update(instance, feedback_fn)
2802
          changed.append((instance.name, idx, disk.size))
2803
    return changed
2804

    
2805

    
2806
class LUClusterRename(LogicalUnit):
2807
  """Rename the cluster.
2808

2809
  """
2810
  HPATH = "cluster-rename"
2811
  HTYPE = constants.HTYPE_CLUSTER
2812

    
2813
  def BuildHooksEnv(self):
2814
    """Build hooks env.
2815

2816
    """
2817
    return {
2818
      "OP_TARGET": self.cfg.GetClusterName(),
2819
      "NEW_NAME": self.op.name,
2820
      }
2821

    
2822
  def BuildHooksNodes(self):
2823
    """Build hooks nodes.
2824

2825
    """
2826
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
2827

    
2828
  def CheckPrereq(self):
2829
    """Verify that the passed name is a valid one.
2830

2831
    """
2832
    hostname = netutils.GetHostname(name=self.op.name,
2833
                                    family=self.cfg.GetPrimaryIPFamily())
2834

    
2835
    new_name = hostname.name
2836
    self.ip = new_ip = hostname.ip
2837
    old_name = self.cfg.GetClusterName()
2838
    old_ip = self.cfg.GetMasterIP()
2839
    if new_name == old_name and new_ip == old_ip:
2840
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2841
                                 " cluster has changed",
2842
                                 errors.ECODE_INVAL)
2843
    if new_ip != old_ip:
2844
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2845
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2846
                                   " reachable on the network" %
2847
                                   new_ip, errors.ECODE_NOTUNIQUE)
2848

    
2849
    self.op.name = new_name
2850

    
2851
  def Exec(self, feedback_fn):
2852
    """Rename the cluster.
2853

2854
    """
2855
    clustername = self.op.name
2856
    ip = self.ip
2857

    
2858
    # shutdown the master IP
2859
    master = self.cfg.GetMasterNode()
2860
    result = self.rpc.call_node_stop_master(master, False)
2861
    result.Raise("Could not disable the master role")
2862

    
2863
    try:
2864
      cluster = self.cfg.GetClusterInfo()
2865
      cluster.cluster_name = clustername
2866
      cluster.master_ip = ip
2867
      self.cfg.Update(cluster, feedback_fn)
2868

    
2869
      # update the known hosts file
2870
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2871
      node_list = self.cfg.GetOnlineNodeList()
2872
      try:
2873
        node_list.remove(master)
2874
      except ValueError:
2875
        pass
2876
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2877
    finally:
2878
      result = self.rpc.call_node_start_master(master, False, False)
2879
      msg = result.fail_msg
2880
      if msg:
2881
        self.LogWarning("Could not re-enable the master role on"
2882
                        " the master, please restart manually: %s", msg)
2883

    
2884
    return clustername
2885

    
2886

    
2887
class LUClusterSetParams(LogicalUnit):
2888
  """Change the parameters of the cluster.
2889

2890
  """
2891
  HPATH = "cluster-modify"
2892
  HTYPE = constants.HTYPE_CLUSTER
2893
  REQ_BGL = False
2894

    
2895
  def CheckArguments(self):
2896
    """Check parameters
2897

2898
    """
2899
    if self.op.uid_pool:
2900
      uidpool.CheckUidPool(self.op.uid_pool)
2901

    
2902
    if self.op.add_uids:
2903
      uidpool.CheckUidPool(self.op.add_uids)
2904

    
2905
    if self.op.remove_uids:
2906
      uidpool.CheckUidPool(self.op.remove_uids)
2907

    
2908
  def ExpandNames(self):
2909
    # FIXME: in the future maybe other cluster params won't require checking on
2910
    # all nodes to be modified.
2911
    self.needed_locks = {
2912
      locking.LEVEL_NODE: locking.ALL_SET,
2913
    }
2914
    self.share_locks[locking.LEVEL_NODE] = 1
2915

    
2916
  def BuildHooksEnv(self):
2917
    """Build hooks env.
2918

2919
    """
2920
    return {
2921
      "OP_TARGET": self.cfg.GetClusterName(),
2922
      "NEW_VG_NAME": self.op.vg_name,
2923
      }
2924

    
2925
  def BuildHooksNodes(self):
2926
    """Build hooks nodes.
2927

2928
    """
2929
    mn = self.cfg.GetMasterNode()
2930
    return ([mn], [mn])
2931

    
2932
  def CheckPrereq(self):
2933
    """Check prerequisites.
2934

2935
    This checks whether the given params don't conflict and
2936
    if the given volume group is valid.
2937

2938
    """
2939
    if self.op.vg_name is not None and not self.op.vg_name:
2940
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2941
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2942
                                   " instances exist", errors.ECODE_INVAL)
2943

    
2944
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2945
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2946
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2947
                                   " drbd-based instances exist",
2948
                                   errors.ECODE_INVAL)
2949

    
2950
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
2951

    
2952
    # if vg_name not None, checks given volume group on all nodes
2953
    if self.op.vg_name:
2954
      vglist = self.rpc.call_vg_list(node_list)
2955
      for node in node_list:
2956
        msg = vglist[node].fail_msg
2957
        if msg:
2958
          # ignoring down node
2959
          self.LogWarning("Error while gathering data on node %s"
2960
                          " (ignoring node): %s", node, msg)
2961
          continue
2962
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2963
                                              self.op.vg_name,
2964
                                              constants.MIN_VG_SIZE)
2965
        if vgstatus:
2966
          raise errors.OpPrereqError("Error on node '%s': %s" %
2967
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2968

    
2969
    if self.op.drbd_helper:
2970
      # checks given drbd helper on all nodes
2971
      helpers = self.rpc.call_drbd_helper(node_list)
2972
      for node in node_list:
2973
        ninfo = self.cfg.GetNodeInfo(node)
2974
        if ninfo.offline:
2975
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2976
          continue
2977
        msg = helpers[node].fail_msg
2978
        if msg:
2979
          raise errors.OpPrereqError("Error checking drbd helper on node"
2980
                                     " '%s': %s" % (node, msg),
2981
                                     errors.ECODE_ENVIRON)
2982
        node_helper = helpers[node].payload
2983
        if node_helper != self.op.drbd_helper:
2984
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2985
                                     (node, node_helper), errors.ECODE_ENVIRON)
2986

    
2987
    self.cluster = cluster = self.cfg.GetClusterInfo()
2988
    # validate params changes
2989
    if self.op.beparams:
2990
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2991
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2992

    
2993
    if self.op.ndparams:
2994
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2995
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2996

    
2997
      # TODO: we need a more general way to handle resetting
2998
      # cluster-level parameters to default values
2999
      if self.new_ndparams["oob_program"] == "":
3000
        self.new_ndparams["oob_program"] = \
3001
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3002

    
3003
    if self.op.nicparams:
3004
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3005
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3006
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3007
      nic_errors = []
3008

    
3009
      # check all instances for consistency
3010
      for instance in self.cfg.GetAllInstancesInfo().values():
3011
        for nic_idx, nic in enumerate(instance.nics):
3012
          params_copy = copy.deepcopy(nic.nicparams)
3013
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3014

    
3015
          # check parameter syntax
3016
          try:
3017
            objects.NIC.CheckParameterSyntax(params_filled)
3018
          except errors.ConfigurationError, err:
3019
            nic_errors.append("Instance %s, nic/%d: %s" %
3020
                              (instance.name, nic_idx, err))
3021

    
3022
          # if we're moving instances to routed, check that they have an ip
3023
          target_mode = params_filled[constants.NIC_MODE]
3024
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3025
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3026
                              " address" % (instance.name, nic_idx))
3027
      if nic_errors:
3028
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3029
                                   "\n".join(nic_errors))
3030

    
3031
    # hypervisor list/parameters
3032
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3033
    if self.op.hvparams:
3034
      for hv_name, hv_dict in self.op.hvparams.items():
3035
        if hv_name not in self.new_hvparams:
3036
          self.new_hvparams[hv_name] = hv_dict
3037
        else:
3038
          self.new_hvparams[hv_name].update(hv_dict)
3039

    
3040
    # os hypervisor parameters
3041
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3042
    if self.op.os_hvp:
3043
      for os_name, hvs in self.op.os_hvp.items():
3044
        if os_name not in self.new_os_hvp:
3045
          self.new_os_hvp[os_name] = hvs
3046
        else:
3047
          for hv_name, hv_dict in hvs.items():
3048
            if hv_name not in self.new_os_hvp[os_name]:
3049
              self.new_os_hvp[os_name][hv_name] = hv_dict
3050
            else:
3051
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3052

    
3053
    # os parameters
3054
    self.new_osp = objects.FillDict(cluster.osparams, {})
3055
    if self.op.osparams:
3056
      for os_name, osp in self.op.osparams.items():
3057
        if os_name not in self.new_osp:
3058
          self.new_osp[os_name] = {}
3059

    
3060
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3061
                                                  use_none=True)
3062

    
3063
        if not self.new_osp[os_name]:
3064
          # we removed all parameters
3065
          del self.new_osp[os_name]
3066
        else:
3067
          # check the parameter validity (remote check)
3068
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3069
                         os_name, self.new_osp[os_name])
3070

    
3071
    # changes to the hypervisor list
3072
    if self.op.enabled_hypervisors is not None:
3073
      self.hv_list = self.op.enabled_hypervisors
3074
      for hv in self.hv_list:
3075
        # if the hypervisor doesn't already exist in the cluster
3076
        # hvparams, we initialize it to empty, and then (in both
3077
        # cases) we make sure to fill the defaults, as we might not
3078
        # have a complete defaults list if the hypervisor wasn't
3079
        # enabled before
3080
        if hv not in new_hvp:
3081
          new_hvp[hv] = {}
3082
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3083
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3084
    else:
3085
      self.hv_list = cluster.enabled_hypervisors
3086

    
3087
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3088
      # either the enabled list has changed, or the parameters have, validate
3089
      for hv_name, hv_params in self.new_hvparams.items():
3090
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3091
            (self.op.enabled_hypervisors and
3092
             hv_name in self.op.enabled_hypervisors)):
3093
          # either this is a new hypervisor, or its parameters have changed
3094
          hv_class = hypervisor.GetHypervisor(hv_name)
3095
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3096
          hv_class.CheckParameterSyntax(hv_params)
3097
          _CheckHVParams(self, node_list, hv_name, hv_params)
3098

    
3099
    if self.op.os_hvp:
3100
      # no need to check any newly-enabled hypervisors, since the
3101
      # defaults have already been checked in the above code-block
3102
      for os_name, os_hvp in self.new_os_hvp.items():
3103
        for hv_name, hv_params in os_hvp.items():
3104
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3105
          # we need to fill in the new os_hvp on top of the actual hv_p
3106
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3107
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3108
          hv_class = hypervisor.GetHypervisor(hv_name)
3109
          hv_class.CheckParameterSyntax(new_osp)
3110
          _CheckHVParams(self, node_list, hv_name, new_osp)
3111

    
3112
    if self.op.default_iallocator:
3113
      alloc_script = utils.FindFile(self.op.default_iallocator,
3114
                                    constants.IALLOCATOR_SEARCH_PATH,
3115
                                    os.path.isfile)
3116
      if alloc_script is None:
3117
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3118
                                   " specified" % self.op.default_iallocator,
3119
                                   errors.ECODE_INVAL)
3120

    
3121
  def Exec(self, feedback_fn):
3122
    """Change the parameters of the cluster.
3123

3124
    """
3125
    if self.op.vg_name is not None:
3126
      new_volume = self.op.vg_name
3127
      if not new_volume:
3128
        new_volume = None
3129
      if new_volume != self.cfg.GetVGName():
3130
        self.cfg.SetVGName(new_volume)
3131
      else:
3132
        feedback_fn("Cluster LVM configuration already in desired"
3133
                    " state, not changing")
3134
    if self.op.drbd_helper is not None:
3135
      new_helper = self.op.drbd_helper
3136
      if not new_helper:
3137
        new_helper = None
3138
      if new_helper != self.cfg.GetDRBDHelper():
3139
        self.cfg.SetDRBDHelper(new_helper)
3140
      else:
3141
        feedback_fn("Cluster DRBD helper already in desired state,"
3142
                    " not changing")
3143
    if self.op.hvparams:
3144
      self.cluster.hvparams = self.new_hvparams
3145
    if self.op.os_hvp:
3146
      self.cluster.os_hvp = self.new_os_hvp
3147
    if self.op.enabled_hypervisors is not None:
3148
      self.cluster.hvparams = self.new_hvparams
3149
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3150
    if self.op.beparams:
3151
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3152
    if self.op.nicparams:
3153
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3154
    if self.op.osparams:
3155
      self.cluster.osparams = self.new_osp
3156
    if self.op.ndparams:
3157
      self.cluster.ndparams = self.new_ndparams
3158

    
3159
    if self.op.candidate_pool_size is not None:
3160
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3161
      # we need to update the pool size here, otherwise the save will fail
3162
      _AdjustCandidatePool(self, [])
3163

    
3164
    if self.op.maintain_node_health is not None:
3165
      self.cluster.maintain_node_health = self.op.maintain_node_health
3166

    
3167
    if self.op.prealloc_wipe_disks is not None:
3168
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3169

    
3170
    if self.op.add_uids is not None:
3171
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3172

    
3173
    if self.op.remove_uids is not None:
3174
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3175

    
3176
    if self.op.uid_pool is not None:
3177
      self.cluster.uid_pool = self.op.uid_pool
3178

    
3179
    if self.op.default_iallocator is not None:
3180
      self.cluster.default_iallocator = self.op.default_iallocator
3181

    
3182
    if self.op.reserved_lvs is not None:
3183
      self.cluster.reserved_lvs = self.op.reserved_lvs
3184

    
3185
    def helper_os(aname, mods, desc):
3186
      desc += " OS list"
3187
      lst = getattr(self.cluster, aname)
3188
      for key, val in mods:
3189
        if key == constants.DDM_ADD:
3190
          if val in lst:
3191
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3192
          else:
3193
            lst.append(val)
3194
        elif key == constants.DDM_REMOVE:
3195
          if val in lst:
3196
            lst.remove(val)
3197
          else:
3198
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3199
        else:
3200
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3201

    
3202
    if self.op.hidden_os:
3203
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3204

    
3205
    if self.op.blacklisted_os:
3206
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3207

    
3208
    if self.op.master_netdev:
3209
      master = self.cfg.GetMasterNode()
3210
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3211
                  self.cluster.master_netdev)
3212
      result = self.rpc.call_node_stop_master(master, False)
3213
      result.Raise("Could not disable the master ip")
3214
      feedback_fn("Changing master_netdev from %s to %s" %
3215
                  (self.cluster.master_netdev, self.op.master_netdev))
3216
      self.cluster.master_netdev = self.op.master_netdev
3217

    
3218
    self.cfg.Update(self.cluster, feedback_fn)
3219

    
3220
    if self.op.master_netdev:
3221
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3222
                  self.op.master_netdev)
3223
      result = self.rpc.call_node_start_master(master, False, False)
3224
      if result.fail_msg:
3225
        self.LogWarning("Could not re-enable the master ip on"
3226
                        " the master, please restart manually: %s",
3227
                        result.fail_msg)
3228

    
3229

    
3230
def _UploadHelper(lu, nodes, fname):
3231
  """Helper for uploading a file and showing warnings.
3232

3233
  """
3234
  if os.path.exists(fname):
3235
    result = lu.rpc.call_upload_file(nodes, fname)
3236
    for to_node, to_result in result.items():
3237
      msg = to_result.fail_msg
3238
      if msg:
3239
        msg = ("Copy of file %s to node %s failed: %s" %
3240
               (fname, to_node, msg))
3241
        lu.proc.LogWarning(msg)
3242

    
3243

    
3244
def _ComputeAncillaryFiles(cluster, redist):
3245
  """Compute files external to Ganeti which need to be consistent.
3246

3247
  @type redist: boolean
3248
  @param redist: Whether to include files which need to be redistributed
3249

3250
  """
3251
  # Compute files for all nodes
3252
  files_all = set([
3253
    constants.SSH_KNOWN_HOSTS_FILE,
3254
    constants.CONFD_HMAC_KEY,
3255
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3256
    ])
3257

    
3258
  if not redist:
3259
    files_all.update(constants.ALL_CERT_FILES)
3260
    files_all.update(ssconf.SimpleStore().GetFileList())
3261

    
3262
  if cluster.modify_etc_hosts:
3263
    files_all.add(constants.ETC_HOSTS)
3264

    
3265
  # Files which must either exist on all nodes or on none
3266
  files_all_opt = set([
3267
    constants.RAPI_USERS_FILE,
3268
    ])
3269

    
3270
  # Files which should only be on master candidates
3271
  files_mc = set()
3272
  if not redist:
3273
    files_mc.add(constants.CLUSTER_CONF_FILE)
3274

    
3275
  # Files which should only be on VM-capable nodes
3276
  files_vm = set(filename
3277
    for hv_name in cluster.enabled_hypervisors
3278
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3279

    
3280
  # Filenames must be unique
3281
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3282
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3283
         "Found file listed in more than one file list"
3284

    
3285
  return (files_all, files_all_opt, files_mc, files_vm)
3286

    
3287

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

3291
  ConfigWriter takes care of distributing the config and ssconf files, but
3292
  there are more files which should be distributed to all nodes. This function
3293
  makes sure those are copied.
3294

3295
  @param lu: calling logical unit
3296
  @param additional_nodes: list of nodes not in the config to distribute to
3297
  @type additional_vm: boolean
3298
  @param additional_vm: whether the additional nodes are vm-capable or not
3299

3300
  """
3301
  # Gather target nodes
3302
  cluster = lu.cfg.GetClusterInfo()
3303
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3304

    
3305
  online_nodes = lu.cfg.GetOnlineNodeList()
3306
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3307

    
3308
  if additional_nodes is not None:
3309
    online_nodes.extend(additional_nodes)
3310
    if additional_vm:
3311
      vm_nodes.extend(additional_nodes)
3312

    
3313
  # Never distribute to master node
3314
  for nodelist in [online_nodes, vm_nodes]:
3315
    if master_info.name in nodelist:
3316
      nodelist.remove(master_info.name)
3317

    
3318
  # Gather file lists
3319
  (files_all, files_all_opt, files_mc, files_vm) = \
3320
    _ComputeAncillaryFiles(cluster, True)
3321

    
3322
  # Never re-distribute configuration file from here
3323
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3324
              constants.CLUSTER_CONF_FILE in files_vm)
3325
  assert not files_mc, "Master candidates not handled in this function"
3326

    
3327
  filemap = [
3328
    (online_nodes, files_all),
3329
    (online_nodes, files_all_opt),
3330
    (vm_nodes, files_vm),
3331
    ]
3332

    
3333
  # Upload the files
3334
  for (node_list, files) in filemap:
3335
    for fname in files:
3336
      _UploadHelper(lu, node_list, fname)
3337

    
3338

    
3339
class LUClusterRedistConf(NoHooksLU):
3340
  """Force the redistribution of cluster configuration.
3341

3342
  This is a very simple LU.
3343

3344
  """
3345
  REQ_BGL = False
3346

    
3347
  def ExpandNames(self):
3348
    self.needed_locks = {
3349
      locking.LEVEL_NODE: locking.ALL_SET,
3350
    }
3351
    self.share_locks[locking.LEVEL_NODE] = 1
3352

    
3353
  def Exec(self, feedback_fn):
3354
    """Redistribute the configuration.
3355

3356
    """
3357
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3358
    _RedistributeAncillaryFiles(self)
3359

    
3360

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

3364
  """
3365
  if not instance.disks or disks is not None and not disks:
3366
    return True
3367

    
3368
  disks = _ExpandCheckDisks(instance, disks)
3369

    
3370
  if not oneshot:
3371
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3372

    
3373
  node = instance.primary_node
3374

    
3375
  for dev in disks:
3376
    lu.cfg.SetDiskID(dev, node)
3377

    
3378
  # TODO: Convert to utils.Retry
3379

    
3380
  retries = 0
3381
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3382
  while True:
3383
    max_time = 0
3384
    done = True
3385
    cumul_degraded = False
3386
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3387
    msg = rstats.fail_msg
3388
    if msg:
3389
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3390
      retries += 1
3391
      if retries >= 10:
3392
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3393
                                 " aborting." % node)
3394
      time.sleep(6)
3395
      continue
3396
    rstats = rstats.payload
3397
    retries = 0
3398
    for i, mstat in enumerate(rstats):
3399
      if mstat is None:
3400
        lu.LogWarning("Can't compute data for node %s/%s",
3401
                           node, disks[i].iv_name)
3402
        continue
3403

    
3404
      cumul_degraded = (cumul_degraded or
3405
                        (mstat.is_degraded and mstat.sync_percent is None))
3406
      if mstat.sync_percent is not None:
3407
        done = False
3408
        if mstat.estimated_time is not None:
3409
          rem_time = ("%s remaining (estimated)" %
3410
                      utils.FormatSeconds(mstat.estimated_time))
3411
          max_time = mstat.estimated_time
3412
        else:
3413
          rem_time = "no time estimate"
3414
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3415
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3416

    
3417
    # if we're done but degraded, let's do a few small retries, to
3418
    # make sure we see a stable and not transient situation; therefore
3419
    # we force restart of the loop
3420
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3421
      logging.info("Degraded disks found, %d retries left", degr_retries)
3422
      degr_retries -= 1
3423
      time.sleep(1)
3424
      continue
3425

    
3426
    if done or oneshot:
3427
      break
3428

    
3429
    time.sleep(min(60, max_time))
3430

    
3431
  if done:
3432
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3433
  return not cumul_degraded
3434

    
3435

    
3436
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3437
  """Check that mirrors are not degraded.
3438

3439
  The ldisk parameter, if True, will change the test from the
3440
  is_degraded attribute (which represents overall non-ok status for
3441
  the device(s)) to the ldisk (representing the local storage status).
3442

3443
  """
3444
  lu.cfg.SetDiskID(dev, node)
3445

    
3446
  result = True
3447

    
3448
  if on_primary or dev.AssembleOnSecondary():
3449
    rstats = lu.rpc.call_blockdev_find(node, dev)
3450
    msg = rstats.fail_msg
3451
    if msg:
3452
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3453
      result = False
3454
    elif not rstats.payload:
3455
      lu.LogWarning("Can't find disk on node %s", node)
3456
      result = False
3457
    else:
3458
      if ldisk:
3459
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3460
      else:
3461
        result = result and not rstats.payload.is_degraded
3462

    
3463
  if dev.children:
3464
    for child in dev.children:
3465
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3466

    
3467
  return result
3468

    
3469

    
3470
class LUOobCommand(NoHooksLU):
3471
  """Logical unit for OOB handling.
3472

3473
  """
3474
  REG_BGL = False
3475
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3476

    
3477
  def ExpandNames(self):
3478
    """Gather locks we need.
3479

3480
    """
3481
    if self.op.node_names:
3482
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3483
      lock_names = self.op.node_names
3484
    else:
3485
      lock_names = locking.ALL_SET
3486

    
3487
    self.needed_locks = {
3488
      locking.LEVEL_NODE: lock_names,
3489
      }
3490

    
3491
  def CheckPrereq(self):
3492
    """Check prerequisites.
3493

3494
    This checks:
3495
     - the node exists in the configuration
3496
     - OOB is supported
3497

3498
    Any errors are signaled by raising errors.OpPrereqError.
3499

3500
    """
3501
    self.nodes = []
3502
    self.master_node = self.cfg.GetMasterNode()
3503

    
3504
    assert self.op.power_delay >= 0.0
3505

    
3506
    if self.op.node_names:
3507
      if (self.op.command in self._SKIP_MASTER and
3508
          self.master_node in self.op.node_names):
3509
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3510
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3511

    
3512
        if master_oob_handler:
3513
          additional_text = ("run '%s %s %s' if you want to operate on the"
3514
                             " master regardless") % (master_oob_handler,
3515
                                                      self.op.command,
3516
                                                      self.master_node)
3517
        else:
3518
          additional_text = "it does not support out-of-band operations"
3519

    
3520
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3521
                                    " allowed for %s; %s") %
3522
                                   (self.master_node, self.op.command,
3523
                                    additional_text), errors.ECODE_INVAL)
3524
    else:
3525
      self.op.node_names = self.cfg.GetNodeList()
3526
      if self.op.command in self._SKIP_MASTER:
3527
        self.op.node_names.remove(self.master_node)
3528

    
3529
    if self.op.command in self._SKIP_MASTER:
3530
      assert self.master_node not in self.op.node_names
3531

    
3532
    for node_name in self.op.node_names:
3533
      node = self.cfg.GetNodeInfo(node_name)
3534

    
3535
      if node is None:
3536
        raise errors.OpPrereqError("Node %s not found" % node_name,
3537
                                   errors.ECODE_NOENT)
3538
      else:
3539
        self.nodes.append(node)
3540

    
3541
      if (not self.op.ignore_status and
3542
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3543
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3544
                                    " not marked offline") % node_name,
3545
                                   errors.ECODE_STATE)
3546

    
3547
  def Exec(self, feedback_fn):
3548
    """Execute OOB and return result if we expect any.
3549

3550
    """
3551
    master_node = self.master_node
3552
    ret = []
3553

    
3554
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3555
                                              key=lambda node: node.name)):
3556
      node_entry = [(constants.RS_NORMAL, node.name)]
3557
      ret.append(node_entry)
3558

    
3559
      oob_program = _SupportsOob(self.cfg, node)
3560

    
3561
      if not oob_program:
3562
        node_entry.append((constants.RS_UNAVAIL, None))
3563
        continue
3564

    
3565
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3566
                   self.op.command, oob_program, node.name)
3567
      result = self.rpc.call_run_oob(master_node, oob_program,
3568
                                     self.op.command, node.name,
3569
                                     self.op.timeout)
3570

    
3571
      if result.fail_msg:
3572
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3573
                        node.name, result.fail_msg)
3574
        node_entry.append((constants.RS_NODATA, None))
3575
      else:
3576
        try:
3577
          self._CheckPayload(result)
3578
        except errors.OpExecError, err:
3579
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3580
                          node.name, err)
3581
          node_entry.append((constants.RS_NODATA, None))
3582
        else:
3583
          if self.op.command == constants.OOB_HEALTH:
3584
            # For health we should log important events
3585
            for item, status in result.payload:
3586
              if status in [constants.OOB_STATUS_WARNING,
3587
                            constants.OOB_STATUS_CRITICAL]:
3588
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3589
                                item, node.name, status)
3590

    
3591
          if self.op.command == constants.OOB_POWER_ON:
3592
            node.powered = True
3593
          elif self.op.command == constants.OOB_POWER_OFF:
3594
            node.powered = False
3595
          elif self.op.command == constants.OOB_POWER_STATUS:
3596
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3597
            if powered != node.powered:
3598
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3599
                               " match actual power state (%s)"), node.powered,
3600
                              node.name, powered)
3601

    
3602
          # For configuration changing commands we should update the node
3603
          if self.op.command in (constants.OOB_POWER_ON,
3604
                                 constants.OOB_POWER_OFF):
3605
            self.cfg.Update(node, feedback_fn)
3606

    
3607
          node_entry.append((constants.RS_NORMAL, result.payload))
3608

    
3609
          if (self.op.command == constants.OOB_POWER_ON and
3610
              idx < len(self.nodes) - 1):
3611
            time.sleep(self.op.power_delay)
3612

    
3613
    return ret
3614

    
3615
  def _CheckPayload(self, result):
3616
    """Checks if the payload is valid.
3617

3618
    @param result: RPC result
3619
    @raises errors.OpExecError: If payload is not valid
3620

3621
    """
3622
    errs = []
3623
    if self.op.command == constants.OOB_HEALTH:
3624
      if not isinstance(result.payload, list):
3625
        errs.append("command 'health' is expected to return a list but got %s" %
3626
                    type(result.payload))
3627
      else:
3628
        for item, status in result.payload:
3629
          if status not in constants.OOB_STATUSES:
3630
            errs.append("health item '%s' has invalid status '%s'" %
3631
                        (item, status))
3632

    
3633
    if self.op.command == constants.OOB_POWER_STATUS:
3634
      if not isinstance(result.payload, dict):
3635
        errs.append("power-status is expected to return a dict but got %s" %
3636
                    type(result.payload))
3637

    
3638
    if self.op.command in [
3639
        constants.OOB_POWER_ON,
3640
        constants.OOB_POWER_OFF,
3641
        constants.OOB_POWER_CYCLE,
3642
        ]:
3643
      if result.payload is not None:
3644
        errs.append("%s is expected to not return payload but got '%s'" %
3645
                    (self.op.command, result.payload))
3646

    
3647
    if errs:
3648
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3649
                               utils.CommaJoin(errs))
3650

    
3651
class _OsQuery(_QueryBase):
3652
  FIELDS = query.OS_FIELDS
3653

    
3654
  def ExpandNames(self, lu):
3655
    # Lock all nodes in shared mode
3656
    # Temporary removal of locks, should be reverted later
3657
    # TODO: reintroduce locks when they are lighter-weight
3658
    lu.needed_locks = {}
3659
    #self.share_locks[locking.LEVEL_NODE] = 1
3660
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3661

    
3662
    # The following variables interact with _QueryBase._GetNames
3663
    if self.names:
3664
      self.wanted = self.names
3665
    else:
3666
      self.wanted = locking.ALL_SET
3667

    
3668
    self.do_locking = self.use_locking
3669

    
3670
  def DeclareLocks(self, lu, level):
3671
    pass
3672

    
3673
  @staticmethod
3674
  def _DiagnoseByOS(rlist):
3675
    """Remaps a per-node return list into an a per-os per-node dictionary
3676

3677
    @param rlist: a map with node names as keys and OS objects as values
3678

3679
    @rtype: dict
3680
    @return: a dictionary with osnames as keys and as value another
3681
        map, with nodes as keys and tuples of (path, status, diagnose,
3682
        variants, parameters, api_versions) as values, eg::
3683

3684
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3685
                                     (/srv/..., False, "invalid api")],
3686
                           "node2": [(/srv/..., True, "", [], [])]}
3687
          }
3688

3689
    """
3690
    all_os = {}
3691
    # we build here the list of nodes that didn't fail the RPC (at RPC
3692
    # level), so that nodes with a non-responding node daemon don't
3693
    # make all OSes invalid
3694
    good_nodes = [node_name for node_name in rlist
3695
                  if not rlist[node_name].fail_msg]
3696
    for node_name, nr in rlist.items():
3697
      if nr.fail_msg or not nr.payload:
3698
        continue
3699
      for (name, path, status, diagnose, variants,
3700
           params, api_versions) in nr.payload:
3701
        if name not in all_os:
3702
          # build a list of nodes for this os containing empty lists
3703
          # for each node in node_list
3704
          all_os[name] = {}
3705
          for nname in good_nodes:
3706
            all_os[name][nname] = []
3707
        # convert params from [name, help] to (name, help)
3708
        params = [tuple(v) for v in params]
3709
        all_os[name][node_name].append((path, status, diagnose,
3710
                                        variants, params, api_versions))
3711
    return all_os
3712

    
3713
  def _GetQueryData(self, lu):
3714
    """Computes the list of nodes and their attributes.
3715

3716
    """
3717
    # Locking is not used
3718
    assert not (compat.any(lu.glm.is_owned(level)
3719
                           for level in locking.LEVELS
3720
                           if level != locking.LEVEL_CLUSTER) or
3721
                self.do_locking or self.use_locking)
3722

    
3723
    valid_nodes = [node.name
3724
                   for node in lu.cfg.GetAllNodesInfo().values()
3725
                   if not node.offline and node.vm_capable]
3726
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3727
    cluster = lu.cfg.GetClusterInfo()
3728

    
3729
    data = {}
3730

    
3731
    for (os_name, os_data) in pol.items():
3732
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3733
                          hidden=(os_name in cluster.hidden_os),
3734
                          blacklisted=(os_name in cluster.blacklisted_os))
3735

    
3736
      variants = set()
3737
      parameters = set()
3738
      api_versions = set()
3739

    
3740
      for idx, osl in enumerate(os_data.values()):
3741
        info.valid = bool(info.valid and osl and osl[0][1])
3742
        if not info.valid:
3743
          break
3744

    
3745
        (node_variants, node_params, node_api) = osl[0][3:6]
3746
        if idx == 0:
3747
          # First entry
3748
          variants.update(node_variants)
3749
          parameters.update(node_params)
3750
          api_versions.update(node_api)
3751
        else:
3752
          # Filter out inconsistent values
3753
          variants.intersection_update(node_variants)
3754
          parameters.intersection_update(node_params)
3755
          api_versions.intersection_update(node_api)
3756

    
3757
      info.variants = list(variants)
3758
      info.parameters = list(parameters)
3759
      info.api_versions = list(api_versions)
3760

    
3761
      data[os_name] = info
3762

    
3763
    # Prepare data in requested order
3764
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3765
            if name in data]
3766

    
3767

    
3768
class LUOsDiagnose(NoHooksLU):
3769
  """Logical unit for OS diagnose/query.
3770

3771
  """
3772
  REQ_BGL = False
3773

    
3774
  @staticmethod
3775
  def _BuildFilter(fields, names):
3776
    """Builds a filter for querying OSes.
3777

3778
    """
3779
    name_filter = qlang.MakeSimpleFilter("name", names)
3780

    
3781
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
3782
    # respective field is not requested
3783
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
3784
                     for fname in ["hidden", "blacklisted"]
3785
                     if fname not in fields]
3786
    if "valid" not in fields:
3787
      status_filter.append([qlang.OP_TRUE, "valid"])
3788

    
3789
    if status_filter:
3790
      status_filter.insert(0, qlang.OP_AND)
3791
    else:
3792
      status_filter = None
3793

    
3794
    if name_filter and status_filter:
3795
      return [qlang.OP_AND, name_filter, status_filter]
3796
    elif name_filter:
3797
      return name_filter
3798
    else:
3799
      return status_filter
3800

    
3801
  def CheckArguments(self):
3802
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
3803
                       self.op.output_fields, False)
3804

    
3805
  def ExpandNames(self):
3806
    self.oq.ExpandNames(self)
3807

    
3808
  def Exec(self, feedback_fn):
3809
    return self.oq.OldStyleQuery(self)
3810

    
3811

    
3812
class LUNodeRemove(LogicalUnit):
3813
  """Logical unit for removing a node.
3814

3815
  """
3816
  HPATH = "node-remove"
3817
  HTYPE = constants.HTYPE_NODE
3818

    
3819
  def BuildHooksEnv(self):
3820
    """Build hooks env.
3821

3822
    This doesn't run on the target node in the pre phase as a failed
3823
    node would then be impossible to remove.
3824

3825
    """
3826
    return {
3827
      "OP_TARGET": self.op.node_name,
3828
      "NODE_NAME": self.op.node_name,
3829
      }
3830

    
3831
  def BuildHooksNodes(self):
3832
    """Build hooks nodes.
3833

3834
    """
3835
    all_nodes = self.cfg.GetNodeList()
3836
    try:
3837
      all_nodes.remove(self.op.node_name)
3838
    except ValueError:
3839
      logging.warning("Node '%s', which is about to be removed, was not found"
3840
                      " in the list of all nodes", self.op.node_name)
3841
    return (all_nodes, all_nodes)
3842

    
3843
  def CheckPrereq(self):
3844
    """Check prerequisites.
3845

3846
    This checks:
3847
     - the node exists in the configuration
3848
     - it does not have primary or secondary instances
3849
     - it's not the master
3850

3851
    Any errors are signaled by raising errors.OpPrereqError.
3852

3853
    """
3854
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3855
    node = self.cfg.GetNodeInfo(self.op.node_name)
3856
    assert node is not None
3857

    
3858
    instance_list = self.cfg.GetInstanceList()
3859

    
3860
    masternode = self.cfg.GetMasterNode()
3861
    if node.name == masternode:
3862
      raise errors.OpPrereqError("Node is the master node, failover to another"
3863
                                 " node is required", errors.ECODE_INVAL)
3864

    
3865
    for instance_name in instance_list:
3866
      instance = self.cfg.GetInstanceInfo(instance_name)
3867
      if node.name in instance.all_nodes:
3868
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3869
                                   " please remove first" % instance_name,
3870
                                   errors.ECODE_INVAL)
3871
    self.op.node_name = node.name
3872
    self.node = node
3873

    
3874
  def Exec(self, feedback_fn):
3875
    """Removes the node from the cluster.
3876

3877
    """
3878
    node = self.node
3879
    logging.info("Stopping the node daemon and removing configs from node %s",
3880
                 node.name)
3881

    
3882
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3883

    
3884
    # Promote nodes to master candidate as needed
3885
    _AdjustCandidatePool(self, exceptions=[node.name])
3886
    self.context.RemoveNode(node.name)
3887

    
3888
    # Run post hooks on the node before it's removed
3889
    _RunPostHook(self, node.name)
3890

    
3891
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3892
    msg = result.fail_msg
3893
    if msg:
3894
      self.LogWarning("Errors encountered on the remote node while leaving"
3895
                      " the cluster: %s", msg)
3896

    
3897
    # Remove node from our /etc/hosts
3898
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3899
      master_node = self.cfg.GetMasterNode()
3900
      result = self.rpc.call_etc_hosts_modify(master_node,
3901
                                              constants.ETC_HOSTS_REMOVE,
3902
                                              node.name, None)
3903
      result.Raise("Can't update hosts file with new host data")
3904
      _RedistributeAncillaryFiles(self)
3905

    
3906

    
3907
class _NodeQuery(_QueryBase):
3908
  FIELDS = query.NODE_FIELDS
3909

    
3910
  def ExpandNames(self, lu):
3911
    lu.needed_locks = {}
3912
    lu.share_locks[locking.LEVEL_NODE] = 1
3913

    
3914
    if self.names:
3915
      self.wanted = _GetWantedNodes(lu, self.names)
3916
    else:
3917
      self.wanted = locking.ALL_SET
3918

    
3919
    self.do_locking = (self.use_locking and
3920
                       query.NQ_LIVE in self.requested_data)
3921

    
3922
    if self.do_locking:
3923
      # if we don't request only static fields, we need to lock the nodes
3924
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3925

    
3926
  def DeclareLocks(self, lu, level):
3927
    pass
3928

    
3929
  def _GetQueryData(self, lu):
3930
    """Computes the list of nodes and their attributes.
3931

3932
    """
3933
    all_info = lu.cfg.GetAllNodesInfo()
3934

    
3935
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3936

    
3937
    # Gather data as requested
3938
    if query.NQ_LIVE in self.requested_data:
3939
      # filter out non-vm_capable nodes
3940
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3941

    
3942
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3943
                                        lu.cfg.GetHypervisorType())
3944
      live_data = dict((name, nresult.payload)
3945
                       for (name, nresult) in node_data.items()
3946
                       if not nresult.fail_msg and nresult.payload)
3947
    else:
3948
      live_data = None
3949

    
3950
    if query.NQ_INST in self.requested_data:
3951
      node_to_primary = dict([(name, set()) for name in nodenames])
3952
      node_to_secondary = dict([(name, set()) for name in nodenames])
3953

    
3954
      inst_data = lu.cfg.GetAllInstancesInfo()
3955

    
3956
      for inst in inst_data.values():
3957
        if inst.primary_node in node_to_primary:
3958
          node_to_primary[inst.primary_node].add(inst.name)
3959
        for secnode in inst.secondary_nodes:
3960
          if secnode in node_to_secondary:
3961
            node_to_secondary[secnode].add(inst.name)
3962
    else:
3963
      node_to_primary = None
3964
      node_to_secondary = None
3965

    
3966
    if query.NQ_OOB in self.requested_data:
3967
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3968
                         for name, node in all_info.iteritems())
3969
    else:
3970
      oob_support = None
3971

    
3972
    if query.NQ_GROUP in self.requested_data:
3973
      groups = lu.cfg.GetAllNodeGroupsInfo()
3974
    else:
3975
      groups = {}
3976

    
3977
    return query.NodeQueryData([all_info[name] for name in nodenames],
3978
                               live_data, lu.cfg.GetMasterNode(),
3979
                               node_to_primary, node_to_secondary, groups,
3980
                               oob_support, lu.cfg.GetClusterInfo())
3981

    
3982

    
3983
class LUNodeQuery(NoHooksLU):
3984
  """Logical unit for querying nodes.
3985

3986
  """
3987
  # pylint: disable-msg=W0142
3988
  REQ_BGL = False
3989

    
3990
  def CheckArguments(self):
3991
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
3992
                         self.op.output_fields, self.op.use_locking)
3993

    
3994
  def ExpandNames(self):
3995
    self.nq.ExpandNames(self)
3996

    
3997
  def Exec(self, feedback_fn):
3998
    return self.nq.OldStyleQuery(self)
3999

    
4000

    
4001
class LUNodeQueryvols(NoHooksLU):
4002
  """Logical unit for getting volumes on node(s).
4003

4004
  """
4005
  REQ_BGL = False
4006
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4007
  _FIELDS_STATIC = utils.FieldSet("node")
4008

    
4009
  def CheckArguments(self):
4010
    _CheckOutputFields(static=self._FIELDS_STATIC,
4011
                       dynamic=self._FIELDS_DYNAMIC,
4012
                       selected=self.op.output_fields)
4013

    
4014
  def ExpandNames(self):
4015
    self.needed_locks = {}
4016
    self.share_locks[locking.LEVEL_NODE] = 1
4017
    if not self.op.nodes:
4018
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4019
    else:
4020
      self.needed_locks[locking.LEVEL_NODE] = \
4021
        _GetWantedNodes(self, self.op.nodes)
4022

    
4023
  def Exec(self, feedback_fn):
4024
    """Computes the list of nodes and their attributes.
4025

4026
    """
4027
    nodenames = self.glm.list_owned(locking.LEVEL_NODE)
4028
    volumes = self.rpc.call_node_volumes(nodenames)
4029

    
4030
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
4031
             in self.cfg.GetInstanceList()]
4032

    
4033
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
4034

    
4035
    output = []
4036
    for node in nodenames:
4037
      nresult = volumes[node]
4038
      if nresult.offline:
4039
        continue
4040
      msg = nresult.fail_msg
4041
      if msg:
4042
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4043
        continue
4044

    
4045
      node_vols = nresult.payload[:]
4046
      node_vols.sort(key=lambda vol: vol['dev'])
4047

    
4048
      for vol in node_vols:
4049
        node_output = []
4050
        for field in self.op.output_fields:
4051
          if field == "node":
4052
            val = node
4053
          elif field == "phys":
4054
            val = vol['dev']
4055
          elif field == "vg":
4056
            val = vol['vg']
4057
          elif field == "name":
4058
            val = vol['name']
4059
          elif field == "size":
4060
            val = int(float(vol['size']))
4061
          elif field == "instance":
4062
            for inst in ilist:
4063
              if node not in lv_by_node[inst]:
4064
                continue
4065
              if vol['name'] in lv_by_node[inst][node]:
4066
                val = inst.name
4067
                break
4068
            else:
4069
              val = '-'
4070
          else:
4071
            raise errors.ParameterError(field)
4072
          node_output.append(str(val))
4073

    
4074
        output.append(node_output)
4075

    
4076
    return output
4077

    
4078

    
4079
class LUNodeQueryStorage(NoHooksLU):
4080
  """Logical unit for getting information on storage units on node(s).
4081

4082
  """
4083
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4084
  REQ_BGL = False
4085

    
4086
  def CheckArguments(self):
4087
    _CheckOutputFields(static=self._FIELDS_STATIC,
4088
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4089
                       selected=self.op.output_fields)
4090

    
4091
  def ExpandNames(self):
4092
    self.needed_locks = {}
4093
    self.share_locks[locking.LEVEL_NODE] = 1
4094

    
4095
    if self.op.nodes:
4096
      self.needed_locks[locking.LEVEL_NODE] = \
4097
        _GetWantedNodes(self, self.op.nodes)
4098
    else:
4099
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4100

    
4101
  def Exec(self, feedback_fn):
4102
    """Computes the list of nodes and their attributes.
4103

4104
    """
4105
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
4106

    
4107
    # Always get name to sort by
4108
    if constants.SF_NAME in self.op.output_fields:
4109
      fields = self.op.output_fields[:]
4110
    else:
4111
      fields = [constants.SF_NAME] + self.op.output_fields
4112

    
4113
    # Never ask for node or type as it's only known to the LU
4114
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4115
      while extra in fields:
4116
        fields.remove(extra)
4117

    
4118
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4119
    name_idx = field_idx[constants.SF_NAME]
4120

    
4121
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4122
    data = self.rpc.call_storage_list(self.nodes,
4123
                                      self.op.storage_type, st_args,
4124
                                      self.op.name, fields)
4125

    
4126
    result = []
4127

    
4128
    for node in utils.NiceSort(self.nodes):
4129
      nresult = data[node]
4130
      if nresult.offline:
4131
        continue
4132

    
4133
      msg = nresult.fail_msg
4134
      if msg:
4135
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4136
        continue
4137

    
4138
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4139

    
4140
      for name in utils.NiceSort(rows.keys()):
4141
        row = rows[name]
4142

    
4143
        out = []
4144

    
4145
        for field in self.op.output_fields:
4146
          if field == constants.SF_NODE:
4147
            val = node
4148
          elif field == constants.SF_TYPE:
4149
            val = self.op.storage_type
4150
          elif field in field_idx:
4151
            val = row[field_idx[field]]
4152
          else:
4153
            raise errors.ParameterError(field)
4154

    
4155
          out.append(val)
4156

    
4157
        result.append(out)
4158

    
4159
    return result
4160

    
4161

    
4162
class _InstanceQuery(_QueryBase):
4163
  FIELDS = query.INSTANCE_FIELDS
4164

    
4165
  def ExpandNames(self, lu):
4166
    lu.needed_locks = {}
4167
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
4168
    lu.share_locks[locking.LEVEL_NODE] = 1
4169

    
4170
    if self.names:
4171
      self.wanted = _GetWantedInstances(lu, self.names)
4172
    else:
4173
      self.wanted = locking.ALL_SET
4174

    
4175
    self.do_locking = (self.use_locking and
4176
                       query.IQ_LIVE in self.requested_data)
4177
    if self.do_locking:
4178
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4179
      lu.needed_locks[locking.LEVEL_NODE] = []
4180
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4181

    
4182
  def DeclareLocks(self, lu, level):
4183
    if level == locking.LEVEL_NODE and self.do_locking:
4184
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
4185

    
4186
  def _GetQueryData(self, lu):
4187
    """Computes the list of instances and their attributes.
4188

4189
    """
4190
    cluster = lu.cfg.GetClusterInfo()
4191
    all_info = lu.cfg.GetAllInstancesInfo()
4192

    
4193
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4194

    
4195
    instance_list = [all_info[name] for name in instance_names]
4196
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4197
                                        for inst in instance_list)))
4198
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4199
    bad_nodes = []
4200
    offline_nodes = []
4201
    wrongnode_inst = set()
4202

    
4203
    # Gather data as requested
4204
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4205
      live_data = {}
4206
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4207
      for name in nodes:
4208
        result = node_data[name]
4209
        if result.offline:
4210
          # offline nodes will be in both lists
4211
          assert result.fail_msg
4212
          offline_nodes.append(name)
4213
        if result.fail_msg:
4214
          bad_nodes.append(name)
4215
        elif result.payload:
4216
          for inst in result.payload:
4217
            if inst in all_info:
4218
              if all_info[inst].primary_node == name:
4219
                live_data.update(result.payload)
4220
              else:
4221
                wrongnode_inst.add(inst)
4222
            else:
4223
              # orphan instance; we don't list it here as we don't
4224
              # handle this case yet in the output of instance listing
4225
              logging.warning("Orphan instance '%s' found on node %s",
4226
                              inst, name)
4227
        # else no instance is alive
4228
    else:
4229
      live_data = {}
4230

    
4231
    if query.IQ_DISKUSAGE in self.requested_data:
4232
      disk_usage = dict((inst.name,
4233
                         _ComputeDiskSize(inst.disk_template,
4234
                                          [{constants.IDISK_SIZE: disk.size}
4235
                                           for disk in inst.disks]))
4236
                        for inst in instance_list)
4237
    else:
4238
      disk_usage = None
4239

    
4240
    if query.IQ_CONSOLE in self.requested_data:
4241
      consinfo = {}
4242
      for inst in instance_list:
4243
        if inst.name in live_data:
4244
          # Instance is running
4245
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4246
        else:
4247
          consinfo[inst.name] = None
4248
      assert set(consinfo.keys()) == set(instance_names)
4249
    else:
4250
      consinfo = None
4251

    
4252
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4253
                                   disk_usage, offline_nodes, bad_nodes,
4254
                                   live_data, wrongnode_inst, consinfo)
4255

    
4256

    
4257
class LUQuery(NoHooksLU):
4258
  """Query for resources/items of a certain kind.
4259

4260
  """
4261
  # pylint: disable-msg=W0142
4262
  REQ_BGL = False
4263

    
4264
  def CheckArguments(self):
4265
    qcls = _GetQueryImplementation(self.op.what)
4266

    
4267
    self.impl = qcls(self.op.filter, self.op.fields, False)
4268

    
4269
  def ExpandNames(self):
4270
    self.impl.ExpandNames(self)
4271

    
4272
  def DeclareLocks(self, level):
4273
    self.impl.DeclareLocks(self, level)
4274

    
4275
  def Exec(self, feedback_fn):
4276
    return self.impl.NewStyleQuery(self)
4277

    
4278

    
4279
class LUQueryFields(NoHooksLU):
4280
  """Query for resources/items of a certain kind.
4281

4282
  """
4283
  # pylint: disable-msg=W0142
4284
  REQ_BGL = False
4285

    
4286
  def CheckArguments(self):
4287
    self.qcls = _GetQueryImplementation(self.op.what)
4288

    
4289
  def ExpandNames(self):
4290
    self.needed_locks = {}
4291

    
4292
  def Exec(self, feedback_fn):
4293
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4294

    
4295

    
4296
class LUNodeModifyStorage(NoHooksLU):
4297
  """Logical unit for modifying a storage volume on a node.
4298

4299
  """
4300
  REQ_BGL = False
4301

    
4302
  def CheckArguments(self):
4303
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4304

    
4305
    storage_type = self.op.storage_type
4306

    
4307
    try:
4308
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4309
    except KeyError:
4310
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4311
                                 " modified" % storage_type,
4312
                                 errors.ECODE_INVAL)
4313

    
4314
    diff = set(self.op.changes.keys()) - modifiable
4315
    if diff:
4316
      raise errors.OpPrereqError("The following fields can not be modified for"
4317
                                 " storage units of type '%s': %r" %
4318
                                 (storage_type, list(diff)),
4319
                                 errors.ECODE_INVAL)
4320

    
4321
  def ExpandNames(self):
4322
    self.needed_locks = {
4323
      locking.LEVEL_NODE: self.op.node_name,
4324
      }
4325

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

4329
    """
4330
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4331
    result = self.rpc.call_storage_modify(self.op.node_name,
4332
                                          self.op.storage_type, st_args,
4333
                                          self.op.name, self.op.changes)
4334
    result.Raise("Failed to modify storage unit '%s' on %s" %
4335
                 (self.op.name, self.op.node_name))
4336

    
4337

    
4338
class LUNodeAdd(LogicalUnit):
4339
  """Logical unit for adding node to the cluster.
4340

4341
  """
4342
  HPATH = "node-add"
4343
  HTYPE = constants.HTYPE_NODE
4344
  _NFLAGS = ["master_capable", "vm_capable"]
4345

    
4346
  def CheckArguments(self):
4347
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4348
    # validate/normalize the node name
4349
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4350
                                         family=self.primary_ip_family)
4351
    self.op.node_name = self.hostname.name
4352

    
4353
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4354
      raise errors.OpPrereqError("Cannot readd the master node",
4355
                                 errors.ECODE_STATE)
4356

    
4357
    if self.op.readd and self.op.group:
4358
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4359
                                 " being readded", errors.ECODE_INVAL)
4360

    
4361
  def BuildHooksEnv(self):
4362
    """Build hooks env.
4363

4364
    This will run on all nodes before, and on all nodes + the new node after.
4365

4366
    """
4367
    return {
4368
      "OP_TARGET": self.op.node_name,
4369
      "NODE_NAME": self.op.node_name,
4370
      "NODE_PIP": self.op.primary_ip,
4371
      "NODE_SIP": self.op.secondary_ip,
4372
      "MASTER_CAPABLE": str(self.op.master_capable),
4373
      "VM_CAPABLE": str(self.op.vm_capable),
4374
      }
4375

    
4376
  def BuildHooksNodes(self):
4377
    """Build hooks nodes.
4378

4379
    """
4380
    # Exclude added node
4381
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4382
    post_nodes = pre_nodes + [self.op.node_name, ]
4383

    
4384
    return (pre_nodes, post_nodes)
4385

    
4386
  def CheckPrereq(self):
4387
    """Check prerequisites.
4388

4389
    This checks:
4390
     - the new node is not already in the config
4391
     - it is resolvable
4392
     - its parameters (single/dual homed) matches the cluster
4393

4394
    Any errors are signaled by raising errors.OpPrereqError.
4395

4396
    """
4397
    cfg = self.cfg
4398
    hostname = self.hostname
4399
    node = hostname.name
4400
    primary_ip = self.op.primary_ip = hostname.ip
4401
    if self.op.secondary_ip is None:
4402
      if self.primary_ip_family == netutils.IP6Address.family:
4403
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4404
                                   " IPv4 address must be given as secondary",
4405
                                   errors.ECODE_INVAL)
4406
      self.op.secondary_ip = primary_ip
4407

    
4408
    secondary_ip = self.op.secondary_ip
4409
    if not netutils.IP4Address.IsValid(secondary_ip):
4410
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4411
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4412

    
4413
    node_list = cfg.GetNodeList()
4414
    if not self.op.readd and node in node_list:
4415
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4416
                                 node, errors.ECODE_EXISTS)
4417
    elif self.op.readd and node not in node_list:
4418
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4419
                                 errors.ECODE_NOENT)
4420

    
4421
    self.changed_primary_ip = False
4422

    
4423
    for existing_node_name in node_list:
4424
      existing_node = cfg.GetNodeInfo(existing_node_name)
4425

    
4426
      if self.op.readd and node == existing_node_name:
4427
        if existing_node.secondary_ip != secondary_ip:
4428
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4429
                                     " address configuration as before",
4430
                                     errors.ECODE_INVAL)
4431
        if existing_node.primary_ip != primary_ip:
4432
          self.changed_primary_ip = True
4433

    
4434
        continue
4435

    
4436
      if (existing_node.primary_ip == primary_ip or
4437
          existing_node.secondary_ip == primary_ip or
4438
          existing_node.primary_ip == secondary_ip or
4439
          existing_node.secondary_ip == secondary_ip):
4440
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4441
                                   " existing node %s" % existing_node.name,
4442
                                   errors.ECODE_NOTUNIQUE)
4443

    
4444
    # After this 'if' block, None is no longer a valid value for the
4445
    # _capable op attributes
4446
    if self.op.readd:
4447
      old_node = self.cfg.GetNodeInfo(node)
4448
      assert old_node is not None, "Can't retrieve locked node %s" % node
4449
      for attr in self._NFLAGS:
4450
        if getattr(self.op, attr) is None:
4451
          setattr(self.op, attr, getattr(old_node, attr))
4452
    else:
4453
      for attr in self._NFLAGS:
4454
        if getattr(self.op, attr) is None:
4455
          setattr(self.op, attr, True)
4456

    
4457
    if self.op.readd and not self.op.vm_capable:
4458
      pri, sec = cfg.GetNodeInstances(node)
4459
      if pri or sec:
4460
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4461
                                   " flag set to false, but it already holds"
4462
                                   " instances" % node,
4463
                                   errors.ECODE_STATE)
4464

    
4465
    # check that the type of the node (single versus dual homed) is the
4466
    # same as for the master
4467
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4468
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4469
    newbie_singlehomed = secondary_ip == primary_ip
4470
    if master_singlehomed != newbie_singlehomed:
4471
      if master_singlehomed:
4472
        raise errors.OpPrereqError("The master has no secondary ip but the"
4473
                                   " new node has one",
4474
                                   errors.ECODE_INVAL)
4475
      else:
4476
        raise errors.OpPrereqError("The master has a secondary ip but the"
4477
                                   " new node doesn't have one",
4478
                                   errors.ECODE_INVAL)
4479

    
4480
    # checks reachability
4481
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4482
      raise errors.OpPrereqError("Node not reachable by ping",
4483
                                 errors.ECODE_ENVIRON)
4484

    
4485
    if not newbie_singlehomed:
4486
      # check reachability from my secondary ip to newbie's secondary ip
4487
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4488
                           source=myself.secondary_ip):
4489
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4490
                                   " based ping to node daemon port",
4491
                                   errors.ECODE_ENVIRON)
4492

    
4493
    if self.op.readd:
4494
      exceptions = [node]
4495
    else:
4496
      exceptions = []
4497

    
4498
    if self.op.master_capable:
4499
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4500
    else:
4501
      self.master_candidate = False
4502

    
4503
    if self.op.readd:
4504
      self.new_node = old_node
4505
    else:
4506
      node_group = cfg.LookupNodeGroup(self.op.group)
4507
      self.new_node = objects.Node(name=node,
4508
                                   primary_ip=primary_ip,
4509
                                   secondary_ip=secondary_ip,
4510
                                   master_candidate=self.master_candidate,
4511
                                   offline=False, drained=False,
4512
                                   group=node_group)
4513

    
4514
    if self.op.ndparams:
4515
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4516

    
4517
  def Exec(self, feedback_fn):
4518
    """Adds the new node to the cluster.
4519

4520
    """
4521
    new_node = self.new_node
4522
    node = new_node.name
4523

    
4524
    # We adding a new node so we assume it's powered
4525
    new_node.powered = True
4526

    
4527
    # for re-adds, reset the offline/drained/master-candidate flags;
4528
    # we need to reset here, otherwise offline would prevent RPC calls
4529
    # later in the procedure; this also means that if the re-add
4530
    # fails, we are left with a non-offlined, broken node
4531
    if self.op.readd:
4532
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4533
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4534
      # if we demote the node, we do cleanup later in the procedure
4535
      new_node.master_candidate = self.master_candidate
4536
      if self.changed_primary_ip:
4537
        new_node.primary_ip = self.op.primary_ip
4538

    
4539
    # copy the master/vm_capable flags
4540
    for attr in self._NFLAGS:
4541
      setattr(new_node, attr, getattr(self.op, attr))
4542

    
4543
    # notify the user about any possible mc promotion
4544
    if new_node.master_candidate:
4545
      self.LogInfo("Node will be a master candidate")
4546

    
4547
    if self.op.ndparams:
4548
      new_node.ndparams = self.op.ndparams
4549
    else:
4550
      new_node.ndparams = {}
4551

    
4552
    # check connectivity
4553
    result = self.rpc.call_version([node])[node]
4554
    result.Raise("Can't get version information from node %s" % node)
4555
    if constants.PROTOCOL_VERSION == result.payload:
4556
      logging.info("Communication to node %s fine, sw version %s match",
4557
                   node, result.payload)
4558
    else:
4559
      raise errors.OpExecError("Version mismatch master version %s,"
4560
                               " node version %s" %
4561
                               (constants.PROTOCOL_VERSION, result.payload))
4562

    
4563
    # Add node to our /etc/hosts, and add key to known_hosts
4564
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4565
      master_node = self.cfg.GetMasterNode()
4566
      result = self.rpc.call_etc_hosts_modify(master_node,
4567
                                              constants.ETC_HOSTS_ADD,
4568
                                              self.hostname.name,
4569
                                              self.hostname.ip)
4570
      result.Raise("Can't update hosts file with new host data")
4571

    
4572
    if new_node.secondary_ip != new_node.primary_ip:
4573
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4574
                               False)
4575

    
4576
    node_verify_list = [self.cfg.GetMasterNode()]
4577
    node_verify_param = {
4578
      constants.NV_NODELIST: [node],
4579
      # TODO: do a node-net-test as well?
4580
    }
4581

    
4582
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4583
                                       self.cfg.GetClusterName())
4584
    for verifier in node_verify_list:
4585
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4586
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4587
      if nl_payload:
4588
        for failed in nl_payload:
4589
          feedback_fn("ssh/hostname verification failed"
4590
                      " (checking from %s): %s" %
4591
                      (verifier, nl_payload[failed]))
4592
        raise errors.OpExecError("ssh/hostname verification failed")
4593

    
4594
    if self.op.readd:
4595
      _RedistributeAncillaryFiles(self)
4596
      self.context.ReaddNode(new_node)
4597
      # make sure we redistribute the config
4598
      self.cfg.Update(new_node, feedback_fn)
4599
      # and make sure the new node will not have old files around
4600
      if not new_node.master_candidate:
4601
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4602
        msg = result.fail_msg
4603
        if msg:
4604
          self.LogWarning("Node failed to demote itself from master"
4605
                          " candidate status: %s" % msg)
4606
    else:
4607
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4608
                                  additional_vm=self.op.vm_capable)
4609
      self.context.AddNode(new_node, self.proc.GetECId())
4610

    
4611

    
4612
class LUNodeSetParams(LogicalUnit):
4613
  """Modifies the parameters of a node.
4614

4615
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4616
      to the node role (as _ROLE_*)
4617
  @cvar _R2F: a dictionary from node role to tuples of flags
4618
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4619

4620
  """
4621
  HPATH = "node-modify"
4622
  HTYPE = constants.HTYPE_NODE
4623
  REQ_BGL = False
4624
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4625
  _F2R = {
4626
    (True, False, False): _ROLE_CANDIDATE,
4627
    (False, True, False): _ROLE_DRAINED,
4628
    (False, False, True): _ROLE_OFFLINE,
4629
    (False, False, False): _ROLE_REGULAR,
4630
    }
4631
  _R2F = dict((v, k) for k, v in _F2R.items())
4632
  _FLAGS = ["master_candidate", "drained", "offline"]
4633

    
4634
  def CheckArguments(self):
4635
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4636
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4637
                self.op.master_capable, self.op.vm_capable,
4638
                self.op.secondary_ip, self.op.ndparams]
4639
    if all_mods.count(None) == len(all_mods):
4640
      raise errors.OpPrereqError("Please pass at least one modification",
4641
                                 errors.ECODE_INVAL)
4642
    if all_mods.count(True) > 1:
4643
      raise errors.OpPrereqError("Can't set the node into more than one"
4644
                                 " state at the same time",
4645
                                 errors.ECODE_INVAL)
4646

    
4647
    # Boolean value that tells us whether we might be demoting from MC
4648
    self.might_demote = (self.op.master_candidate == False or
4649
                         self.op.offline == True or
4650
                         self.op.drained == True or
4651
                         self.op.master_capable == False)
4652

    
4653
    if self.op.secondary_ip:
4654
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4655
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4656
                                   " address" % self.op.secondary_ip,
4657
                                   errors.ECODE_INVAL)
4658

    
4659
    self.lock_all = self.op.auto_promote and self.might_demote
4660
    self.lock_instances = self.op.secondary_ip is not None
4661

    
4662
  def ExpandNames(self):
4663
    if self.lock_all:
4664
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4665
    else:
4666
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4667

    
4668
    if self.lock_instances:
4669
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4670

    
4671
  def DeclareLocks(self, level):
4672
    # If we have locked all instances, before waiting to lock nodes, release
4673
    # all the ones living on nodes unrelated to the current operation.
4674
    if level == locking.LEVEL_NODE and self.lock_instances:
4675
      self.affected_instances = []
4676
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4677
        instances_keep = []
4678

    
4679
        # Build list of instances to release
4680
        for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
4681
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4682
          if (instance.disk_template in constants.DTS_INT_MIRROR and
4683
              self.op.node_name in instance.all_nodes):
4684
            instances_keep.append(instance_name)
4685
            self.affected_instances.append(instance)
4686

    
4687
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
4688

    
4689
        assert (set(self.glm.list_owned(locking.LEVEL_INSTANCE)) ==
4690
                set(instances_keep))
4691

    
4692
  def BuildHooksEnv(self):
4693
    """Build hooks env.
4694

4695
    This runs on the master node.
4696

4697
    """
4698
    return {
4699
      "OP_TARGET": self.op.node_name,
4700
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4701
      "OFFLINE": str(self.op.offline),
4702
      "DRAINED": str(self.op.drained),
4703
      "MASTER_CAPABLE": str(self.op.master_capable),
4704
      "VM_CAPABLE": str(self.op.vm_capable),
4705
      }
4706

    
4707
  def BuildHooksNodes(self):
4708
    """Build hooks nodes.
4709

4710
    """
4711
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
4712
    return (nl, nl)
4713

    
4714
  def CheckPrereq(self):
4715
    """Check prerequisites.
4716

4717
    This only checks the instance list against the existing names.
4718

4719
    """
4720
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4721

    
4722
    if (self.op.master_candidate is not None or
4723
        self.op.drained is not None or
4724
        self.op.offline is not None):
4725
      # we can't change the master's node flags
4726
      if self.op.node_name == self.cfg.GetMasterNode():
4727
        raise errors.OpPrereqError("The master role can be changed"
4728
                                   " only via master-failover",
4729
                                   errors.ECODE_INVAL)
4730

    
4731
    if self.op.master_candidate and not node.master_capable:
4732
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4733
                                 " it a master candidate" % node.name,
4734
                                 errors.ECODE_STATE)
4735

    
4736
    if self.op.vm_capable == False:
4737
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4738
      if ipri or isec:
4739
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4740
                                   " the vm_capable flag" % node.name,
4741
                                   errors.ECODE_STATE)
4742

    
4743
    if node.master_candidate and self.might_demote and not self.lock_all:
4744
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4745
      # check if after removing the current node, we're missing master
4746
      # candidates
4747
      (mc_remaining, mc_should, _) = \
4748
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4749
      if mc_remaining < mc_should:
4750
        raise errors.OpPrereqError("Not enough master candidates, please"
4751
                                   " pass auto promote option to allow"
4752
                                   " promotion", errors.ECODE_STATE)
4753

    
4754
    self.old_flags = old_flags = (node.master_candidate,
4755
                                  node.drained, node.offline)
4756
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
4757
    self.old_role = old_role = self._F2R[old_flags]
4758

    
4759
    # Check for ineffective changes
4760
    for attr in self._FLAGS:
4761
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4762
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4763
        setattr(self.op, attr, None)
4764

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

    
4768
    # TODO: We might query the real power state if it supports OOB
4769
    if _SupportsOob(self.cfg, node):
4770
      if self.op.offline is False and not (node.powered or
4771
                                           self.op.powered == True):
4772
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
4773
                                    " offline status can be reset") %
4774
                                   self.op.node_name)
4775
    elif self.op.powered is not None:
4776
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4777
                                  " as it does not support out-of-band"
4778
                                  " handling") % self.op.node_name)
4779

    
4780
    # If we're being deofflined/drained, we'll MC ourself if needed
4781
    if (self.op.drained == False or self.op.offline == False or
4782
        (self.op.master_capable and not node.master_capable)):
4783
      if _DecideSelfPromotion(self):
4784
        self.op.master_candidate = True
4785
        self.LogInfo("Auto-promoting node to master candidate")
4786

    
4787
    # If we're no longer master capable, we'll demote ourselves from MC
4788
    if self.op.master_capable == False and node.master_candidate:
4789
      self.LogInfo("Demoting from master candidate")
4790
      self.op.master_candidate = False
4791

    
4792
    # Compute new role
4793
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4794
    if self.op.master_candidate:
4795
      new_role = self._ROLE_CANDIDATE
4796
    elif self.op.drained:
4797
      new_role = self._ROLE_DRAINED
4798
    elif self.op.offline:
4799
      new_role = self._ROLE_OFFLINE
4800
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4801
      # False is still in new flags, which means we're un-setting (the
4802
      # only) True flag
4803
      new_role = self._ROLE_REGULAR
4804
    else: # no new flags, nothing, keep old role
4805
      new_role = old_role
4806

    
4807
    self.new_role = new_role
4808

    
4809
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4810
      # Trying to transition out of offline status
4811
      result = self.rpc.call_version([node.name])[node.name]
4812
      if result.fail_msg:
4813
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4814
                                   " to report its version: %s" %
4815
                                   (node.name, result.fail_msg),
4816
                                   errors.ECODE_STATE)
4817
      else:
4818
        self.LogWarning("Transitioning node from offline to online state"
4819
                        " without using re-add. Please make sure the node"
4820
                        " is healthy!")
4821

    
4822
    if self.op.secondary_ip:
4823
      # Ok even without locking, because this can't be changed by any LU
4824
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4825
      master_singlehomed = master.secondary_ip == master.primary_ip
4826
      if master_singlehomed and self.op.secondary_ip:
4827
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4828
                                   " homed cluster", errors.ECODE_INVAL)
4829

    
4830
      if node.offline:
4831
        if self.affected_instances:
4832
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4833
                                     " node has instances (%s) configured"
4834
                                     " to use it" % self.affected_instances)
4835
      else:
4836
        # On online nodes, check that no instances are running, and that
4837
        # the node has the new ip and we can reach it.
4838
        for instance in self.affected_instances:
4839
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4840

    
4841
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4842
        if master.name != node.name:
4843
          # check reachability from master secondary ip to new secondary ip
4844
          if not netutils.TcpPing(self.op.secondary_ip,
4845
                                  constants.DEFAULT_NODED_PORT,
4846
                                  source=master.secondary_ip):
4847
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4848
                                       " based ping to node daemon port",
4849
                                       errors.ECODE_ENVIRON)
4850

    
4851
    if self.op.ndparams:
4852
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4853
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4854
      self.new_ndparams = new_ndparams
4855

    
4856
  def Exec(self, feedback_fn):
4857
    """Modifies a node.
4858

4859
    """
4860
    node = self.node
4861
    old_role = self.old_role
4862
    new_role = self.new_role
4863

    
4864
    result = []
4865

    
4866
    if self.op.ndparams:
4867
      node.ndparams = self.new_ndparams
4868

    
4869
    if self.op.powered is not None:
4870
      node.powered = self.op.powered
4871

    
4872
    for attr in ["master_capable", "vm_capable"]:
4873
      val = getattr(self.op, attr)
4874
      if val is not None:
4875
        setattr(node, attr, val)
4876
        result.append((attr, str(val)))
4877

    
4878
    if new_role != old_role:
4879
      # Tell the node to demote itself, if no longer MC and not offline
4880
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4881
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4882
        if msg:
4883
          self.LogWarning("Node failed to demote itself: %s", msg)
4884

    
4885
      new_flags = self._R2F[new_role]
4886
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4887
        if of != nf:
4888
          result.append((desc, str(nf)))
4889
      (node.master_candidate, node.drained, node.offline) = new_flags
4890

    
4891
      # we locked all nodes, we adjust the CP before updating this node
4892
      if self.lock_all:
4893
        _AdjustCandidatePool(self, [node.name])
4894

    
4895
    if self.op.secondary_ip:
4896
      node.secondary_ip = self.op.secondary_ip
4897
      result.append(("secondary_ip", self.op.secondary_ip))
4898

    
4899
    # this will trigger configuration file update, if needed
4900
    self.cfg.Update(node, feedback_fn)
4901

    
4902
    # this will trigger job queue propagation or cleanup if the mc
4903
    # flag changed
4904
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4905
      self.context.ReaddNode(node)
4906

    
4907
    return result
4908

    
4909

    
4910
class LUNodePowercycle(NoHooksLU):
4911
  """Powercycles a node.
4912

4913
  """
4914
  REQ_BGL = False
4915

    
4916
  def CheckArguments(self):
4917
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4918
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4919
      raise errors.OpPrereqError("The node is the master and the force"
4920
                                 " parameter was not set",
4921
                                 errors.ECODE_INVAL)
4922

    
4923
  def ExpandNames(self):
4924
    """Locking for PowercycleNode.
4925

4926
    This is a last-resort option and shouldn't block on other
4927
    jobs. Therefore, we grab no locks.
4928

4929
    """
4930
    self.needed_locks = {}
4931

    
4932
  def Exec(self, feedback_fn):
4933
    """Reboots a node.
4934

4935
    """
4936
    result = self.rpc.call_node_powercycle(self.op.node_name,
4937
                                           self.cfg.GetHypervisorType())
4938
    result.Raise("Failed to schedule the reboot")
4939
    return result.payload
4940

    
4941

    
4942
class LUClusterQuery(NoHooksLU):
4943
  """Query cluster configuration.
4944

4945
  """
4946
  REQ_BGL = False
4947

    
4948
  def ExpandNames(self):
4949
    self.needed_locks = {}
4950

    
4951
  def Exec(self, feedback_fn):
4952
    """Return cluster config.
4953

4954
    """
4955
    cluster = self.cfg.GetClusterInfo()
4956
    os_hvp = {}
4957

    
4958
    # Filter just for enabled hypervisors
4959
    for os_name, hv_dict in cluster.os_hvp.items():
4960
      os_hvp[os_name] = {}
4961
      for hv_name, hv_params in hv_dict.items():
4962
        if hv_name in cluster.enabled_hypervisors:
4963
          os_hvp[os_name][hv_name] = hv_params
4964

    
4965
    # Convert ip_family to ip_version
4966
    primary_ip_version = constants.IP4_VERSION
4967
    if cluster.primary_ip_family == netutils.IP6Address.family:
4968
      primary_ip_version = constants.IP6_VERSION
4969

    
4970
    result = {
4971
      "software_version": constants.RELEASE_VERSION,
4972
      "protocol_version": constants.PROTOCOL_VERSION,
4973
      "config_version": constants.CONFIG_VERSION,
4974
      "os_api_version": max(constants.OS_API_VERSIONS),
4975
      "export_version": constants.EXPORT_VERSION,
4976
      "architecture": (platform.architecture()[0], platform.machine()),
4977
      "name": cluster.cluster_name,
4978
      "master": cluster.master_node,
4979
      "default_hypervisor": cluster.enabled_hypervisors[0],
4980
      "enabled_hypervisors": cluster.enabled_hypervisors,
4981
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4982
                        for hypervisor_name in cluster.enabled_hypervisors]),
4983
      "os_hvp": os_hvp,
4984
      "beparams": cluster.beparams,
4985
      "osparams": cluster.osparams,
4986
      "nicparams": cluster.nicparams,
4987
      "ndparams": cluster.ndparams,
4988
      "candidate_pool_size": cluster.candidate_pool_size,
4989
      "master_netdev": cluster.master_netdev,
4990
      "volume_group_name": cluster.volume_group_name,
4991
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4992
      "file_storage_dir": cluster.file_storage_dir,
4993
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
4994
      "maintain_node_health": cluster.maintain_node_health,
4995
      "ctime": cluster.ctime,
4996
      "mtime": cluster.mtime,
4997
      "uuid": cluster.uuid,
4998
      "tags": list(cluster.GetTags()),
4999
      "uid_pool": cluster.uid_pool,
5000
      "default_iallocator": cluster.default_iallocator,
5001
      "reserved_lvs": cluster.reserved_lvs,
5002
      "primary_ip_version": primary_ip_version,
5003
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5004
      "hidden_os": cluster.hidden_os,
5005
      "blacklisted_os": cluster.blacklisted_os,
5006
      }
5007

    
5008
    return result
5009

    
5010

    
5011
class LUClusterConfigQuery(NoHooksLU):
5012
  """Return configuration values.
5013

5014
  """
5015
  REQ_BGL = False
5016
  _FIELDS_DYNAMIC = utils.FieldSet()
5017
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5018
                                  "watcher_pause", "volume_group_name")
5019

    
5020
  def CheckArguments(self):
5021
    _CheckOutputFields(static=self._FIELDS_STATIC,
5022
                       dynamic=self._FIELDS_DYNAMIC,
5023
                       selected=self.op.output_fields)
5024

    
5025
  def ExpandNames(self):
5026
    self.needed_locks = {}
5027

    
5028
  def Exec(self, feedback_fn):
5029
    """Dump a representation of the cluster config to the standard output.
5030

5031
    """
5032
    values = []
5033
    for field in self.op.output_fields:
5034
      if field == "cluster_name":
5035
        entry = self.cfg.GetClusterName()
5036
      elif field == "master_node":
5037
        entry = self.cfg.GetMasterNode()
5038
      elif field == "drain_flag":
5039
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5040
      elif field == "watcher_pause":
5041
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5042
      elif field == "volume_group_name":
5043
        entry = self.cfg.GetVGName()
5044
      else:
5045
        raise errors.ParameterError(field)
5046
      values.append(entry)
5047
    return values
5048

    
5049

    
5050
class LUInstanceActivateDisks(NoHooksLU):
5051
  """Bring up an instance's disks.
5052

5053
  """
5054
  REQ_BGL = False
5055

    
5056
  def ExpandNames(self):
5057
    self._ExpandAndLockInstance()
5058
    self.needed_locks[locking.LEVEL_NODE] = []
5059
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5060

    
5061
  def DeclareLocks(self, level):
5062
    if level == locking.LEVEL_NODE:
5063
      self._LockInstancesNodes()
5064

    
5065
  def CheckPrereq(self):
5066
    """Check prerequisites.
5067

5068
    This checks that the instance is in the cluster.
5069

5070
    """
5071
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5072
    assert self.instance is not None, \
5073
      "Cannot retrieve locked instance %s" % self.op.instance_name
5074
    _CheckNodeOnline(self, self.instance.primary_node)
5075

    
5076
  def Exec(self, feedback_fn):
5077
    """Activate the disks.
5078

5079
    """
5080
    disks_ok, disks_info = \
5081
              _AssembleInstanceDisks(self, self.instance,
5082
                                     ignore_size=self.op.ignore_size)
5083
    if not disks_ok:
5084
      raise errors.OpExecError("Cannot activate block devices")
5085

    
5086
    return disks_info
5087

    
5088

    
5089
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5090
                           ignore_size=False):
5091
  """Prepare the block devices for an instance.
5092

5093
  This sets up the block devices on all nodes.
5094

5095
  @type lu: L{LogicalUnit}
5096
  @param lu: the logical unit on whose behalf we execute
5097
  @type instance: L{objects.Instance}
5098
  @param instance: the instance for whose disks we assemble
5099
  @type disks: list of L{objects.Disk} or None
5100
  @param disks: which disks to assemble (or all, if None)
5101
  @type ignore_secondaries: boolean
5102
  @param ignore_secondaries: if true, errors on secondary nodes
5103
      won't result in an error return from the function
5104
  @type ignore_size: boolean
5105
  @param ignore_size: if true, the current known size of the disk
5106
      will not be used during the disk activation, useful for cases
5107
      when the size is wrong
5108
  @return: False if the operation failed, otherwise a list of
5109
      (host, instance_visible_name, node_visible_name)
5110
      with the mapping from node devices to instance devices
5111

5112
  """
5113
  device_info = []
5114
  disks_ok = True
5115
  iname = instance.name
5116
  disks = _ExpandCheckDisks(instance, disks)
5117

    
5118
  # With the two passes mechanism we try to reduce the window of
5119
  # opportunity for the race condition of switching DRBD to primary
5120
  # before handshaking occured, but we do not eliminate it
5121

    
5122
  # The proper fix would be to wait (with some limits) until the
5123
  # connection has been made and drbd transitions from WFConnection
5124
  # into any other network-connected state (Connected, SyncTarget,
5125
  # SyncSource, etc.)
5126

    
5127
  # 1st pass, assemble on all nodes in secondary mode
5128
  for idx, inst_disk in enumerate(disks):
5129
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5130
      if ignore_size:
5131
        node_disk = node_disk.Copy()
5132
        node_disk.UnsetSize()
5133
      lu.cfg.SetDiskID(node_disk, node)
5134
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5135
      msg = result.fail_msg
5136
      if msg:
5137
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5138
                           " (is_primary=False, pass=1): %s",
5139
                           inst_disk.iv_name, node, msg)
5140
        if not ignore_secondaries:
5141
          disks_ok = False
5142

    
5143
  # FIXME: race condition on drbd migration to primary
5144

    
5145
  # 2nd pass, do only the primary node
5146
  for idx, inst_disk in enumerate(disks):
5147
    dev_path = None
5148

    
5149
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5150
      if node != instance.primary_node:
5151
        continue
5152
      if ignore_size:
5153
        node_disk = node_disk.Copy()
5154
        node_disk.UnsetSize()
5155
      lu.cfg.SetDiskID(node_disk, node)
5156
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5157
      msg = result.fail_msg
5158
      if msg:
5159
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5160
                           " (is_primary=True, pass=2): %s",
5161
                           inst_disk.iv_name, node, msg)
5162
        disks_ok = False
5163
      else:
5164
        dev_path = result.payload
5165

    
5166
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5167

    
5168
  # leave the disks configured for the primary node
5169
  # this is a workaround that would be fixed better by
5170
  # improving the logical/physical id handling
5171
  for disk in disks:
5172
    lu.cfg.SetDiskID(disk, instance.primary_node)
5173

    
5174
  return disks_ok, device_info
5175

    
5176

    
5177
def _StartInstanceDisks(lu, instance, force):
5178
  """Start the disks of an instance.
5179

5180
  """
5181
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5182
                                           ignore_secondaries=force)
5183
  if not disks_ok:
5184
    _ShutdownInstanceDisks(lu, instance)
5185
    if force is not None and not force:
5186
      lu.proc.LogWarning("", hint="If the message above refers to a"
5187
                         " secondary node,"
5188
                         " you can retry the operation using '--force'.")
5189
    raise errors.OpExecError("Disk consistency error")
5190

    
5191

    
5192
class LUInstanceDeactivateDisks(NoHooksLU):
5193
  """Shutdown an instance's disks.
5194

5195
  """
5196
  REQ_BGL = False
5197

    
5198
  def ExpandNames(self):
5199
    self._ExpandAndLockInstance()
5200
    self.needed_locks[locking.LEVEL_NODE] = []
5201
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5202

    
5203
  def DeclareLocks(self, level):
5204
    if level == locking.LEVEL_NODE:
5205
      self._LockInstancesNodes()
5206

    
5207
  def CheckPrereq(self):
5208
    """Check prerequisites.
5209

5210
    This checks that the instance is in the cluster.
5211

5212
    """
5213
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5214
    assert self.instance is not None, \
5215
      "Cannot retrieve locked instance %s" % self.op.instance_name
5216

    
5217
  def Exec(self, feedback_fn):
5218
    """Deactivate the disks
5219

5220
    """
5221
    instance = self.instance
5222
    if self.op.force:
5223
      _ShutdownInstanceDisks(self, instance)
5224
    else:
5225
      _SafeShutdownInstanceDisks(self, instance)
5226

    
5227

    
5228
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5229
  """Shutdown block devices of an instance.
5230

5231
  This function checks if an instance is running, before calling
5232
  _ShutdownInstanceDisks.
5233

5234
  """
5235
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5236
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5237

    
5238

    
5239
def _ExpandCheckDisks(instance, disks):
5240
  """Return the instance disks selected by the disks list
5241

5242
  @type disks: list of L{objects.Disk} or None
5243
  @param disks: selected disks
5244
  @rtype: list of L{objects.Disk}
5245
  @return: selected instance disks to act on
5246

5247
  """
5248
  if disks is None:
5249
    return instance.disks
5250
  else:
5251
    if not set(disks).issubset(instance.disks):
5252
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5253
                                   " target instance")
5254
    return disks
5255

    
5256

    
5257
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5258
  """Shutdown block devices of an instance.
5259

5260
  This does the shutdown on all nodes of the instance.
5261

5262
  If the ignore_primary is false, errors on the primary node are
5263
  ignored.
5264

5265
  """
5266
  all_result = True
5267
  disks = _ExpandCheckDisks(instance, disks)
5268

    
5269
  for disk in disks:
5270
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5271
      lu.cfg.SetDiskID(top_disk, node)
5272
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5273
      msg = result.fail_msg
5274
      if msg:
5275
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5276
                      disk.iv_name, node, msg)
5277
        if ((node == instance.primary_node and not ignore_primary) or
5278
            (node != instance.primary_node and not result.offline)):
5279
          all_result = False
5280
  return all_result
5281

    
5282

    
5283
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5284
  """Checks if a node has enough free memory.
5285

5286
  This function check if a given node has the needed amount of free
5287
  memory. In case the node has less memory or we cannot get the
5288
  information from the node, this function raise an OpPrereqError
5289
  exception.
5290

5291
  @type lu: C{LogicalUnit}
5292
  @param lu: a logical unit from which we get configuration data
5293
  @type node: C{str}
5294
  @param node: the node to check
5295
  @type reason: C{str}
5296
  @param reason: string to use in the error message
5297
  @type requested: C{int}
5298
  @param requested: the amount of memory in MiB to check for
5299
  @type hypervisor_name: C{str}
5300
  @param hypervisor_name: the hypervisor to ask for memory stats
5301
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5302
      we cannot check the node
5303

5304
  """
5305
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5306
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5307
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5308
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5309
  if not isinstance(free_mem, int):
5310
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5311
                               " was '%s'" % (node, free_mem),
5312
                               errors.ECODE_ENVIRON)
5313
  if requested > free_mem:
5314
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5315
                               " needed %s MiB, available %s MiB" %
5316
                               (node, reason, requested, free_mem),
5317
                               errors.ECODE_NORES)
5318

    
5319

    
5320
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5321
  """Checks if nodes have enough free disk space in the all VGs.
5322

5323
  This function check if all given nodes have the needed amount of
5324
  free disk. In case any node has less disk or we cannot get the
5325
  information from the node, this function raise an OpPrereqError
5326
  exception.
5327

5328
  @type lu: C{LogicalUnit}
5329
  @param lu: a logical unit from which we get configuration data
5330
  @type nodenames: C{list}
5331
  @param nodenames: the list of node names to check
5332
  @type req_sizes: C{dict}
5333
  @param req_sizes: the hash of vg and corresponding amount of disk in
5334
      MiB to check for
5335
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5336
      or we cannot check the node
5337

5338
  """
5339
  for vg, req_size in req_sizes.items():
5340
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5341

    
5342

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

5346
  This function check if all given nodes have the needed amount of
5347
  free disk. In case any node has less disk or we cannot get the
5348
  information from the node, this function raise an OpPrereqError
5349
  exception.
5350

5351
  @type lu: C{LogicalUnit}
5352
  @param lu: a logical unit from which we get configuration data
5353
  @type nodenames: C{list}
5354
  @param nodenames: the list of node names to check
5355
  @type vg: C{str}
5356
  @param vg: the volume group to check
5357
  @type requested: C{int}
5358
  @param requested: the amount of disk in MiB to check for
5359
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5360
      or we cannot check the node
5361

5362
  """
5363
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5364
  for node in nodenames:
5365
    info = nodeinfo[node]
5366
    info.Raise("Cannot get current information from node %s" % node,
5367
               prereq=True, ecode=errors.ECODE_ENVIRON)
5368
    vg_free = info.payload.get("vg_free", None)
5369
    if not isinstance(vg_free, int):
5370
      raise errors.OpPrereqError("Can't compute free disk space on node"
5371
                                 " %s for vg %s, result was '%s'" %
5372
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5373
    if requested > vg_free:
5374
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5375
                                 " vg %s: required %d MiB, available %d MiB" %
5376
                                 (node, vg, requested, vg_free),
5377
                                 errors.ECODE_NORES)
5378

    
5379

    
5380
class LUInstanceStartup(LogicalUnit):
5381
  """Starts an instance.
5382

5383
  """
5384
  HPATH = "instance-start"
5385
  HTYPE = constants.HTYPE_INSTANCE
5386
  REQ_BGL = False
5387

    
5388
  def CheckArguments(self):
5389
    # extra beparams
5390
    if self.op.beparams:
5391
      # fill the beparams dict
5392
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5393

    
5394
  def ExpandNames(self):
5395
    self._ExpandAndLockInstance()
5396

    
5397
  def BuildHooksEnv(self):
5398
    """Build hooks env.
5399

5400
    This runs on master, primary and secondary nodes of the instance.
5401

5402
    """
5403
    env = {
5404
      "FORCE": self.op.force,
5405
      }
5406

    
5407
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5408

    
5409
    return env
5410

    
5411
  def BuildHooksNodes(self):
5412
    """Build hooks nodes.
5413

5414
    """
5415
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5416
    return (nl, nl)
5417

    
5418
  def CheckPrereq(self):
5419
    """Check prerequisites.
5420

5421
    This checks that the instance is in the cluster.
5422

5423
    """
5424
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5425
    assert self.instance is not None, \
5426
      "Cannot retrieve locked instance %s" % self.op.instance_name
5427

    
5428
    # extra hvparams
5429
    if self.op.hvparams:
5430
      # check hypervisor parameter syntax (locally)
5431
      cluster = self.cfg.GetClusterInfo()
5432
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5433
      filled_hvp = cluster.FillHV(instance)
5434
      filled_hvp.update(self.op.hvparams)
5435
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5436
      hv_type.CheckParameterSyntax(filled_hvp)
5437
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5438

    
5439
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5440

    
5441
    if self.primary_offline and self.op.ignore_offline_nodes:
5442
      self.proc.LogWarning("Ignoring offline primary node")
5443

    
5444
      if self.op.hvparams or self.op.beparams:
5445
        self.proc.LogWarning("Overridden parameters are ignored")
5446
    else:
5447
      _CheckNodeOnline(self, instance.primary_node)
5448

    
5449
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5450

    
5451
      # check bridges existence
5452
      _CheckInstanceBridgesExist(self, instance)
5453

    
5454
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5455
                                                instance.name,
5456
                                                instance.hypervisor)
5457
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5458
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5459
      if not remote_info.payload: # not running already
5460
        _CheckNodeFreeMemory(self, instance.primary_node,
5461
                             "starting instance %s" % instance.name,
5462
                             bep[constants.BE_MEMORY], instance.hypervisor)
5463

    
5464
  def Exec(self, feedback_fn):
5465
    """Start the instance.
5466

5467
    """
5468
    instance = self.instance
5469
    force = self.op.force
5470

    
5471
    if not self.op.no_remember:
5472
      self.cfg.MarkInstanceUp(instance.name)
5473

    
5474
    if self.primary_offline:
5475
      assert self.op.ignore_offline_nodes
5476
      self.proc.LogInfo("Primary node offline, marked instance as started")
5477
    else:
5478
      node_current = instance.primary_node
5479

    
5480
      _StartInstanceDisks(self, instance, force)
5481

    
5482
      result = self.rpc.call_instance_start(node_current, instance,
5483
                                            self.op.hvparams, self.op.beparams)
5484
      msg = result.fail_msg
5485
      if msg:
5486
        _ShutdownInstanceDisks(self, instance)
5487
        raise errors.OpExecError("Could not start instance: %s" % msg)
5488

    
5489

    
5490
class LUInstanceReboot(LogicalUnit):
5491
  """Reboot an instance.
5492

5493
  """
5494
  HPATH = "instance-reboot"
5495
  HTYPE = constants.HTYPE_INSTANCE
5496
  REQ_BGL = False
5497

    
5498
  def ExpandNames(self):
5499
    self._ExpandAndLockInstance()
5500

    
5501
  def BuildHooksEnv(self):
5502
    """Build hooks env.
5503

5504
    This runs on master, primary and secondary nodes of the instance.
5505

5506
    """
5507
    env = {
5508
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5509
      "REBOOT_TYPE": self.op.reboot_type,
5510
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5511
      }
5512

    
5513
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5514

    
5515
    return env
5516

    
5517
  def BuildHooksNodes(self):
5518
    """Build hooks nodes.
5519

5520
    """
5521
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5522
    return (nl, nl)
5523

    
5524
  def CheckPrereq(self):
5525
    """Check prerequisites.
5526

5527
    This checks that the instance is in the cluster.
5528

5529
    """
5530
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5531
    assert self.instance is not None, \
5532
      "Cannot retrieve locked instance %s" % self.op.instance_name
5533

    
5534
    _CheckNodeOnline(self, instance.primary_node)
5535

    
5536
    # check bridges existence
5537
    _CheckInstanceBridgesExist(self, instance)
5538

    
5539
  def Exec(self, feedback_fn):
5540
    """Reboot the instance.
5541

5542
    """
5543
    instance = self.instance
5544
    ignore_secondaries = self.op.ignore_secondaries
5545
    reboot_type = self.op.reboot_type
5546

    
5547
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5548
                                              instance.name,
5549
                                              instance.hypervisor)
5550
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5551
    instance_running = bool(remote_info.payload)
5552

    
5553
    node_current = instance.primary_node
5554

    
5555
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5556
                                            constants.INSTANCE_REBOOT_HARD]:
5557
      for disk in instance.disks:
5558
        self.cfg.SetDiskID(disk, node_current)
5559
      result = self.rpc.call_instance_reboot(node_current, instance,
5560
                                             reboot_type,
5561
                                             self.op.shutdown_timeout)
5562
      result.Raise("Could not reboot instance")
5563
    else:
5564
      if instance_running:
5565
        result = self.rpc.call_instance_shutdown(node_current, instance,
5566
                                                 self.op.shutdown_timeout)
5567
        result.Raise("Could not shutdown instance for full reboot")
5568
        _ShutdownInstanceDisks(self, instance)
5569
      else:
5570
        self.LogInfo("Instance %s was already stopped, starting now",
5571
                     instance.name)
5572
      _StartInstanceDisks(self, instance, ignore_secondaries)
5573
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5574
      msg = result.fail_msg
5575
      if msg:
5576
        _ShutdownInstanceDisks(self, instance)
5577
        raise errors.OpExecError("Could not start instance for"
5578
                                 " full reboot: %s" % msg)
5579

    
5580
    self.cfg.MarkInstanceUp(instance.name)
5581

    
5582

    
5583
class LUInstanceShutdown(LogicalUnit):
5584
  """Shutdown an instance.
5585

5586
  """
5587
  HPATH = "instance-stop"
5588
  HTYPE = constants.HTYPE_INSTANCE
5589
  REQ_BGL = False
5590

    
5591
  def ExpandNames(self):
5592
    self._ExpandAndLockInstance()
5593

    
5594
  def BuildHooksEnv(self):
5595
    """Build hooks env.
5596

5597
    This runs on master, primary and secondary nodes of the instance.
5598

5599
    """
5600
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5601
    env["TIMEOUT"] = self.op.timeout
5602
    return env
5603

    
5604
  def BuildHooksNodes(self):
5605
    """Build hooks nodes.
5606

5607
    """
5608
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5609
    return (nl, nl)
5610

    
5611
  def CheckPrereq(self):
5612
    """Check prerequisites.
5613

5614
    This checks that the instance is in the cluster.
5615

5616
    """
5617
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5618
    assert self.instance is not None, \
5619
      "Cannot retrieve locked instance %s" % self.op.instance_name
5620

    
5621
    self.primary_offline = \
5622
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5623

    
5624
    if self.primary_offline and self.op.ignore_offline_nodes:
5625
      self.proc.LogWarning("Ignoring offline primary node")
5626
    else:
5627
      _CheckNodeOnline(self, self.instance.primary_node)
5628

    
5629
  def Exec(self, feedback_fn):
5630
    """Shutdown the instance.
5631

5632
    """
5633
    instance = self.instance
5634
    node_current = instance.primary_node
5635
    timeout = self.op.timeout
5636

    
5637
    if not self.op.no_remember:
5638
      self.cfg.MarkInstanceDown(instance.name)
5639

    
5640
    if self.primary_offline:
5641
      assert self.op.ignore_offline_nodes
5642
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5643
    else:
5644
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5645
      msg = result.fail_msg
5646
      if msg:
5647
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5648

    
5649
      _ShutdownInstanceDisks(self, instance)
5650

    
5651

    
5652
class LUInstanceReinstall(LogicalUnit):
5653
  """Reinstall an instance.
5654

5655
  """
5656
  HPATH = "instance-reinstall"
5657
  HTYPE = constants.HTYPE_INSTANCE
5658
  REQ_BGL = False
5659

    
5660
  def ExpandNames(self):
5661
    self._ExpandAndLockInstance()
5662

    
5663
  def BuildHooksEnv(self):
5664
    """Build hooks env.
5665

5666
    This runs on master, primary and secondary nodes of the instance.
5667

5668
    """
5669
    return _BuildInstanceHookEnvByObject(self, self.instance)
5670

    
5671
  def BuildHooksNodes(self):
5672
    """Build hooks nodes.
5673

5674
    """
5675
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5676
    return (nl, nl)
5677

    
5678
  def CheckPrereq(self):
5679
    """Check prerequisites.
5680

5681
    This checks that the instance is in the cluster and is not running.
5682

5683
    """
5684
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5685
    assert instance is not None, \
5686
      "Cannot retrieve locked instance %s" % self.op.instance_name
5687
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5688
                     " offline, cannot reinstall")
5689
    for node in instance.secondary_nodes:
5690
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5691
                       " cannot reinstall")
5692

    
5693
    if instance.disk_template == constants.DT_DISKLESS:
5694
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5695
                                 self.op.instance_name,
5696
                                 errors.ECODE_INVAL)
5697
    _CheckInstanceDown(self, instance, "cannot reinstall")
5698

    
5699
    if self.op.os_type is not None:
5700
      # OS verification
5701
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5702
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5703
      instance_os = self.op.os_type
5704
    else:
5705
      instance_os = instance.os
5706

    
5707
    nodelist = list(instance.all_nodes)
5708

    
5709
    if self.op.osparams:
5710
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5711
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5712
      self.os_inst = i_osdict # the new dict (without defaults)
5713
    else:
5714
      self.os_inst = None
5715

    
5716
    self.instance = instance
5717

    
5718
  def Exec(self, feedback_fn):
5719
    """Reinstall the instance.
5720

5721
    """
5722
    inst = self.instance
5723

    
5724
    if self.op.os_type is not None:
5725
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5726
      inst.os = self.op.os_type
5727
      # Write to configuration
5728
      self.cfg.Update(inst, feedback_fn)
5729

    
5730
    _StartInstanceDisks(self, inst, None)
5731
    try:
5732
      feedback_fn("Running the instance OS create scripts...")
5733
      # FIXME: pass debug option from opcode to backend
5734
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5735
                                             self.op.debug_level,
5736
                                             osparams=self.os_inst)
5737
      result.Raise("Could not install OS for instance %s on node %s" %
5738
                   (inst.name, inst.primary_node))
5739
    finally:
5740
      _ShutdownInstanceDisks(self, inst)
5741

    
5742

    
5743
class LUInstanceRecreateDisks(LogicalUnit):
5744
  """Recreate an instance's missing disks.
5745

5746
  """
5747
  HPATH = "instance-recreate-disks"
5748
  HTYPE = constants.HTYPE_INSTANCE
5749
  REQ_BGL = False
5750

    
5751
  def CheckArguments(self):
5752
    # normalise the disk list
5753
    self.op.disks = sorted(frozenset(self.op.disks))
5754

    
5755
  def ExpandNames(self):
5756
    self._ExpandAndLockInstance()
5757
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5758
    if self.op.nodes:
5759
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5760
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5761
    else:
5762
      self.needed_locks[locking.LEVEL_NODE] = []
5763

    
5764
  def DeclareLocks(self, level):
5765
    if level == locking.LEVEL_NODE:
5766
      # if we replace the nodes, we only need to lock the old primary,
5767
      # otherwise we need to lock all nodes for disk re-creation
5768
      primary_only = bool(self.op.nodes)
5769
      self._LockInstancesNodes(primary_only=primary_only)
5770

    
5771
  def BuildHooksEnv(self):
5772
    """Build hooks env.
5773

5774
    This runs on master, primary and secondary nodes of the instance.
5775

5776
    """
5777
    return _BuildInstanceHookEnvByObject(self, self.instance)
5778

    
5779
  def BuildHooksNodes(self):
5780
    """Build hooks nodes.
5781

5782
    """
5783
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5784
    return (nl, nl)
5785

    
5786
  def CheckPrereq(self):
5787
    """Check prerequisites.
5788

5789
    This checks that the instance is in the cluster and is not running.
5790

5791
    """
5792
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5793
    assert instance is not None, \
5794
      "Cannot retrieve locked instance %s" % self.op.instance_name
5795
    if self.op.nodes:
5796
      if len(self.op.nodes) != len(instance.all_nodes):
5797
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
5798
                                   " %d replacement nodes were specified" %
5799
                                   (instance.name, len(instance.all_nodes),
5800
                                    len(self.op.nodes)),
5801
                                   errors.ECODE_INVAL)
5802
      assert instance.disk_template != constants.DT_DRBD8 or \
5803
          len(self.op.nodes) == 2
5804
      assert instance.disk_template != constants.DT_PLAIN or \
5805
          len(self.op.nodes) == 1
5806
      primary_node = self.op.nodes[0]
5807
    else:
5808
      primary_node = instance.primary_node
5809
    _CheckNodeOnline(self, primary_node)
5810

    
5811
    if instance.disk_template == constants.DT_DISKLESS:
5812
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5813
                                 self.op.instance_name, errors.ECODE_INVAL)
5814
    # if we replace nodes *and* the old primary is offline, we don't
5815
    # check
5816
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
5817
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
5818
    if not (self.op.nodes and old_pnode.offline):
5819
      _CheckInstanceDown(self, instance, "cannot recreate disks")
5820

    
5821
    if not self.op.disks:
5822
      self.op.disks = range(len(instance.disks))
5823
    else:
5824
      for idx in self.op.disks:
5825
        if idx >= len(instance.disks):
5826
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
5827
                                     errors.ECODE_INVAL)
5828
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
5829
      raise errors.OpPrereqError("Can't recreate disks partially and"
5830
                                 " change the nodes at the same time",
5831
                                 errors.ECODE_INVAL)
5832
    self.instance = instance
5833

    
5834
  def Exec(self, feedback_fn):
5835
    """Recreate the disks.
5836

5837
    """
5838
    # change primary node, if needed
5839
    if self.op.nodes:
5840
      self.instance.primary_node = self.op.nodes[0]
5841
      self.LogWarning("Changing the instance's nodes, you will have to"
5842
                      " remove any disks left on the older nodes manually")
5843

    
5844
    to_skip = []
5845
    for idx, disk in enumerate(self.instance.disks):
5846
      if idx not in self.op.disks: # disk idx has not been passed in
5847
        to_skip.append(idx)
5848
        continue
5849
      # update secondaries for disks, if needed
5850
      if self.op.nodes:
5851
        if disk.dev_type == constants.LD_DRBD8:
5852
          # need to update the nodes
5853
          assert len(self.op.nodes) == 2
5854
          logical_id = list(disk.logical_id)
5855
          logical_id[0] = self.op.nodes[0]
5856
          logical_id[1] = self.op.nodes[1]
5857
          disk.logical_id = tuple(logical_id)
5858

    
5859
    if self.op.nodes:
5860
      self.cfg.Update(self.instance, feedback_fn)
5861

    
5862
    _CreateDisks(self, self.instance, to_skip=to_skip)
5863

    
5864

    
5865
class LUInstanceRename(LogicalUnit):
5866
  """Rename an instance.
5867

5868
  """
5869
  HPATH = "instance-rename"
5870
  HTYPE = constants.HTYPE_INSTANCE
5871

    
5872
  def CheckArguments(self):
5873
    """Check arguments.
5874

5875
    """
5876
    if self.op.ip_check and not self.op.name_check:
5877
      # TODO: make the ip check more flexible and not depend on the name check
5878
      raise errors.OpPrereqError("IP address check requires a name check",
5879
                                 errors.ECODE_INVAL)
5880

    
5881
  def BuildHooksEnv(self):
5882
    """Build hooks env.
5883

5884
    This runs on master, primary and secondary nodes of the instance.
5885

5886
    """
5887
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5888
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5889
    return env
5890

    
5891
  def BuildHooksNodes(self):
5892
    """Build hooks nodes.
5893

5894
    """
5895
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5896
    return (nl, nl)
5897

    
5898
  def CheckPrereq(self):
5899
    """Check prerequisites.
5900

5901
    This checks that the instance is in the cluster and is not running.
5902

5903
    """
5904
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5905
                                                self.op.instance_name)
5906
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5907
    assert instance is not None
5908
    _CheckNodeOnline(self, instance.primary_node)
5909
    _CheckInstanceDown(self, instance, "cannot rename")
5910
    self.instance = instance
5911

    
5912
    new_name = self.op.new_name
5913
    if self.op.name_check:
5914
      hostname = netutils.GetHostname(name=new_name)
5915
      if hostname != new_name:
5916
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5917
                     hostname.name)
5918
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
5919
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
5920
                                    " same as given hostname '%s'") %
5921
                                    (hostname.name, self.op.new_name),
5922
                                    errors.ECODE_INVAL)
5923
      new_name = self.op.new_name = hostname.name
5924
      if (self.op.ip_check and
5925
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5926
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5927
                                   (hostname.ip, new_name),
5928
                                   errors.ECODE_NOTUNIQUE)
5929

    
5930
    instance_list = self.cfg.GetInstanceList()
5931
    if new_name in instance_list and new_name != instance.name:
5932
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5933
                                 new_name, errors.ECODE_EXISTS)
5934

    
5935
  def Exec(self, feedback_fn):
5936
    """Rename the instance.
5937

5938
    """
5939
    inst = self.instance
5940
    old_name = inst.name
5941

    
5942
    rename_file_storage = False
5943
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
5944
        self.op.new_name != inst.name):
5945
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5946
      rename_file_storage = True
5947

    
5948
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5949
    # Change the instance lock. This is definitely safe while we hold the BGL.
5950
    # Otherwise the new lock would have to be added in acquired mode.
5951
    assert self.REQ_BGL
5952
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
5953
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5954

    
5955
    # re-read the instance from the configuration after rename
5956
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5957

    
5958
    if rename_file_storage:
5959
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5960
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5961
                                                     old_file_storage_dir,
5962
                                                     new_file_storage_dir)
5963
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5964
                   " (but the instance has been renamed in Ganeti)" %
5965
                   (inst.primary_node, old_file_storage_dir,
5966
                    new_file_storage_dir))
5967

    
5968
    _StartInstanceDisks(self, inst, None)
5969
    try:
5970
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5971
                                                 old_name, self.op.debug_level)
5972
      msg = result.fail_msg
5973
      if msg:
5974
        msg = ("Could not run OS rename script for instance %s on node %s"
5975
               " (but the instance has been renamed in Ganeti): %s" %
5976
               (inst.name, inst.primary_node, msg))
5977
        self.proc.LogWarning(msg)
5978
    finally:
5979
      _ShutdownInstanceDisks(self, inst)
5980

    
5981
    return inst.name
5982

    
5983

    
5984
class LUInstanceRemove(LogicalUnit):
5985
  """Remove an instance.
5986

5987
  """
5988
  HPATH = "instance-remove"
5989
  HTYPE = constants.HTYPE_INSTANCE
5990
  REQ_BGL = False
5991

    
5992
  def ExpandNames(self):
5993
    self._ExpandAndLockInstance()
5994
    self.needed_locks[locking.LEVEL_NODE] = []
5995
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5996

    
5997
  def DeclareLocks(self, level):
5998
    if level == locking.LEVEL_NODE:
5999
      self._LockInstancesNodes()
6000

    
6001
  def BuildHooksEnv(self):
6002
    """Build hooks env.
6003

6004
    This runs on master, primary and secondary nodes of the instance.
6005

6006
    """
6007
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6008
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6009
    return env
6010

    
6011
  def BuildHooksNodes(self):
6012
    """Build hooks nodes.
6013

6014
    """
6015
    nl = [self.cfg.GetMasterNode()]
6016
    nl_post = list(self.instance.all_nodes) + nl
6017
    return (nl, nl_post)
6018

    
6019
  def CheckPrereq(self):
6020
    """Check prerequisites.
6021

6022
    This checks that the instance is in the cluster.
6023

6024
    """
6025
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6026
    assert self.instance is not None, \
6027
      "Cannot retrieve locked instance %s" % self.op.instance_name
6028

    
6029
  def Exec(self, feedback_fn):
6030
    """Remove the instance.
6031

6032
    """
6033
    instance = self.instance
6034
    logging.info("Shutting down instance %s on node %s",
6035
                 instance.name, instance.primary_node)
6036

    
6037
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6038
                                             self.op.shutdown_timeout)
6039
    msg = result.fail_msg
6040
    if msg:
6041
      if self.op.ignore_failures:
6042
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6043
      else:
6044
        raise errors.OpExecError("Could not shutdown instance %s on"
6045
                                 " node %s: %s" %
6046
                                 (instance.name, instance.primary_node, msg))
6047

    
6048
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6049

    
6050

    
6051
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6052
  """Utility function to remove an instance.
6053

6054
  """
6055
  logging.info("Removing block devices for instance %s", instance.name)
6056

    
6057
  if not _RemoveDisks(lu, instance):
6058
    if not ignore_failures:
6059
      raise errors.OpExecError("Can't remove instance's disks")
6060
    feedback_fn("Warning: can't remove instance's disks")
6061

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

    
6064
  lu.cfg.RemoveInstance(instance.name)
6065

    
6066
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6067
    "Instance lock removal conflict"
6068

    
6069
  # Remove lock for the instance
6070
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6071

    
6072

    
6073
class LUInstanceQuery(NoHooksLU):
6074
  """Logical unit for querying instances.
6075

6076
  """
6077
  # pylint: disable-msg=W0142
6078
  REQ_BGL = False
6079

    
6080
  def CheckArguments(self):
6081
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6082
                             self.op.output_fields, self.op.use_locking)
6083

    
6084
  def ExpandNames(self):
6085
    self.iq.ExpandNames(self)
6086

    
6087
  def DeclareLocks(self, level):
6088
    self.iq.DeclareLocks(self, level)
6089

    
6090
  def Exec(self, feedback_fn):
6091
    return self.iq.OldStyleQuery(self)
6092

    
6093

    
6094
class LUInstanceFailover(LogicalUnit):
6095
  """Failover an instance.
6096

6097
  """
6098
  HPATH = "instance-failover"
6099
  HTYPE = constants.HTYPE_INSTANCE
6100
  REQ_BGL = False
6101

    
6102
  def CheckArguments(self):
6103
    """Check the arguments.
6104

6105
    """
6106
    self.iallocator = getattr(self.op, "iallocator", None)
6107
    self.target_node = getattr(self.op, "target_node", None)
6108

    
6109
  def ExpandNames(self):
6110
    self._ExpandAndLockInstance()
6111

    
6112
    if self.op.target_node is not None:
6113
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6114

    
6115
    self.needed_locks[locking.LEVEL_NODE] = []
6116
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6117

    
6118
    ignore_consistency = self.op.ignore_consistency
6119
    shutdown_timeout = self.op.shutdown_timeout
6120
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6121
                                       cleanup=False,
6122
                                       failover=True,
6123
                                       ignore_consistency=ignore_consistency,
6124
                                       shutdown_timeout=shutdown_timeout)
6125
    self.tasklets = [self._migrater]
6126

    
6127
  def DeclareLocks(self, level):
6128
    if level == locking.LEVEL_NODE:
6129
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6130
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6131
        if self.op.target_node is None:
6132
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6133
        else:
6134
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6135
                                                   self.op.target_node]
6136
        del self.recalculate_locks[locking.LEVEL_NODE]
6137
      else:
6138
        self._LockInstancesNodes()
6139

    
6140
  def BuildHooksEnv(self):
6141
    """Build hooks env.
6142

6143
    This runs on master, primary and secondary nodes of the instance.
6144

6145
    """
6146
    instance = self._migrater.instance
6147
    source_node = instance.primary_node
6148
    target_node = self.op.target_node
6149
    env = {
6150
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6151
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6152
      "OLD_PRIMARY": source_node,
6153
      "NEW_PRIMARY": target_node,
6154
      }
6155

    
6156
    if instance.disk_template in constants.DTS_INT_MIRROR:
6157
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6158
      env["NEW_SECONDARY"] = source_node
6159
    else:
6160
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6161

    
6162
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6163

    
6164
    return env
6165

    
6166
  def BuildHooksNodes(self):
6167
    """Build hooks nodes.
6168

6169
    """
6170
    instance = self._migrater.instance
6171
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6172
    return (nl, nl + [instance.primary_node])
6173

    
6174

    
6175
class LUInstanceMigrate(LogicalUnit):
6176
  """Migrate an instance.
6177

6178
  This is migration without shutting down, compared to the failover,
6179
  which is done with shutdown.
6180

6181
  """
6182
  HPATH = "instance-migrate"
6183
  HTYPE = constants.HTYPE_INSTANCE
6184
  REQ_BGL = False
6185

    
6186
  def ExpandNames(self):
6187
    self._ExpandAndLockInstance()
6188

    
6189
    if self.op.target_node is not None:
6190
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6191

    
6192
    self.needed_locks[locking.LEVEL_NODE] = []
6193
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6194

    
6195
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6196
                                       cleanup=self.op.cleanup,
6197
                                       failover=False,
6198
                                       fallback=self.op.allow_failover)
6199
    self.tasklets = [self._migrater]
6200

    
6201
  def DeclareLocks(self, level):
6202
    if level == locking.LEVEL_NODE:
6203
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6204
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6205
        if self.op.target_node is None:
6206
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6207
        else:
6208
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6209
                                                   self.op.target_node]
6210
        del self.recalculate_locks[locking.LEVEL_NODE]
6211
      else:
6212
        self._LockInstancesNodes()
6213

    
6214
  def BuildHooksEnv(self):
6215
    """Build hooks env.
6216

6217
    This runs on master, primary and secondary nodes of the instance.
6218

6219
    """
6220
    instance = self._migrater.instance
6221
    source_node = instance.primary_node
6222
    target_node = self.op.target_node
6223
    env = _BuildInstanceHookEnvByObject(self, instance)
6224
    env.update({
6225
      "MIGRATE_LIVE": self._migrater.live,
6226
      "MIGRATE_CLEANUP": self.op.cleanup,
6227
      "OLD_PRIMARY": source_node,
6228
      "NEW_PRIMARY": target_node,
6229
      })
6230

    
6231
    if instance.disk_template in constants.DTS_INT_MIRROR:
6232
      env["OLD_SECONDARY"] = target_node
6233
      env["NEW_SECONDARY"] = source_node
6234
    else:
6235
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6236

    
6237
    return env
6238

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

6242
    """
6243
    instance = self._migrater.instance
6244
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6245
    return (nl, nl + [instance.primary_node])
6246

    
6247

    
6248
class LUInstanceMove(LogicalUnit):
6249
  """Move an instance by data-copying.
6250

6251
  """
6252
  HPATH = "instance-move"
6253
  HTYPE = constants.HTYPE_INSTANCE
6254
  REQ_BGL = False
6255

    
6256
  def ExpandNames(self):
6257
    self._ExpandAndLockInstance()
6258
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6259
    self.op.target_node = target_node
6260
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6261
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6262

    
6263
  def DeclareLocks(self, level):
6264
    if level == locking.LEVEL_NODE:
6265
      self._LockInstancesNodes(primary_only=True)
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
    env = {
6274
      "TARGET_NODE": self.op.target_node,
6275
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6276
      }
6277
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6278
    return env
6279

    
6280
  def BuildHooksNodes(self):
6281
    """Build hooks nodes.
6282

6283
    """
6284
    nl = [
6285
      self.cfg.GetMasterNode(),
6286
      self.instance.primary_node,
6287
      self.op.target_node,
6288
      ]
6289
    return (nl, nl)
6290

    
6291
  def CheckPrereq(self):
6292
    """Check prerequisites.
6293

6294
    This checks that the instance is in the cluster.
6295

6296
    """
6297
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6298
    assert self.instance is not None, \
6299
      "Cannot retrieve locked instance %s" % self.op.instance_name
6300

    
6301
    node = self.cfg.GetNodeInfo(self.op.target_node)
6302
    assert node is not None, \
6303
      "Cannot retrieve locked node %s" % self.op.target_node
6304

    
6305
    self.target_node = target_node = node.name
6306

    
6307
    if target_node == instance.primary_node:
6308
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6309
                                 (instance.name, target_node),
6310
                                 errors.ECODE_STATE)
6311

    
6312
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6313

    
6314
    for idx, dsk in enumerate(instance.disks):
6315
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6316
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6317
                                   " cannot copy" % idx, errors.ECODE_STATE)
6318

    
6319
    _CheckNodeOnline(self, target_node)
6320
    _CheckNodeNotDrained(self, target_node)
6321
    _CheckNodeVmCapable(self, target_node)
6322

    
6323
    if instance.admin_up:
6324
      # check memory requirements on the secondary node
6325
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6326
                           instance.name, bep[constants.BE_MEMORY],
6327
                           instance.hypervisor)
6328
    else:
6329
      self.LogInfo("Not checking memory on the secondary node as"
6330
                   " instance will not be started")
6331

    
6332
    # check bridge existance
6333
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6334

    
6335
  def Exec(self, feedback_fn):
6336
    """Move an instance.
6337

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

6341
    """
6342
    instance = self.instance
6343

    
6344
    source_node = instance.primary_node
6345
    target_node = self.target_node
6346

    
6347
    self.LogInfo("Shutting down instance %s on source node %s",
6348
                 instance.name, source_node)
6349

    
6350
    result = self.rpc.call_instance_shutdown(source_node, instance,
6351
                                             self.op.shutdown_timeout)
6352
    msg = result.fail_msg
6353
    if msg:
6354
      if self.op.ignore_consistency:
6355
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6356
                             " Proceeding anyway. Please make sure node"
6357
                             " %s is down. Error details: %s",
6358
                             instance.name, source_node, source_node, msg)
6359
      else:
6360
        raise errors.OpExecError("Could not shutdown instance %s on"
6361
                                 " node %s: %s" %
6362
                                 (instance.name, source_node, msg))
6363

    
6364
    # create the target disks
6365
    try:
6366
      _CreateDisks(self, instance, target_node=target_node)
6367
    except errors.OpExecError:
6368
      self.LogWarning("Device creation failed, reverting...")
6369
      try:
6370
        _RemoveDisks(self, instance, target_node=target_node)
6371
      finally:
6372
        self.cfg.ReleaseDRBDMinors(instance.name)
6373
        raise
6374

    
6375
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6376

    
6377
    errs = []
6378
    # activate, get path, copy the data over
6379
    for idx, disk in enumerate(instance.disks):
6380
      self.LogInfo("Copying data for disk %d", idx)
6381
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6382
                                               instance.name, True, idx)
6383
      if result.fail_msg:
6384
        self.LogWarning("Can't assemble newly created disk %d: %s",
6385
                        idx, result.fail_msg)
6386
        errs.append(result.fail_msg)
6387
        break
6388
      dev_path = result.payload
6389
      result = self.rpc.call_blockdev_export(source_node, disk,
6390
                                             target_node, dev_path,
6391
                                             cluster_name)
6392
      if result.fail_msg:
6393
        self.LogWarning("Can't copy data over for disk %d: %s",
6394
                        idx, result.fail_msg)
6395
        errs.append(result.fail_msg)
6396
        break
6397

    
6398
    if errs:
6399
      self.LogWarning("Some disks failed to copy, aborting")
6400
      try:
6401
        _RemoveDisks(self, instance, target_node=target_node)
6402
      finally:
6403
        self.cfg.ReleaseDRBDMinors(instance.name)
6404
        raise errors.OpExecError("Errors during disk copy: %s" %
6405
                                 (",".join(errs),))
6406

    
6407
    instance.primary_node = target_node
6408
    self.cfg.Update(instance, feedback_fn)
6409

    
6410
    self.LogInfo("Removing the disks on the original node")
6411
    _RemoveDisks(self, instance, target_node=source_node)
6412

    
6413
    # Only start the instance if it's marked as up
6414
    if instance.admin_up:
6415
      self.LogInfo("Starting instance %s on node %s",
6416
                   instance.name, target_node)
6417

    
6418
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6419
                                           ignore_secondaries=True)
6420
      if not disks_ok:
6421
        _ShutdownInstanceDisks(self, instance)
6422
        raise errors.OpExecError("Can't activate the instance's disks")
6423

    
6424
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6425
      msg = result.fail_msg
6426
      if msg:
6427
        _ShutdownInstanceDisks(self, instance)
6428
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6429
                                 (instance.name, target_node, msg))
6430

    
6431

    
6432
class LUNodeMigrate(LogicalUnit):
6433
  """Migrate all instances from a node.
6434

6435
  """
6436
  HPATH = "node-migrate"
6437
  HTYPE = constants.HTYPE_NODE
6438
  REQ_BGL = False
6439

    
6440
  def CheckArguments(self):
6441
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6442

    
6443
  def ExpandNames(self):
6444
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6445

    
6446
    self.needed_locks = {}
6447

    
6448
    # Create tasklets for migrating instances for all instances on this node
6449
    names = []
6450
    tasklets = []
6451

    
6452
    self.lock_all_nodes = False
6453

    
6454
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6455
      logging.debug("Migrating instance %s", inst.name)
6456
      names.append(inst.name)
6457

    
6458
      tasklets.append(TLMigrateInstance(self, inst.name, cleanup=False))
6459

    
6460
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6461
        # We need to lock all nodes, as the iallocator will choose the
6462
        # destination nodes afterwards
6463
        self.lock_all_nodes = True
6464

    
6465
    self.tasklets = tasklets
6466

    
6467
    # Declare node locks
6468
    if self.lock_all_nodes:
6469
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6470
    else:
6471
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6472
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6473

    
6474
    # Declare instance locks
6475
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6476

    
6477
  def DeclareLocks(self, level):
6478
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6479
      self._LockInstancesNodes()
6480

    
6481
  def BuildHooksEnv(self):
6482
    """Build hooks env.
6483

6484
    This runs on the master, the primary and all the secondaries.
6485

6486
    """
6487
    return {
6488
      "NODE_NAME": self.op.node_name,
6489
      }
6490

    
6491
  def BuildHooksNodes(self):
6492
    """Build hooks nodes.
6493

6494
    """
6495
    nl = [self.cfg.GetMasterNode()]
6496
    return (nl, nl)
6497

    
6498

    
6499
class TLMigrateInstance(Tasklet):
6500
  """Tasklet class for instance migration.
6501

6502
  @type live: boolean
6503
  @ivar live: whether the migration will be done live or non-live;
6504
      this variable is initalized only after CheckPrereq has run
6505
  @type cleanup: boolean
6506
  @ivar cleanup: Wheater we cleanup from a failed migration
6507
  @type iallocator: string
6508
  @ivar iallocator: The iallocator used to determine target_node
6509
  @type target_node: string
6510
  @ivar target_node: If given, the target_node to reallocate the instance to
6511
  @type failover: boolean
6512
  @ivar failover: Whether operation results in failover or migration
6513
  @type fallback: boolean
6514
  @ivar fallback: Whether fallback to failover is allowed if migration not
6515
                  possible
6516
  @type ignore_consistency: boolean
6517
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6518
                            and target node
6519
  @type shutdown_timeout: int
6520
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6521

6522
  """
6523
  def __init__(self, lu, instance_name, cleanup=False,
6524
               failover=False, fallback=False,
6525
               ignore_consistency=False,
6526
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6527
    """Initializes this class.
6528

6529
    """
6530
    Tasklet.__init__(self, lu)
6531

    
6532
    # Parameters
6533
    self.instance_name = instance_name
6534
    self.cleanup = cleanup
6535
    self.live = False # will be overridden later
6536
    self.failover = failover
6537
    self.fallback = fallback
6538
    self.ignore_consistency = ignore_consistency
6539
    self.shutdown_timeout = shutdown_timeout
6540

    
6541
  def CheckPrereq(self):
6542
    """Check prerequisites.
6543

6544
    This checks that the instance is in the cluster.
6545

6546
    """
6547
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6548
    instance = self.cfg.GetInstanceInfo(instance_name)
6549
    assert instance is not None
6550
    self.instance = instance
6551

    
6552
    if (not self.cleanup and not instance.admin_up and not self.failover and
6553
        self.fallback):
6554
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6555
                      " to failover")
6556
      self.failover = True
6557

    
6558
    if instance.disk_template not in constants.DTS_MIRRORED:
6559
      if self.failover:
6560
        text = "failovers"
6561
      else:
6562
        text = "migrations"
6563
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6564
                                 " %s" % (instance.disk_template, text),
6565
                                 errors.ECODE_STATE)
6566

    
6567
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6568
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6569

    
6570
      if self.lu.op.iallocator:
6571
        self._RunAllocator()
6572
      else:
6573
        # We set set self.target_node as it is required by
6574
        # BuildHooksEnv
6575
        self.target_node = self.lu.op.target_node
6576

    
6577
      # self.target_node is already populated, either directly or by the
6578
      # iallocator run
6579
      target_node = self.target_node
6580
      if self.target_node == instance.primary_node:
6581
        raise errors.OpPrereqError("Cannot migrate instance %s"
6582
                                   " to its primary (%s)" %
6583
                                   (instance.name, instance.primary_node))
6584

    
6585
      if len(self.lu.tasklets) == 1:
6586
        # It is safe to release locks only when we're the only tasklet
6587
        # in the LU
6588
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6589
                      keep=[instance.primary_node, self.target_node])
6590

    
6591
    else:
6592
      secondary_nodes = instance.secondary_nodes
6593
      if not secondary_nodes:
6594
        raise errors.ConfigurationError("No secondary node but using"
6595
                                        " %s disk template" %
6596
                                        instance.disk_template)
6597
      target_node = secondary_nodes[0]
6598
      if self.lu.op.iallocator or (self.lu.op.target_node and
6599
                                   self.lu.op.target_node != target_node):
6600
        if self.failover:
6601
          text = "failed over"
6602
        else:
6603
          text = "migrated"
6604
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6605
                                   " be %s to arbitrary nodes"
6606
                                   " (neither an iallocator nor a target"
6607
                                   " node can be passed)" %
6608
                                   (instance.disk_template, text),
6609
                                   errors.ECODE_INVAL)
6610

    
6611
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6612

    
6613
    # check memory requirements on the secondary node
6614
    if not self.failover or instance.admin_up:
6615
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6616
                           instance.name, i_be[constants.BE_MEMORY],
6617
                           instance.hypervisor)
6618
    else:
6619
      self.lu.LogInfo("Not checking memory on the secondary node as"
6620
                      " instance will not be started")
6621

    
6622
    # check bridge existance
6623
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6624

    
6625
    if not self.cleanup:
6626
      _CheckNodeNotDrained(self.lu, target_node)
6627
      if not self.failover:
6628
        result = self.rpc.call_instance_migratable(instance.primary_node,
6629
                                                   instance)
6630
        if result.fail_msg and self.fallback:
6631
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6632
                          " failover")
6633
          self.failover = True
6634
        else:
6635
          result.Raise("Can't migrate, please use failover",
6636
                       prereq=True, ecode=errors.ECODE_STATE)
6637

    
6638
    assert not (self.failover and self.cleanup)
6639

    
6640
    if not self.failover:
6641
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6642
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6643
                                   " parameters are accepted",
6644
                                   errors.ECODE_INVAL)
6645
      if self.lu.op.live is not None:
6646
        if self.lu.op.live:
6647
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6648
        else:
6649
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6650
        # reset the 'live' parameter to None so that repeated
6651
        # invocations of CheckPrereq do not raise an exception
6652
        self.lu.op.live = None
6653
      elif self.lu.op.mode is None:
6654
        # read the default value from the hypervisor
6655
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6656
                                                skip_globals=False)
6657
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6658

    
6659
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6660
    else:
6661
      # Failover is never live
6662
      self.live = False
6663

    
6664
  def _RunAllocator(self):
6665
    """Run the allocator based on input opcode.
6666

6667
    """
6668
    ial = IAllocator(self.cfg, self.rpc,
6669
                     mode=constants.IALLOCATOR_MODE_RELOC,
6670
                     name=self.instance_name,
6671
                     # TODO See why hail breaks with a single node below
6672
                     relocate_from=[self.instance.primary_node,
6673
                                    self.instance.primary_node],
6674
                     )
6675

    
6676
    ial.Run(self.lu.op.iallocator)
6677

    
6678
    if not ial.success:
6679
      raise errors.OpPrereqError("Can't compute nodes using"
6680
                                 " iallocator '%s': %s" %
6681
                                 (self.lu.op.iallocator, ial.info),
6682
                                 errors.ECODE_NORES)
6683
    if len(ial.result) != ial.required_nodes:
6684
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6685
                                 " of nodes (%s), required %s" %
6686
                                 (self.lu.op.iallocator, len(ial.result),
6687
                                  ial.required_nodes), errors.ECODE_FAULT)
6688
    self.target_node = ial.result[0]
6689
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6690
                 self.instance_name, self.lu.op.iallocator,
6691
                 utils.CommaJoin(ial.result))
6692

    
6693
  def _WaitUntilSync(self):
6694
    """Poll with custom rpc for disk sync.
6695

6696
    This uses our own step-based rpc call.
6697

6698
    """
6699
    self.feedback_fn("* wait until resync is done")
6700
    all_done = False
6701
    while not all_done:
6702
      all_done = True
6703
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6704
                                            self.nodes_ip,
6705
                                            self.instance.disks)
6706
      min_percent = 100
6707
      for node, nres in result.items():
6708
        nres.Raise("Cannot resync disks on node %s" % node)
6709
        node_done, node_percent = nres.payload
6710
        all_done = all_done and node_done
6711
        if node_percent is not None:
6712
          min_percent = min(min_percent, node_percent)
6713
      if not all_done:
6714
        if min_percent < 100:
6715
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6716
        time.sleep(2)
6717

    
6718
  def _EnsureSecondary(self, node):
6719
    """Demote a node to secondary.
6720

6721
    """
6722
    self.feedback_fn("* switching node %s to secondary mode" % node)
6723

    
6724
    for dev in self.instance.disks:
6725
      self.cfg.SetDiskID(dev, node)
6726

    
6727
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6728
                                          self.instance.disks)
6729
    result.Raise("Cannot change disk to secondary on node %s" % node)
6730

    
6731
  def _GoStandalone(self):
6732
    """Disconnect from the network.
6733

6734
    """
6735
    self.feedback_fn("* changing into standalone mode")
6736
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6737
                                               self.instance.disks)
6738
    for node, nres in result.items():
6739
      nres.Raise("Cannot disconnect disks node %s" % node)
6740

    
6741
  def _GoReconnect(self, multimaster):
6742
    """Reconnect to the network.
6743

6744
    """
6745
    if multimaster:
6746
      msg = "dual-master"
6747
    else:
6748
      msg = "single-master"
6749
    self.feedback_fn("* changing disks into %s mode" % msg)
6750
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6751
                                           self.instance.disks,
6752
                                           self.instance.name, multimaster)
6753
    for node, nres in result.items():
6754
      nres.Raise("Cannot change disks config on node %s" % node)
6755

    
6756
  def _ExecCleanup(self):
6757
    """Try to cleanup after a failed migration.
6758

6759
    The cleanup is done by:
6760
      - check that the instance is running only on one node
6761
        (and update the config if needed)
6762
      - change disks on its secondary node to secondary
6763
      - wait until disks are fully synchronized
6764
      - disconnect from the network
6765
      - change disks into single-master mode
6766
      - wait again until disks are fully synchronized
6767

6768
    """
6769
    instance = self.instance
6770
    target_node = self.target_node
6771
    source_node = self.source_node
6772

    
6773
    # check running on only one node
6774
    self.feedback_fn("* checking where the instance actually runs"
6775
                     " (if this hangs, the hypervisor might be in"
6776
                     " a bad state)")
6777
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6778
    for node, result in ins_l.items():
6779
      result.Raise("Can't contact node %s" % node)
6780

    
6781
    runningon_source = instance.name in ins_l[source_node].payload
6782
    runningon_target = instance.name in ins_l[target_node].payload
6783

    
6784
    if runningon_source and runningon_target:
6785
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6786
                               " or the hypervisor is confused; you will have"
6787
                               " to ensure manually that it runs only on one"
6788
                               " and restart this operation")
6789

    
6790
    if not (runningon_source or runningon_target):
6791
      raise errors.OpExecError("Instance does not seem to be running at all;"
6792
                               " in this case it's safer to repair by"
6793
                               " running 'gnt-instance stop' to ensure disk"
6794
                               " shutdown, and then restarting it")
6795

    
6796
    if runningon_target:
6797
      # the migration has actually succeeded, we need to update the config
6798
      self.feedback_fn("* instance running on secondary node (%s),"
6799
                       " updating config" % target_node)
6800
      instance.primary_node = target_node
6801
      self.cfg.Update(instance, self.feedback_fn)
6802
      demoted_node = source_node
6803
    else:
6804
      self.feedback_fn("* instance confirmed to be running on its"
6805
                       " primary node (%s)" % source_node)
6806
      demoted_node = target_node
6807

    
6808
    if instance.disk_template in constants.DTS_INT_MIRROR:
6809
      self._EnsureSecondary(demoted_node)
6810
      try:
6811
        self._WaitUntilSync()
6812
      except errors.OpExecError:
6813
        # we ignore here errors, since if the device is standalone, it
6814
        # won't be able to sync
6815
        pass
6816
      self._GoStandalone()
6817
      self._GoReconnect(False)
6818
      self._WaitUntilSync()
6819

    
6820
    self.feedback_fn("* done")
6821

    
6822
  def _RevertDiskStatus(self):
6823
    """Try to revert the disk status after a failed migration.
6824

6825
    """
6826
    target_node = self.target_node
6827
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
6828
      return
6829

    
6830
    try:
6831
      self._EnsureSecondary(target_node)
6832
      self._GoStandalone()
6833
      self._GoReconnect(False)
6834
      self._WaitUntilSync()
6835
    except errors.OpExecError, err:
6836
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
6837
                         " please try to recover the instance manually;"
6838
                         " error '%s'" % str(err))
6839

    
6840
  def _AbortMigration(self):
6841
    """Call the hypervisor code to abort a started migration.
6842

6843
    """
6844
    instance = self.instance
6845
    target_node = self.target_node
6846
    migration_info = self.migration_info
6847

    
6848
    abort_result = self.rpc.call_finalize_migration(target_node,
6849
                                                    instance,
6850
                                                    migration_info,
6851
                                                    False)
6852
    abort_msg = abort_result.fail_msg
6853
    if abort_msg:
6854
      logging.error("Aborting migration failed on target node %s: %s",
6855
                    target_node, abort_msg)
6856
      # Don't raise an exception here, as we stil have to try to revert the
6857
      # disk status, even if this step failed.
6858

    
6859
  def _ExecMigration(self):
6860
    """Migrate an instance.
6861

6862
    The migrate is done by:
6863
      - change the disks into dual-master mode
6864
      - wait until disks are fully synchronized again
6865
      - migrate the instance
6866
      - change disks on the new secondary node (the old primary) to secondary
6867
      - wait until disks are fully synchronized
6868
      - change disks into single-master mode
6869

6870
    """
6871
    instance = self.instance
6872
    target_node = self.target_node
6873
    source_node = self.source_node
6874

    
6875
    self.feedback_fn("* checking disk consistency between source and target")
6876
    for dev in instance.disks:
6877
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6878
        raise errors.OpExecError("Disk %s is degraded or not fully"
6879
                                 " synchronized on target node,"
6880
                                 " aborting migration" % dev.iv_name)
6881

    
6882
    # First get the migration information from the remote node
6883
    result = self.rpc.call_migration_info(source_node, instance)
6884
    msg = result.fail_msg
6885
    if msg:
6886
      log_err = ("Failed fetching source migration information from %s: %s" %
6887
                 (source_node, msg))
6888
      logging.error(log_err)
6889
      raise errors.OpExecError(log_err)
6890

    
6891
    self.migration_info = migration_info = result.payload
6892

    
6893
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6894
      # Then switch the disks to master/master mode
6895
      self._EnsureSecondary(target_node)
6896
      self._GoStandalone()
6897
      self._GoReconnect(True)
6898
      self._WaitUntilSync()
6899

    
6900
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6901
    result = self.rpc.call_accept_instance(target_node,
6902
                                           instance,
6903
                                           migration_info,
6904
                                           self.nodes_ip[target_node])
6905

    
6906
    msg = result.fail_msg
6907
    if msg:
6908
      logging.error("Instance pre-migration failed, trying to revert"
6909
                    " disk status: %s", msg)
6910
      self.feedback_fn("Pre-migration failed, aborting")
6911
      self._AbortMigration()
6912
      self._RevertDiskStatus()
6913
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6914
                               (instance.name, msg))
6915

    
6916
    self.feedback_fn("* migrating instance to %s" % target_node)
6917
    result = self.rpc.call_instance_migrate(source_node, instance,
6918
                                            self.nodes_ip[target_node],
6919
                                            self.live)
6920
    msg = result.fail_msg
6921
    if msg:
6922
      logging.error("Instance migration failed, trying to revert"
6923
                    " disk status: %s", msg)
6924
      self.feedback_fn("Migration failed, aborting")
6925
      self._AbortMigration()
6926
      self._RevertDiskStatus()
6927
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6928
                               (instance.name, msg))
6929

    
6930
    instance.primary_node = target_node
6931
    # distribute new instance config to the other nodes
6932
    self.cfg.Update(instance, self.feedback_fn)
6933

    
6934
    result = self.rpc.call_finalize_migration(target_node,
6935
                                              instance,
6936
                                              migration_info,
6937
                                              True)
6938
    msg = result.fail_msg
6939
    if msg:
6940
      logging.error("Instance migration succeeded, but finalization failed:"
6941
                    " %s", msg)
6942
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6943
                               msg)
6944

    
6945
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6946
      self._EnsureSecondary(source_node)
6947
      self._WaitUntilSync()
6948
      self._GoStandalone()
6949
      self._GoReconnect(False)
6950
      self._WaitUntilSync()
6951

    
6952
    self.feedback_fn("* done")
6953

    
6954
  def _ExecFailover(self):
6955
    """Failover an instance.
6956

6957
    The failover is done by shutting it down on its present node and
6958
    starting it on the secondary.
6959

6960
    """
6961
    instance = self.instance
6962
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
6963

    
6964
    source_node = instance.primary_node
6965
    target_node = self.target_node
6966

    
6967
    if instance.admin_up:
6968
      self.feedback_fn("* checking disk consistency between source and target")
6969
      for dev in instance.disks:
6970
        # for drbd, these are drbd over lvm
6971
        if not _CheckDiskConsistency(self, dev, target_node, False):
6972
          if not self.ignore_consistency:
6973
            raise errors.OpExecError("Disk %s is degraded on target node,"
6974
                                     " aborting failover" % dev.iv_name)
6975
    else:
6976
      self.feedback_fn("* not checking disk consistency as instance is not"
6977
                       " running")
6978

    
6979
    self.feedback_fn("* shutting down instance on source node")
6980
    logging.info("Shutting down instance %s on node %s",
6981
                 instance.name, source_node)
6982

    
6983
    result = self.rpc.call_instance_shutdown(source_node, instance,
6984
                                             self.shutdown_timeout)
6985
    msg = result.fail_msg
6986
    if msg:
6987
      if self.ignore_consistency or primary_node.offline:
6988
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
6989
                           " proceeding anyway; please make sure node"
6990
                           " %s is down; error details: %s",
6991
                           instance.name, source_node, source_node, msg)
6992
      else:
6993
        raise errors.OpExecError("Could not shutdown instance %s on"
6994
                                 " node %s: %s" %
6995
                                 (instance.name, source_node, msg))
6996

    
6997
    self.feedback_fn("* deactivating the instance's disks on source node")
6998
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
6999
      raise errors.OpExecError("Can't shut down the instance's disks.")
7000

    
7001
    instance.primary_node = target_node
7002
    # distribute new instance config to the other nodes
7003
    self.cfg.Update(instance, self.feedback_fn)
7004

    
7005
    # Only start the instance if it's marked as up
7006
    if instance.admin_up:
7007
      self.feedback_fn("* activating the instance's disks on target node")
7008
      logging.info("Starting instance %s on node %s",
7009
                   instance.name, target_node)
7010

    
7011
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7012
                                           ignore_secondaries=True)
7013
      if not disks_ok:
7014
        _ShutdownInstanceDisks(self, instance)
7015
        raise errors.OpExecError("Can't activate the instance's disks")
7016

    
7017
      self.feedback_fn("* starting the instance on the target node")
7018
      result = self.rpc.call_instance_start(target_node, instance, None, None)
7019
      msg = result.fail_msg
7020
      if msg:
7021
        _ShutdownInstanceDisks(self, instance)
7022
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7023
                                 (instance.name, target_node, msg))
7024

    
7025
  def Exec(self, feedback_fn):
7026
    """Perform the migration.
7027

7028
    """
7029
    self.feedback_fn = feedback_fn
7030
    self.source_node = self.instance.primary_node
7031

    
7032
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7033
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7034
      self.target_node = self.instance.secondary_nodes[0]
7035
      # Otherwise self.target_node has been populated either
7036
      # directly, or through an iallocator.
7037

    
7038
    self.all_nodes = [self.source_node, self.target_node]
7039
    self.nodes_ip = {
7040
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7041
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7042
      }
7043

    
7044
    if self.failover:
7045
      feedback_fn("Failover instance %s" % self.instance.name)
7046
      self._ExecFailover()
7047
    else:
7048
      feedback_fn("Migrating instance %s" % self.instance.name)
7049

    
7050
      if self.cleanup:
7051
        return self._ExecCleanup()
7052
      else:
7053
        return self._ExecMigration()
7054

    
7055

    
7056
def _CreateBlockDev(lu, node, instance, device, force_create,
7057
                    info, force_open):
7058
  """Create a tree of block devices on a given node.
7059

7060
  If this device type has to be created on secondaries, create it and
7061
  all its children.
7062

7063
  If not, just recurse to children keeping the same 'force' value.
7064

7065
  @param lu: the lu on whose behalf we execute
7066
  @param node: the node on which to create the device
7067
  @type instance: L{objects.Instance}
7068
  @param instance: the instance which owns the device
7069
  @type device: L{objects.Disk}
7070
  @param device: the device to create
7071
  @type force_create: boolean
7072
  @param force_create: whether to force creation of this device; this
7073
      will be change to True whenever we find a device which has
7074
      CreateOnSecondary() attribute
7075
  @param info: the extra 'metadata' we should attach to the device
7076
      (this will be represented as a LVM tag)
7077
  @type force_open: boolean
7078
  @param force_open: this parameter will be passes to the
7079
      L{backend.BlockdevCreate} function where it specifies
7080
      whether we run on primary or not, and it affects both
7081
      the child assembly and the device own Open() execution
7082

7083
  """
7084
  if device.CreateOnSecondary():
7085
    force_create = True
7086

    
7087
  if device.children:
7088
    for child in device.children:
7089
      _CreateBlockDev(lu, node, instance, child, force_create,
7090
                      info, force_open)
7091

    
7092
  if not force_create:
7093
    return
7094

    
7095
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7096

    
7097

    
7098
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7099
  """Create a single block device on a given node.
7100

7101
  This will not recurse over children of the device, so they must be
7102
  created in advance.
7103

7104
  @param lu: the lu on whose behalf we execute
7105
  @param node: the node on which to create the device
7106
  @type instance: L{objects.Instance}
7107
  @param instance: the instance which owns the device
7108
  @type device: L{objects.Disk}
7109
  @param device: the device to create
7110
  @param info: the extra 'metadata' we should attach to the device
7111
      (this will be represented as a LVM tag)
7112
  @type force_open: boolean
7113
  @param force_open: this parameter will be passes to the
7114
      L{backend.BlockdevCreate} function where it specifies
7115
      whether we run on primary or not, and it affects both
7116
      the child assembly and the device own Open() execution
7117

7118
  """
7119
  lu.cfg.SetDiskID(device, node)
7120
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7121
                                       instance.name, force_open, info)
7122
  result.Raise("Can't create block device %s on"
7123
               " node %s for instance %s" % (device, node, instance.name))
7124
  if device.physical_id is None:
7125
    device.physical_id = result.payload
7126

    
7127

    
7128
def _GenerateUniqueNames(lu, exts):
7129
  """Generate a suitable LV name.
7130

7131
  This will generate a logical volume name for the given instance.
7132

7133
  """
7134
  results = []
7135
  for val in exts:
7136
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7137
    results.append("%s%s" % (new_id, val))
7138
  return results
7139

    
7140

    
7141
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7142
                         iv_name, p_minor, s_minor):
7143
  """Generate a drbd8 device complete with its children.
7144

7145
  """
7146
  assert len(vgnames) == len(names) == 2
7147
  port = lu.cfg.AllocatePort()
7148
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7149
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7150
                          logical_id=(vgnames[0], names[0]))
7151
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7152
                          logical_id=(vgnames[1], names[1]))
7153
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7154
                          logical_id=(primary, secondary, port,
7155
                                      p_minor, s_minor,
7156
                                      shared_secret),
7157
                          children=[dev_data, dev_meta],
7158
                          iv_name=iv_name)
7159
  return drbd_dev
7160

    
7161

    
7162
def _GenerateDiskTemplate(lu, template_name,
7163
                          instance_name, primary_node,
7164
                          secondary_nodes, disk_info,
7165
                          file_storage_dir, file_driver,
7166
                          base_index, feedback_fn):
7167
  """Generate the entire disk layout for a given template type.
7168

7169
  """
7170
  #TODO: compute space requirements
7171

    
7172
  vgname = lu.cfg.GetVGName()
7173
  disk_count = len(disk_info)
7174
  disks = []
7175
  if template_name == constants.DT_DISKLESS:
7176
    pass
7177
  elif template_name == constants.DT_PLAIN:
7178
    if len(secondary_nodes) != 0:
7179
      raise errors.ProgrammerError("Wrong template configuration")
7180

    
7181
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7182
                                      for i in range(disk_count)])
7183
    for idx, disk in enumerate(disk_info):
7184
      disk_index = idx + base_index
7185
      vg = disk.get(constants.IDISK_VG, vgname)
7186
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7187
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7188
                              size=disk[constants.IDISK_SIZE],
7189
                              logical_id=(vg, names[idx]),
7190
                              iv_name="disk/%d" % disk_index,
7191
                              mode=disk[constants.IDISK_MODE])
7192
      disks.append(disk_dev)
7193
  elif template_name == constants.DT_DRBD8:
7194
    if len(secondary_nodes) != 1:
7195
      raise errors.ProgrammerError("Wrong template configuration")
7196
    remote_node = secondary_nodes[0]
7197
    minors = lu.cfg.AllocateDRBDMinor(
7198
      [primary_node, remote_node] * len(disk_info), instance_name)
7199

    
7200
    names = []
7201
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7202
                                               for i in range(disk_count)]):
7203
      names.append(lv_prefix + "_data")
7204
      names.append(lv_prefix + "_meta")
7205
    for idx, disk in enumerate(disk_info):
7206
      disk_index = idx + base_index
7207
      data_vg = disk.get(constants.IDISK_VG, vgname)
7208
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7209
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7210
                                      disk[constants.IDISK_SIZE],
7211
                                      [data_vg, meta_vg],
7212
                                      names[idx * 2:idx * 2 + 2],
7213
                                      "disk/%d" % disk_index,
7214
                                      minors[idx * 2], minors[idx * 2 + 1])
7215
      disk_dev.mode = disk[constants.IDISK_MODE]
7216
      disks.append(disk_dev)
7217
  elif template_name == constants.DT_FILE:
7218
    if len(secondary_nodes) != 0:
7219
      raise errors.ProgrammerError("Wrong template configuration")
7220

    
7221
    opcodes.RequireFileStorage()
7222

    
7223
    for idx, disk in enumerate(disk_info):
7224
      disk_index = idx + base_index
7225
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7226
                              size=disk[constants.IDISK_SIZE],
7227
                              iv_name="disk/%d" % disk_index,
7228
                              logical_id=(file_driver,
7229
                                          "%s/disk%d" % (file_storage_dir,
7230
                                                         disk_index)),
7231
                              mode=disk[constants.IDISK_MODE])
7232
      disks.append(disk_dev)
7233
  elif template_name == constants.DT_SHARED_FILE:
7234
    if len(secondary_nodes) != 0:
7235
      raise errors.ProgrammerError("Wrong template configuration")
7236

    
7237
    opcodes.RequireSharedFileStorage()
7238

    
7239
    for idx, disk in enumerate(disk_info):
7240
      disk_index = idx + base_index
7241
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7242
                              size=disk[constants.IDISK_SIZE],
7243
                              iv_name="disk/%d" % disk_index,
7244
                              logical_id=(file_driver,
7245
                                          "%s/disk%d" % (file_storage_dir,
7246
                                                         disk_index)),
7247
                              mode=disk[constants.IDISK_MODE])
7248
      disks.append(disk_dev)
7249
  elif template_name == constants.DT_BLOCK:
7250
    if len(secondary_nodes) != 0:
7251
      raise errors.ProgrammerError("Wrong template configuration")
7252

    
7253
    for idx, disk in enumerate(disk_info):
7254
      disk_index = idx + base_index
7255
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7256
                              size=disk[constants.IDISK_SIZE],
7257
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7258
                                          disk[constants.IDISK_ADOPT]),
7259
                              iv_name="disk/%d" % disk_index,
7260
                              mode=disk[constants.IDISK_MODE])
7261
      disks.append(disk_dev)
7262

    
7263
  else:
7264
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7265
  return disks
7266

    
7267

    
7268
def _GetInstanceInfoText(instance):
7269
  """Compute that text that should be added to the disk's metadata.
7270

7271
  """
7272
  return "originstname+%s" % instance.name
7273

    
7274

    
7275
def _CalcEta(time_taken, written, total_size):
7276
  """Calculates the ETA based on size written and total size.
7277

7278
  @param time_taken: The time taken so far
7279
  @param written: amount written so far
7280
  @param total_size: The total size of data to be written
7281
  @return: The remaining time in seconds
7282

7283
  """
7284
  avg_time = time_taken / float(written)
7285
  return (total_size - written) * avg_time
7286

    
7287

    
7288
def _WipeDisks(lu, instance):
7289
  """Wipes instance disks.
7290

7291
  @type lu: L{LogicalUnit}
7292
  @param lu: the logical unit on whose behalf we execute
7293
  @type instance: L{objects.Instance}
7294
  @param instance: the instance whose disks we should create
7295
  @return: the success of the wipe
7296

7297
  """
7298
  node = instance.primary_node
7299

    
7300
  for device in instance.disks:
7301
    lu.cfg.SetDiskID(device, node)
7302

    
7303
  logging.info("Pause sync of instance %s disks", instance.name)
7304
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7305

    
7306
  for idx, success in enumerate(result.payload):
7307
    if not success:
7308
      logging.warn("pause-sync of instance %s for disks %d failed",
7309
                   instance.name, idx)
7310

    
7311
  try:
7312
    for idx, device in enumerate(instance.disks):
7313
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7314
      # MAX_WIPE_CHUNK at max
7315
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7316
                            constants.MIN_WIPE_CHUNK_PERCENT)
7317
      # we _must_ make this an int, otherwise rounding errors will
7318
      # occur
7319
      wipe_chunk_size = int(wipe_chunk_size)
7320

    
7321
      lu.LogInfo("* Wiping disk %d", idx)
7322
      logging.info("Wiping disk %d for instance %s, node %s using"
7323
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7324

    
7325
      offset = 0
7326
      size = device.size
7327
      last_output = 0
7328
      start_time = time.time()
7329

    
7330
      while offset < size:
7331
        wipe_size = min(wipe_chunk_size, size - offset)
7332
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7333
                      idx, offset, wipe_size)
7334
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7335
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7336
                     (idx, offset, wipe_size))
7337
        now = time.time()
7338
        offset += wipe_size
7339
        if now - last_output >= 60:
7340
          eta = _CalcEta(now - start_time, offset, size)
7341
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7342
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7343
          last_output = now
7344
  finally:
7345
    logging.info("Resume sync of instance %s disks", instance.name)
7346

    
7347
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7348

    
7349
    for idx, success in enumerate(result.payload):
7350
      if not success:
7351
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7352
                      " look at the status and troubleshoot the issue", idx)
7353
        logging.warn("resume-sync of instance %s for disks %d failed",
7354
                     instance.name, idx)
7355

    
7356

    
7357
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7358
  """Create all disks for an instance.
7359

7360
  This abstracts away some work from AddInstance.
7361

7362
  @type lu: L{LogicalUnit}
7363
  @param lu: the logical unit on whose behalf we execute
7364
  @type instance: L{objects.Instance}
7365
  @param instance: the instance whose disks we should create
7366
  @type to_skip: list
7367
  @param to_skip: list of indices to skip
7368
  @type target_node: string
7369
  @param target_node: if passed, overrides the target node for creation
7370
  @rtype: boolean
7371
  @return: the success of the creation
7372

7373
  """
7374
  info = _GetInstanceInfoText(instance)
7375
  if target_node is None:
7376
    pnode = instance.primary_node
7377
    all_nodes = instance.all_nodes
7378
  else:
7379
    pnode = target_node
7380
    all_nodes = [pnode]
7381

    
7382
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
7383
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7384
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7385

    
7386
    result.Raise("Failed to create directory '%s' on"
7387
                 " node %s" % (file_storage_dir, pnode))
7388

    
7389
  # Note: this needs to be kept in sync with adding of disks in
7390
  # LUInstanceSetParams
7391
  for idx, device in enumerate(instance.disks):
7392
    if to_skip and idx in to_skip:
7393
      continue
7394
    logging.info("Creating volume %s for instance %s",
7395
                 device.iv_name, instance.name)
7396
    #HARDCODE
7397
    for node in all_nodes:
7398
      f_create = node == pnode
7399
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7400

    
7401

    
7402
def _RemoveDisks(lu, instance, target_node=None):
7403
  """Remove all disks for an instance.
7404

7405
  This abstracts away some work from `AddInstance()` and
7406
  `RemoveInstance()`. Note that in case some of the devices couldn't
7407
  be removed, the removal will continue with the other ones (compare
7408
  with `_CreateDisks()`).
7409

7410
  @type lu: L{LogicalUnit}
7411
  @param lu: the logical unit on whose behalf we execute
7412
  @type instance: L{objects.Instance}
7413
  @param instance: the instance whose disks we should remove
7414
  @type target_node: string
7415
  @param target_node: used to override the node on which to remove the disks
7416
  @rtype: boolean
7417
  @return: the success of the removal
7418

7419
  """
7420
  logging.info("Removing block devices for instance %s", instance.name)
7421

    
7422
  all_result = True
7423
  for device in instance.disks:
7424
    if target_node:
7425
      edata = [(target_node, device)]
7426
    else:
7427
      edata = device.ComputeNodeTree(instance.primary_node)
7428
    for node, disk in edata:
7429
      lu.cfg.SetDiskID(disk, node)
7430
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7431
      if msg:
7432
        lu.LogWarning("Could not remove block device %s on node %s,"
7433
                      " continuing anyway: %s", device.iv_name, node, msg)
7434
        all_result = False
7435

    
7436
  if instance.disk_template == constants.DT_FILE:
7437
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7438
    if target_node:
7439
      tgt = target_node
7440
    else:
7441
      tgt = instance.primary_node
7442
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7443
    if result.fail_msg:
7444
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7445
                    file_storage_dir, instance.primary_node, result.fail_msg)
7446
      all_result = False
7447

    
7448
  return all_result
7449

    
7450

    
7451
def _ComputeDiskSizePerVG(disk_template, disks):
7452
  """Compute disk size requirements in the volume group
7453

7454
  """
7455
  def _compute(disks, payload):
7456
    """Universal algorithm.
7457

7458
    """
7459
    vgs = {}
7460
    for disk in disks:
7461
      vgs[disk[constants.IDISK_VG]] = \
7462
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7463

    
7464
    return vgs
7465

    
7466
  # Required free disk space as a function of disk and swap space
7467
  req_size_dict = {
7468
    constants.DT_DISKLESS: {},
7469
    constants.DT_PLAIN: _compute(disks, 0),
7470
    # 128 MB are added for drbd metadata for each disk
7471
    constants.DT_DRBD8: _compute(disks, 128),
7472
    constants.DT_FILE: {},
7473
    constants.DT_SHARED_FILE: {},
7474
  }
7475

    
7476
  if disk_template not in req_size_dict:
7477
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7478
                                 " is unknown" %  disk_template)
7479

    
7480
  return req_size_dict[disk_template]
7481

    
7482

    
7483
def _ComputeDiskSize(disk_template, disks):
7484
  """Compute disk size requirements in the volume group
7485

7486
  """
7487
  # Required free disk space as a function of disk and swap space
7488
  req_size_dict = {
7489
    constants.DT_DISKLESS: None,
7490
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7491
    # 128 MB are added for drbd metadata for each disk
7492
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7493
    constants.DT_FILE: None,
7494
    constants.DT_SHARED_FILE: 0,
7495
    constants.DT_BLOCK: 0,
7496
  }
7497

    
7498
  if disk_template not in req_size_dict:
7499
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7500
                                 " is unknown" %  disk_template)
7501

    
7502
  return req_size_dict[disk_template]
7503

    
7504

    
7505
def _FilterVmNodes(lu, nodenames):
7506
  """Filters out non-vm_capable nodes from a list.
7507

7508
  @type lu: L{LogicalUnit}
7509
  @param lu: the logical unit for which we check
7510
  @type nodenames: list
7511
  @param nodenames: the list of nodes on which we should check
7512
  @rtype: list
7513
  @return: the list of vm-capable nodes
7514

7515
  """
7516
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7517
  return [name for name in nodenames if name not in vm_nodes]
7518

    
7519

    
7520
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7521
  """Hypervisor parameter validation.
7522

7523
  This function abstract the hypervisor parameter validation to be
7524
  used in both instance create and instance modify.
7525

7526
  @type lu: L{LogicalUnit}
7527
  @param lu: the logical unit for which we check
7528
  @type nodenames: list
7529
  @param nodenames: the list of nodes on which we should check
7530
  @type hvname: string
7531
  @param hvname: the name of the hypervisor we should use
7532
  @type hvparams: dict
7533
  @param hvparams: the parameters which we need to check
7534
  @raise errors.OpPrereqError: if the parameters are not valid
7535

7536
  """
7537
  nodenames = _FilterVmNodes(lu, nodenames)
7538
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7539
                                                  hvname,
7540
                                                  hvparams)
7541
  for node in nodenames:
7542
    info = hvinfo[node]
7543
    if info.offline:
7544
      continue
7545
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7546

    
7547

    
7548
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7549
  """OS parameters validation.
7550

7551
  @type lu: L{LogicalUnit}
7552
  @param lu: the logical unit for which we check
7553
  @type required: boolean
7554
  @param required: whether the validation should fail if the OS is not
7555
      found
7556
  @type nodenames: list
7557
  @param nodenames: the list of nodes on which we should check
7558
  @type osname: string
7559
  @param osname: the name of the hypervisor we should use
7560
  @type osparams: dict
7561
  @param osparams: the parameters which we need to check
7562
  @raise errors.OpPrereqError: if the parameters are not valid
7563

7564
  """
7565
  nodenames = _FilterVmNodes(lu, nodenames)
7566
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7567
                                   [constants.OS_VALIDATE_PARAMETERS],
7568
                                   osparams)
7569
  for node, nres in result.items():
7570
    # we don't check for offline cases since this should be run only
7571
    # against the master node and/or an instance's nodes
7572
    nres.Raise("OS Parameters validation failed on node %s" % node)
7573
    if not nres.payload:
7574
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7575
                 osname, node)
7576

    
7577

    
7578
class LUInstanceCreate(LogicalUnit):
7579
  """Create an instance.
7580

7581
  """
7582
  HPATH = "instance-add"
7583
  HTYPE = constants.HTYPE_INSTANCE
7584
  REQ_BGL = False
7585

    
7586
  def CheckArguments(self):
7587
    """Check arguments.
7588

7589
    """
7590
    # do not require name_check to ease forward/backward compatibility
7591
    # for tools
7592
    if self.op.no_install and self.op.start:
7593
      self.LogInfo("No-installation mode selected, disabling startup")
7594
      self.op.start = False
7595
    # validate/normalize the instance name
7596
    self.op.instance_name = \
7597
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7598

    
7599
    if self.op.ip_check and not self.op.name_check:
7600
      # TODO: make the ip check more flexible and not depend on the name check
7601
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7602
                                 " check", errors.ECODE_INVAL)
7603

    
7604
    # check nics' parameter names
7605
    for nic in self.op.nics:
7606
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7607

    
7608
    # check disks. parameter names and consistent adopt/no-adopt strategy
7609
    has_adopt = has_no_adopt = False
7610
    for disk in self.op.disks:
7611
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7612
      if constants.IDISK_ADOPT in disk:
7613
        has_adopt = True
7614
      else:
7615
        has_no_adopt = True
7616
    if has_adopt and has_no_adopt:
7617
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7618
                                 errors.ECODE_INVAL)
7619
    if has_adopt:
7620
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7621
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7622
                                   " '%s' disk template" %
7623
                                   self.op.disk_template,
7624
                                   errors.ECODE_INVAL)
7625
      if self.op.iallocator is not None:
7626
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7627
                                   " iallocator script", errors.ECODE_INVAL)
7628
      if self.op.mode == constants.INSTANCE_IMPORT:
7629
        raise errors.OpPrereqError("Disk adoption not allowed for"
7630
                                   " instance import", errors.ECODE_INVAL)
7631
    else:
7632
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7633
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7634
                                   " but no 'adopt' parameter given" %
7635
                                   self.op.disk_template,
7636
                                   errors.ECODE_INVAL)
7637

    
7638
    self.adopt_disks = has_adopt
7639

    
7640
    # instance name verification
7641
    if self.op.name_check:
7642
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7643
      self.op.instance_name = self.hostname1.name
7644
      # used in CheckPrereq for ip ping check
7645
      self.check_ip = self.hostname1.ip
7646
    else:
7647
      self.check_ip = None
7648

    
7649
    # file storage checks
7650
    if (self.op.file_driver and
7651
        not self.op.file_driver in constants.FILE_DRIVER):
7652
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7653
                                 self.op.file_driver, errors.ECODE_INVAL)
7654

    
7655
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7656
      raise errors.OpPrereqError("File storage directory path not absolute",
7657
                                 errors.ECODE_INVAL)
7658

    
7659
    ### Node/iallocator related checks
7660
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7661

    
7662
    if self.op.pnode is not None:
7663
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7664
        if self.op.snode is None:
7665
          raise errors.OpPrereqError("The networked disk templates need"
7666
                                     " a mirror node", errors.ECODE_INVAL)
7667
      elif self.op.snode:
7668
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7669
                        " template")
7670
        self.op.snode = None
7671

    
7672
    self._cds = _GetClusterDomainSecret()
7673

    
7674
    if self.op.mode == constants.INSTANCE_IMPORT:
7675
      # On import force_variant must be True, because if we forced it at
7676
      # initial install, our only chance when importing it back is that it
7677
      # works again!
7678
      self.op.force_variant = True
7679

    
7680
      if self.op.no_install:
7681
        self.LogInfo("No-installation mode has no effect during import")
7682

    
7683
    elif self.op.mode == constants.INSTANCE_CREATE:
7684
      if self.op.os_type is None:
7685
        raise errors.OpPrereqError("No guest OS specified",
7686
                                   errors.ECODE_INVAL)
7687
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7688
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7689
                                   " installation" % self.op.os_type,
7690
                                   errors.ECODE_STATE)
7691
      if self.op.disk_template is None:
7692
        raise errors.OpPrereqError("No disk template specified",
7693
                                   errors.ECODE_INVAL)
7694

    
7695
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7696
      # Check handshake to ensure both clusters have the same domain secret
7697
      src_handshake = self.op.source_handshake
7698
      if not src_handshake:
7699
        raise errors.OpPrereqError("Missing source handshake",
7700
                                   errors.ECODE_INVAL)
7701

    
7702
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7703
                                                           src_handshake)
7704
      if errmsg:
7705
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7706
                                   errors.ECODE_INVAL)
7707

    
7708
      # Load and check source CA
7709
      self.source_x509_ca_pem = self.op.source_x509_ca
7710
      if not self.source_x509_ca_pem:
7711
        raise errors.OpPrereqError("Missing source X509 CA",
7712
                                   errors.ECODE_INVAL)
7713

    
7714
      try:
7715
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7716
                                                    self._cds)
7717
      except OpenSSL.crypto.Error, err:
7718
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7719
                                   (err, ), errors.ECODE_INVAL)
7720

    
7721
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7722
      if errcode is not None:
7723
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7724
                                   errors.ECODE_INVAL)
7725

    
7726
      self.source_x509_ca = cert
7727

    
7728
      src_instance_name = self.op.source_instance_name
7729
      if not src_instance_name:
7730
        raise errors.OpPrereqError("Missing source instance name",
7731
                                   errors.ECODE_INVAL)
7732

    
7733
      self.source_instance_name = \
7734
          netutils.GetHostname(name=src_instance_name).name
7735

    
7736
    else:
7737
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7738
                                 self.op.mode, errors.ECODE_INVAL)
7739

    
7740
  def ExpandNames(self):
7741
    """ExpandNames for CreateInstance.
7742

7743
    Figure out the right locks for instance creation.
7744

7745
    """
7746
    self.needed_locks = {}
7747

    
7748
    instance_name = self.op.instance_name
7749
    # this is just a preventive check, but someone might still add this
7750
    # instance in the meantime, and creation will fail at lock-add time
7751
    if instance_name in self.cfg.GetInstanceList():
7752
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7753
                                 instance_name, errors.ECODE_EXISTS)
7754

    
7755
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7756

    
7757
    if self.op.iallocator:
7758
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7759
    else:
7760
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7761
      nodelist = [self.op.pnode]
7762
      if self.op.snode is not None:
7763
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7764
        nodelist.append(self.op.snode)
7765
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7766

    
7767
    # in case of import lock the source node too
7768
    if self.op.mode == constants.INSTANCE_IMPORT:
7769
      src_node = self.op.src_node
7770
      src_path = self.op.src_path
7771

    
7772
      if src_path is None:
7773
        self.op.src_path = src_path = self.op.instance_name
7774

    
7775
      if src_node is None:
7776
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7777
        self.op.src_node = None
7778
        if os.path.isabs(src_path):
7779
          raise errors.OpPrereqError("Importing an instance from an absolute"
7780
                                     " path requires a source node option",
7781
                                     errors.ECODE_INVAL)
7782
      else:
7783
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7784
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7785
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7786
        if not os.path.isabs(src_path):
7787
          self.op.src_path = src_path = \
7788
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7789

    
7790
  def _RunAllocator(self):
7791
    """Run the allocator based on input opcode.
7792

7793
    """
7794
    nics = [n.ToDict() for n in self.nics]
7795
    ial = IAllocator(self.cfg, self.rpc,
7796
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7797
                     name=self.op.instance_name,
7798
                     disk_template=self.op.disk_template,
7799
                     tags=[],
7800
                     os=self.op.os_type,
7801
                     vcpus=self.be_full[constants.BE_VCPUS],
7802
                     mem_size=self.be_full[constants.BE_MEMORY],
7803
                     disks=self.disks,
7804
                     nics=nics,
7805
                     hypervisor=self.op.hypervisor,
7806
                     )
7807

    
7808
    ial.Run(self.op.iallocator)
7809

    
7810
    if not ial.success:
7811
      raise errors.OpPrereqError("Can't compute nodes using"
7812
                                 " iallocator '%s': %s" %
7813
                                 (self.op.iallocator, ial.info),
7814
                                 errors.ECODE_NORES)
7815
    if len(ial.result) != ial.required_nodes:
7816
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7817
                                 " of nodes (%s), required %s" %
7818
                                 (self.op.iallocator, len(ial.result),
7819
                                  ial.required_nodes), errors.ECODE_FAULT)
7820
    self.op.pnode = ial.result[0]
7821
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7822
                 self.op.instance_name, self.op.iallocator,
7823
                 utils.CommaJoin(ial.result))
7824
    if ial.required_nodes == 2:
7825
      self.op.snode = ial.result[1]
7826

    
7827
  def BuildHooksEnv(self):
7828
    """Build hooks env.
7829

7830
    This runs on master, primary and secondary nodes of the instance.
7831

7832
    """
7833
    env = {
7834
      "ADD_MODE": self.op.mode,
7835
      }
7836
    if self.op.mode == constants.INSTANCE_IMPORT:
7837
      env["SRC_NODE"] = self.op.src_node
7838
      env["SRC_PATH"] = self.op.src_path
7839
      env["SRC_IMAGES"] = self.src_images
7840

    
7841
    env.update(_BuildInstanceHookEnv(
7842
      name=self.op.instance_name,
7843
      primary_node=self.op.pnode,
7844
      secondary_nodes=self.secondaries,
7845
      status=self.op.start,
7846
      os_type=self.op.os_type,
7847
      memory=self.be_full[constants.BE_MEMORY],
7848
      vcpus=self.be_full[constants.BE_VCPUS],
7849
      nics=_NICListToTuple(self, self.nics),
7850
      disk_template=self.op.disk_template,
7851
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
7852
             for d in self.disks],
7853
      bep=self.be_full,
7854
      hvp=self.hv_full,
7855
      hypervisor_name=self.op.hypervisor,
7856
    ))
7857

    
7858
    return env
7859

    
7860
  def BuildHooksNodes(self):
7861
    """Build hooks nodes.
7862

7863
    """
7864
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
7865
    return nl, nl
7866

    
7867
  def _ReadExportInfo(self):
7868
    """Reads the export information from disk.
7869

7870
    It will override the opcode source node and path with the actual
7871
    information, if these two were not specified before.
7872

7873
    @return: the export information
7874

7875
    """
7876
    assert self.op.mode == constants.INSTANCE_IMPORT
7877

    
7878
    src_node = self.op.src_node
7879
    src_path = self.op.src_path
7880

    
7881
    if src_node is None:
7882
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
7883
      exp_list = self.rpc.call_export_list(locked_nodes)
7884
      found = False
7885
      for node in exp_list:
7886
        if exp_list[node].fail_msg:
7887
          continue
7888
        if src_path in exp_list[node].payload:
7889
          found = True
7890
          self.op.src_node = src_node = node
7891
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7892
                                                       src_path)
7893
          break
7894
      if not found:
7895
        raise errors.OpPrereqError("No export found for relative path %s" %
7896
                                    src_path, errors.ECODE_INVAL)
7897

    
7898
    _CheckNodeOnline(self, src_node)
7899
    result = self.rpc.call_export_info(src_node, src_path)
7900
    result.Raise("No export or invalid export found in dir %s" % src_path)
7901

    
7902
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7903
    if not export_info.has_section(constants.INISECT_EXP):
7904
      raise errors.ProgrammerError("Corrupted export config",
7905
                                   errors.ECODE_ENVIRON)
7906

    
7907
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7908
    if (int(ei_version) != constants.EXPORT_VERSION):
7909
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7910
                                 (ei_version, constants.EXPORT_VERSION),
7911
                                 errors.ECODE_ENVIRON)
7912
    return export_info
7913

    
7914
  def _ReadExportParams(self, einfo):
7915
    """Use export parameters as defaults.
7916

7917
    In case the opcode doesn't specify (as in override) some instance
7918
    parameters, then try to use them from the export information, if
7919
    that declares them.
7920

7921
    """
7922
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7923

    
7924
    if self.op.disk_template is None:
7925
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7926
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7927
                                          "disk_template")
7928
      else:
7929
        raise errors.OpPrereqError("No disk template specified and the export"
7930
                                   " is missing the disk_template information",
7931
                                   errors.ECODE_INVAL)
7932

    
7933
    if not self.op.disks:
7934
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7935
        disks = []
7936
        # TODO: import the disk iv_name too
7937
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7938
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7939
          disks.append({constants.IDISK_SIZE: disk_sz})
7940
        self.op.disks = disks
7941
      else:
7942
        raise errors.OpPrereqError("No disk info specified and the export"
7943
                                   " is missing the disk information",
7944
                                   errors.ECODE_INVAL)
7945

    
7946
    if (not self.op.nics and
7947
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7948
      nics = []
7949
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7950
        ndict = {}
7951
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7952
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7953
          ndict[name] = v
7954
        nics.append(ndict)
7955
      self.op.nics = nics
7956

    
7957
    if (self.op.hypervisor is None and
7958
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7959
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7960
    if einfo.has_section(constants.INISECT_HYP):
7961
      # use the export parameters but do not override the ones
7962
      # specified by the user
7963
      for name, value in einfo.items(constants.INISECT_HYP):
7964
        if name not in self.op.hvparams:
7965
          self.op.hvparams[name] = value
7966

    
7967
    if einfo.has_section(constants.INISECT_BEP):
7968
      # use the parameters, without overriding
7969
      for name, value in einfo.items(constants.INISECT_BEP):
7970
        if name not in self.op.beparams:
7971
          self.op.beparams[name] = value
7972
    else:
7973
      # try to read the parameters old style, from the main section
7974
      for name in constants.BES_PARAMETERS:
7975
        if (name not in self.op.beparams and
7976
            einfo.has_option(constants.INISECT_INS, name)):
7977
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7978

    
7979
    if einfo.has_section(constants.INISECT_OSP):
7980
      # use the parameters, without overriding
7981
      for name, value in einfo.items(constants.INISECT_OSP):
7982
        if name not in self.op.osparams:
7983
          self.op.osparams[name] = value
7984

    
7985
  def _RevertToDefaults(self, cluster):
7986
    """Revert the instance parameters to the default values.
7987

7988
    """
7989
    # hvparams
7990
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7991
    for name in self.op.hvparams.keys():
7992
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7993
        del self.op.hvparams[name]
7994
    # beparams
7995
    be_defs = cluster.SimpleFillBE({})
7996
    for name in self.op.beparams.keys():
7997
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7998
        del self.op.beparams[name]
7999
    # nic params
8000
    nic_defs = cluster.SimpleFillNIC({})
8001
    for nic in self.op.nics:
8002
      for name in constants.NICS_PARAMETERS:
8003
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8004
          del nic[name]
8005
    # osparams
8006
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8007
    for name in self.op.osparams.keys():
8008
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8009
        del self.op.osparams[name]
8010

    
8011
  def CheckPrereq(self):
8012
    """Check prerequisites.
8013

8014
    """
8015
    if self.op.mode == constants.INSTANCE_IMPORT:
8016
      export_info = self._ReadExportInfo()
8017
      self._ReadExportParams(export_info)
8018

    
8019
    if (not self.cfg.GetVGName() and
8020
        self.op.disk_template not in constants.DTS_NOT_LVM):
8021
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8022
                                 " instances", errors.ECODE_STATE)
8023

    
8024
    if self.op.hypervisor is None:
8025
      self.op.hypervisor = self.cfg.GetHypervisorType()
8026

    
8027
    cluster = self.cfg.GetClusterInfo()
8028
    enabled_hvs = cluster.enabled_hypervisors
8029
    if self.op.hypervisor not in enabled_hvs:
8030
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8031
                                 " cluster (%s)" % (self.op.hypervisor,
8032
                                  ",".join(enabled_hvs)),
8033
                                 errors.ECODE_STATE)
8034

    
8035
    # check hypervisor parameter syntax (locally)
8036
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8037
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8038
                                      self.op.hvparams)
8039
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8040
    hv_type.CheckParameterSyntax(filled_hvp)
8041
    self.hv_full = filled_hvp
8042
    # check that we don't specify global parameters on an instance
8043
    _CheckGlobalHvParams(self.op.hvparams)
8044

    
8045
    # fill and remember the beparams dict
8046
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8047
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8048

    
8049
    # build os parameters
8050
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8051

    
8052
    # now that hvp/bep are in final format, let's reset to defaults,
8053
    # if told to do so
8054
    if self.op.identify_defaults:
8055
      self._RevertToDefaults(cluster)
8056

    
8057
    # NIC buildup
8058
    self.nics = []
8059
    for idx, nic in enumerate(self.op.nics):
8060
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8061
      nic_mode = nic_mode_req
8062
      if nic_mode is None:
8063
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8064

    
8065
      # in routed mode, for the first nic, the default ip is 'auto'
8066
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8067
        default_ip_mode = constants.VALUE_AUTO
8068
      else:
8069
        default_ip_mode = constants.VALUE_NONE
8070

    
8071
      # ip validity checks
8072
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8073
      if ip is None or ip.lower() == constants.VALUE_NONE:
8074
        nic_ip = None
8075
      elif ip.lower() == constants.VALUE_AUTO:
8076
        if not self.op.name_check:
8077
          raise errors.OpPrereqError("IP address set to auto but name checks"
8078
                                     " have been skipped",
8079
                                     errors.ECODE_INVAL)
8080
        nic_ip = self.hostname1.ip
8081
      else:
8082
        if not netutils.IPAddress.IsValid(ip):
8083
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8084
                                     errors.ECODE_INVAL)
8085
        nic_ip = ip
8086

    
8087
      # TODO: check the ip address for uniqueness
8088
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8089
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8090
                                   errors.ECODE_INVAL)
8091

    
8092
      # MAC address verification
8093
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8094
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8095
        mac = utils.NormalizeAndValidateMac(mac)
8096

    
8097
        try:
8098
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8099
        except errors.ReservationError:
8100
          raise errors.OpPrereqError("MAC address %s already in use"
8101
                                     " in cluster" % mac,
8102
                                     errors.ECODE_NOTUNIQUE)
8103

    
8104
      #  Build nic parameters
8105
      link = nic.get(constants.INIC_LINK, None)
8106
      nicparams = {}
8107
      if nic_mode_req:
8108
        nicparams[constants.NIC_MODE] = nic_mode_req
8109
      if link:
8110
        nicparams[constants.NIC_LINK] = link
8111

    
8112
      check_params = cluster.SimpleFillNIC(nicparams)
8113
      objects.NIC.CheckParameterSyntax(check_params)
8114
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8115

    
8116
    # disk checks/pre-build
8117
    default_vg = self.cfg.GetVGName()
8118
    self.disks = []
8119
    for disk in self.op.disks:
8120
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8121
      if mode not in constants.DISK_ACCESS_SET:
8122
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8123
                                   mode, errors.ECODE_INVAL)
8124
      size = disk.get(constants.IDISK_SIZE, None)
8125
      if size is None:
8126
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8127
      try:
8128
        size = int(size)
8129
      except (TypeError, ValueError):
8130
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8131
                                   errors.ECODE_INVAL)
8132

    
8133
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8134
      new_disk = {
8135
        constants.IDISK_SIZE: size,
8136
        constants.IDISK_MODE: mode,
8137
        constants.IDISK_VG: data_vg,
8138
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8139
        }
8140
      if constants.IDISK_ADOPT in disk:
8141
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8142
      self.disks.append(new_disk)
8143

    
8144
    if self.op.mode == constants.INSTANCE_IMPORT:
8145

    
8146
      # Check that the new instance doesn't have less disks than the export
8147
      instance_disks = len(self.disks)
8148
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8149
      if instance_disks < export_disks:
8150
        raise errors.OpPrereqError("Not enough disks to import."
8151
                                   " (instance: %d, export: %d)" %
8152
                                   (instance_disks, export_disks),
8153
                                   errors.ECODE_INVAL)
8154

    
8155
      disk_images = []
8156
      for idx in range(export_disks):
8157
        option = 'disk%d_dump' % idx
8158
        if export_info.has_option(constants.INISECT_INS, option):
8159
          # FIXME: are the old os-es, disk sizes, etc. useful?
8160
          export_name = export_info.get(constants.INISECT_INS, option)
8161
          image = utils.PathJoin(self.op.src_path, export_name)
8162
          disk_images.append(image)
8163
        else:
8164
          disk_images.append(False)
8165

    
8166
      self.src_images = disk_images
8167

    
8168
      old_name = export_info.get(constants.INISECT_INS, 'name')
8169
      try:
8170
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8171
      except (TypeError, ValueError), err:
8172
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8173
                                   " an integer: %s" % str(err),
8174
                                   errors.ECODE_STATE)
8175
      if self.op.instance_name == old_name:
8176
        for idx, nic in enumerate(self.nics):
8177
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8178
            nic_mac_ini = 'nic%d_mac' % idx
8179
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8180

    
8181
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8182

    
8183
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8184
    if self.op.ip_check:
8185
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8186
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8187
                                   (self.check_ip, self.op.instance_name),
8188
                                   errors.ECODE_NOTUNIQUE)
8189

    
8190
    #### mac address generation
8191
    # By generating here the mac address both the allocator and the hooks get
8192
    # the real final mac address rather than the 'auto' or 'generate' value.
8193
    # There is a race condition between the generation and the instance object
8194
    # creation, which means that we know the mac is valid now, but we're not
8195
    # sure it will be when we actually add the instance. If things go bad
8196
    # adding the instance will abort because of a duplicate mac, and the
8197
    # creation job will fail.
8198
    for nic in self.nics:
8199
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8200
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8201

    
8202
    #### allocator run
8203

    
8204
    if self.op.iallocator is not None:
8205
      self._RunAllocator()
8206

    
8207
    #### node related checks
8208

    
8209
    # check primary node
8210
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8211
    assert self.pnode is not None, \
8212
      "Cannot retrieve locked node %s" % self.op.pnode
8213
    if pnode.offline:
8214
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8215
                                 pnode.name, errors.ECODE_STATE)
8216
    if pnode.drained:
8217
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8218
                                 pnode.name, errors.ECODE_STATE)
8219
    if not pnode.vm_capable:
8220
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8221
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8222

    
8223
    self.secondaries = []
8224

    
8225
    # mirror node verification
8226
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8227
      if self.op.snode == pnode.name:
8228
        raise errors.OpPrereqError("The secondary node cannot be the"
8229
                                   " primary node", errors.ECODE_INVAL)
8230
      _CheckNodeOnline(self, self.op.snode)
8231
      _CheckNodeNotDrained(self, self.op.snode)
8232
      _CheckNodeVmCapable(self, self.op.snode)
8233
      self.secondaries.append(self.op.snode)
8234

    
8235
    nodenames = [pnode.name] + self.secondaries
8236

    
8237
    if not self.adopt_disks:
8238
      # Check lv size requirements, if not adopting
8239
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8240
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8241

    
8242
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8243
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8244
                                disk[constants.IDISK_ADOPT])
8245
                     for disk in self.disks])
8246
      if len(all_lvs) != len(self.disks):
8247
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8248
                                   errors.ECODE_INVAL)
8249
      for lv_name in all_lvs:
8250
        try:
8251
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8252
          # to ReserveLV uses the same syntax
8253
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8254
        except errors.ReservationError:
8255
          raise errors.OpPrereqError("LV named %s used by another instance" %
8256
                                     lv_name, errors.ECODE_NOTUNIQUE)
8257

    
8258
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8259
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8260

    
8261
      node_lvs = self.rpc.call_lv_list([pnode.name],
8262
                                       vg_names.payload.keys())[pnode.name]
8263
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8264
      node_lvs = node_lvs.payload
8265

    
8266
      delta = all_lvs.difference(node_lvs.keys())
8267
      if delta:
8268
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8269
                                   utils.CommaJoin(delta),
8270
                                   errors.ECODE_INVAL)
8271
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8272
      if online_lvs:
8273
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8274
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8275
                                   errors.ECODE_STATE)
8276
      # update the size of disk based on what is found
8277
      for dsk in self.disks:
8278
        dsk[constants.IDISK_SIZE] = \
8279
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8280
                                        dsk[constants.IDISK_ADOPT])][0]))
8281

    
8282
    elif self.op.disk_template == constants.DT_BLOCK:
8283
      # Normalize and de-duplicate device paths
8284
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8285
                       for disk in self.disks])
8286
      if len(all_disks) != len(self.disks):
8287
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8288
                                   errors.ECODE_INVAL)
8289
      baddisks = [d for d in all_disks
8290
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8291
      if baddisks:
8292
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8293
                                   " cannot be adopted" %
8294
                                   (", ".join(baddisks),
8295
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8296
                                   errors.ECODE_INVAL)
8297

    
8298
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8299
                                            list(all_disks))[pnode.name]
8300
      node_disks.Raise("Cannot get block device information from node %s" %
8301
                       pnode.name)
8302
      node_disks = node_disks.payload
8303
      delta = all_disks.difference(node_disks.keys())
8304
      if delta:
8305
        raise errors.OpPrereqError("Missing block device(s): %s" %
8306
                                   utils.CommaJoin(delta),
8307
                                   errors.ECODE_INVAL)
8308
      for dsk in self.disks:
8309
        dsk[constants.IDISK_SIZE] = \
8310
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8311

    
8312
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8313

    
8314
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8315
    # check OS parameters (remotely)
8316
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8317

    
8318
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8319

    
8320
    # memory check on primary node
8321
    if self.op.start:
8322
      _CheckNodeFreeMemory(self, self.pnode.name,
8323
                           "creating instance %s" % self.op.instance_name,
8324
                           self.be_full[constants.BE_MEMORY],
8325
                           self.op.hypervisor)
8326

    
8327
    self.dry_run_result = list(nodenames)
8328

    
8329
  def Exec(self, feedback_fn):
8330
    """Create and add the instance to the cluster.
8331

8332
    """
8333
    instance = self.op.instance_name
8334
    pnode_name = self.pnode.name
8335

    
8336
    ht_kind = self.op.hypervisor
8337
    if ht_kind in constants.HTS_REQ_PORT:
8338
      network_port = self.cfg.AllocatePort()
8339
    else:
8340
      network_port = None
8341

    
8342
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
8343
      # this is needed because os.path.join does not accept None arguments
8344
      if self.op.file_storage_dir is None:
8345
        string_file_storage_dir = ""
8346
      else:
8347
        string_file_storage_dir = self.op.file_storage_dir
8348

    
8349
      # build the full file storage dir path
8350
      if self.op.disk_template == constants.DT_SHARED_FILE:
8351
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8352
      else:
8353
        get_fsd_fn = self.cfg.GetFileStorageDir
8354

    
8355
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
8356
                                        string_file_storage_dir, instance)
8357
    else:
8358
      file_storage_dir = ""
8359

    
8360
    disks = _GenerateDiskTemplate(self,
8361
                                  self.op.disk_template,
8362
                                  instance, pnode_name,
8363
                                  self.secondaries,
8364
                                  self.disks,
8365
                                  file_storage_dir,
8366
                                  self.op.file_driver,
8367
                                  0,
8368
                                  feedback_fn)
8369

    
8370
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8371
                            primary_node=pnode_name,
8372
                            nics=self.nics, disks=disks,
8373
                            disk_template=self.op.disk_template,
8374
                            admin_up=False,
8375
                            network_port=network_port,
8376
                            beparams=self.op.beparams,
8377
                            hvparams=self.op.hvparams,
8378
                            hypervisor=self.op.hypervisor,
8379
                            osparams=self.op.osparams,
8380
                            )
8381

    
8382
    if self.adopt_disks:
8383
      if self.op.disk_template == constants.DT_PLAIN:
8384
        # rename LVs to the newly-generated names; we need to construct
8385
        # 'fake' LV disks with the old data, plus the new unique_id
8386
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8387
        rename_to = []
8388
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8389
          rename_to.append(t_dsk.logical_id)
8390
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8391
          self.cfg.SetDiskID(t_dsk, pnode_name)
8392
        result = self.rpc.call_blockdev_rename(pnode_name,
8393
                                               zip(tmp_disks, rename_to))
8394
        result.Raise("Failed to rename adoped LVs")
8395
    else:
8396
      feedback_fn("* creating instance disks...")
8397
      try:
8398
        _CreateDisks(self, iobj)
8399
      except errors.OpExecError:
8400
        self.LogWarning("Device creation failed, reverting...")
8401
        try:
8402
          _RemoveDisks(self, iobj)
8403
        finally:
8404
          self.cfg.ReleaseDRBDMinors(instance)
8405
          raise
8406

    
8407
    feedback_fn("adding instance %s to cluster config" % instance)
8408

    
8409
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8410

    
8411
    # Declare that we don't want to remove the instance lock anymore, as we've
8412
    # added the instance to the config
8413
    del self.remove_locks[locking.LEVEL_INSTANCE]
8414

    
8415
    if self.op.mode == constants.INSTANCE_IMPORT:
8416
      # Release unused nodes
8417
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8418
    else:
8419
      # Release all nodes
8420
      _ReleaseLocks(self, locking.LEVEL_NODE)
8421

    
8422
    disk_abort = False
8423
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8424
      feedback_fn("* wiping instance disks...")
8425
      try:
8426
        _WipeDisks(self, iobj)
8427
      except errors.OpExecError, err:
8428
        logging.exception("Wiping disks failed")
8429
        self.LogWarning("Wiping instance disks failed (%s)", err)
8430
        disk_abort = True
8431

    
8432
    if disk_abort:
8433
      # Something is already wrong with the disks, don't do anything else
8434
      pass
8435
    elif self.op.wait_for_sync:
8436
      disk_abort = not _WaitForSync(self, iobj)
8437
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8438
      # make sure the disks are not degraded (still sync-ing is ok)
8439
      time.sleep(15)
8440
      feedback_fn("* checking mirrors status")
8441
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8442
    else:
8443
      disk_abort = False
8444

    
8445
    if disk_abort:
8446
      _RemoveDisks(self, iobj)
8447
      self.cfg.RemoveInstance(iobj.name)
8448
      # Make sure the instance lock gets removed
8449
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8450
      raise errors.OpExecError("There are some degraded disks for"
8451
                               " this instance")
8452

    
8453
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8454
      if self.op.mode == constants.INSTANCE_CREATE:
8455
        if not self.op.no_install:
8456
          feedback_fn("* running the instance OS create scripts...")
8457
          # FIXME: pass debug option from opcode to backend
8458
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8459
                                                 self.op.debug_level)
8460
          result.Raise("Could not add os for instance %s"
8461
                       " on node %s" % (instance, pnode_name))
8462

    
8463
      elif self.op.mode == constants.INSTANCE_IMPORT:
8464
        feedback_fn("* running the instance OS import scripts...")
8465

    
8466
        transfers = []
8467

    
8468
        for idx, image in enumerate(self.src_images):
8469
          if not image:
8470
            continue
8471

    
8472
          # FIXME: pass debug option from opcode to backend
8473
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8474
                                             constants.IEIO_FILE, (image, ),
8475
                                             constants.IEIO_SCRIPT,
8476
                                             (iobj.disks[idx], idx),
8477
                                             None)
8478
          transfers.append(dt)
8479

    
8480
        import_result = \
8481
          masterd.instance.TransferInstanceData(self, feedback_fn,
8482
                                                self.op.src_node, pnode_name,
8483
                                                self.pnode.secondary_ip,
8484
                                                iobj, transfers)
8485
        if not compat.all(import_result):
8486
          self.LogWarning("Some disks for instance %s on node %s were not"
8487
                          " imported successfully" % (instance, pnode_name))
8488

    
8489
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8490
        feedback_fn("* preparing remote import...")
8491
        # The source cluster will stop the instance before attempting to make a
8492
        # connection. In some cases stopping an instance can take a long time,
8493
        # hence the shutdown timeout is added to the connection timeout.
8494
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8495
                           self.op.source_shutdown_timeout)
8496
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8497

    
8498
        assert iobj.primary_node == self.pnode.name
8499
        disk_results = \
8500
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8501
                                        self.source_x509_ca,
8502
                                        self._cds, timeouts)
8503
        if not compat.all(disk_results):
8504
          # TODO: Should the instance still be started, even if some disks
8505
          # failed to import (valid for local imports, too)?
8506
          self.LogWarning("Some disks for instance %s on node %s were not"
8507
                          " imported successfully" % (instance, pnode_name))
8508

    
8509
        # Run rename script on newly imported instance
8510
        assert iobj.name == instance
8511
        feedback_fn("Running rename script for %s" % instance)
8512
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8513
                                                   self.source_instance_name,
8514
                                                   self.op.debug_level)
8515
        if result.fail_msg:
8516
          self.LogWarning("Failed to run rename script for %s on node"
8517
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8518

    
8519
      else:
8520
        # also checked in the prereq part
8521
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8522
                                     % self.op.mode)
8523

    
8524
    if self.op.start:
8525
      iobj.admin_up = True
8526
      self.cfg.Update(iobj, feedback_fn)
8527
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8528
      feedback_fn("* starting instance...")
8529
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8530
      result.Raise("Could not start instance")
8531

    
8532
    return list(iobj.all_nodes)
8533

    
8534

    
8535
class LUInstanceConsole(NoHooksLU):
8536
  """Connect to an instance's console.
8537

8538
  This is somewhat special in that it returns the command line that
8539
  you need to run on the master node in order to connect to the
8540
  console.
8541

8542
  """
8543
  REQ_BGL = False
8544

    
8545
  def ExpandNames(self):
8546
    self._ExpandAndLockInstance()
8547

    
8548
  def CheckPrereq(self):
8549
    """Check prerequisites.
8550

8551
    This checks that the instance is in the cluster.
8552

8553
    """
8554
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8555
    assert self.instance is not None, \
8556
      "Cannot retrieve locked instance %s" % self.op.instance_name
8557
    _CheckNodeOnline(self, self.instance.primary_node)
8558

    
8559
  def Exec(self, feedback_fn):
8560
    """Connect to the console of an instance
8561

8562
    """
8563
    instance = self.instance
8564
    node = instance.primary_node
8565

    
8566
    node_insts = self.rpc.call_instance_list([node],
8567
                                             [instance.hypervisor])[node]
8568
    node_insts.Raise("Can't get node information from %s" % node)
8569

    
8570
    if instance.name not in node_insts.payload:
8571
      if instance.admin_up:
8572
        state = constants.INSTST_ERRORDOWN
8573
      else:
8574
        state = constants.INSTST_ADMINDOWN
8575
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8576
                               (instance.name, state))
8577

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

    
8580
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8581

    
8582

    
8583
def _GetInstanceConsole(cluster, instance):
8584
  """Returns console information for an instance.
8585

8586
  @type cluster: L{objects.Cluster}
8587
  @type instance: L{objects.Instance}
8588
  @rtype: dict
8589

8590
  """
8591
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8592
  # beparams and hvparams are passed separately, to avoid editing the
8593
  # instance and then saving the defaults in the instance itself.
8594
  hvparams = cluster.FillHV(instance)
8595
  beparams = cluster.FillBE(instance)
8596
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8597

    
8598
  assert console.instance == instance.name
8599
  assert console.Validate()
8600

    
8601
  return console.ToDict()
8602

    
8603

    
8604
class LUInstanceReplaceDisks(LogicalUnit):
8605
  """Replace the disks of an instance.
8606

8607
  """
8608
  HPATH = "mirrors-replace"
8609
  HTYPE = constants.HTYPE_INSTANCE
8610
  REQ_BGL = False
8611

    
8612
  def CheckArguments(self):
8613
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8614
                                  self.op.iallocator)
8615

    
8616
  def ExpandNames(self):
8617
    self._ExpandAndLockInstance()
8618

    
8619
    assert locking.LEVEL_NODE not in self.needed_locks
8620
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8621

    
8622
    assert self.op.iallocator is None or self.op.remote_node is None, \
8623
      "Conflicting options"
8624

    
8625
    if self.op.remote_node is not None:
8626
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8627

    
8628
      # Warning: do not remove the locking of the new secondary here
8629
      # unless DRBD8.AddChildren is changed to work in parallel;
8630
      # currently it doesn't since parallel invocations of
8631
      # FindUnusedMinor will conflict
8632
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8633
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8634
    else:
8635
      self.needed_locks[locking.LEVEL_NODE] = []
8636
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8637

    
8638
      if self.op.iallocator is not None:
8639
        # iallocator will select a new node in the same group
8640
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8641

    
8642
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8643
                                   self.op.iallocator, self.op.remote_node,
8644
                                   self.op.disks, False, self.op.early_release)
8645

    
8646
    self.tasklets = [self.replacer]
8647

    
8648
  def DeclareLocks(self, level):
8649
    if level == locking.LEVEL_NODEGROUP:
8650
      assert self.op.remote_node is None
8651
      assert self.op.iallocator is not None
8652
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8653

    
8654
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8655
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8656
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8657

    
8658
    elif level == locking.LEVEL_NODE:
8659
      if self.op.iallocator is not None:
8660
        assert self.op.remote_node is None
8661
        assert not self.needed_locks[locking.LEVEL_NODE]
8662

    
8663
        # Lock member nodes of all locked groups
8664
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8665
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8666
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8667
      else:
8668
        self._LockInstancesNodes()
8669

    
8670
  def BuildHooksEnv(self):
8671
    """Build hooks env.
8672

8673
    This runs on the master, the primary and all the secondaries.
8674

8675
    """
8676
    instance = self.replacer.instance
8677
    env = {
8678
      "MODE": self.op.mode,
8679
      "NEW_SECONDARY": self.op.remote_node,
8680
      "OLD_SECONDARY": instance.secondary_nodes[0],
8681
      }
8682
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8683
    return env
8684

    
8685
  def BuildHooksNodes(self):
8686
    """Build hooks nodes.
8687

8688
    """
8689
    instance = self.replacer.instance
8690
    nl = [
8691
      self.cfg.GetMasterNode(),
8692
      instance.primary_node,
8693
      ]
8694
    if self.op.remote_node is not None:
8695
      nl.append(self.op.remote_node)
8696
    return nl, nl
8697

    
8698
  def CheckPrereq(self):
8699
    """Check prerequisites.
8700

8701
    """
8702
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8703
            self.op.iallocator is None)
8704

    
8705
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8706
    if owned_groups:
8707
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8708
      if owned_groups != groups:
8709
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8710
                                 " since lock was acquired, current list is %r,"
8711
                                 " used to be '%s'" %
8712
                                 (self.op.instance_name,
8713
                                  utils.CommaJoin(groups),
8714
                                  utils.CommaJoin(owned_groups)))
8715

    
8716
    return LogicalUnit.CheckPrereq(self)
8717

    
8718

    
8719
class TLReplaceDisks(Tasklet):
8720
  """Replaces disks for an instance.
8721

8722
  Note: Locking is not within the scope of this class.
8723

8724
  """
8725
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8726
               disks, delay_iallocator, early_release):
8727
    """Initializes this class.
8728

8729
    """
8730
    Tasklet.__init__(self, lu)
8731

    
8732
    # Parameters
8733
    self.instance_name = instance_name
8734
    self.mode = mode
8735
    self.iallocator_name = iallocator_name
8736
    self.remote_node = remote_node
8737
    self.disks = disks
8738
    self.delay_iallocator = delay_iallocator
8739
    self.early_release = early_release
8740

    
8741
    # Runtime data
8742
    self.instance = None
8743
    self.new_node = None
8744
    self.target_node = None
8745
    self.other_node = None
8746
    self.remote_node_info = None
8747
    self.node_secondary_ip = None
8748

    
8749
  @staticmethod
8750
  def CheckArguments(mode, remote_node, iallocator):
8751
    """Helper function for users of this class.
8752

8753
    """
8754
    # check for valid parameter combination
8755
    if mode == constants.REPLACE_DISK_CHG:
8756
      if remote_node is None and iallocator is None:
8757
        raise errors.OpPrereqError("When changing the secondary either an"
8758
                                   " iallocator script must be used or the"
8759
                                   " new node given", errors.ECODE_INVAL)
8760

    
8761
      if remote_node is not None and iallocator is not None:
8762
        raise errors.OpPrereqError("Give either the iallocator or the new"
8763
                                   " secondary, not both", errors.ECODE_INVAL)
8764

    
8765
    elif remote_node is not None or iallocator is not None:
8766
      # Not replacing the secondary
8767
      raise errors.OpPrereqError("The iallocator and new node options can"
8768
                                 " only be used when changing the"
8769
                                 " secondary node", errors.ECODE_INVAL)
8770

    
8771
  @staticmethod
8772
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8773
    """Compute a new secondary node using an IAllocator.
8774

8775
    """
8776
    ial = IAllocator(lu.cfg, lu.rpc,
8777
                     mode=constants.IALLOCATOR_MODE_RELOC,
8778
                     name=instance_name,
8779
                     relocate_from=relocate_from)
8780

    
8781
    ial.Run(iallocator_name)
8782

    
8783
    if not ial.success:
8784
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8785
                                 " %s" % (iallocator_name, ial.info),
8786
                                 errors.ECODE_NORES)
8787

    
8788
    if len(ial.result) != ial.required_nodes:
8789
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8790
                                 " of nodes (%s), required %s" %
8791
                                 (iallocator_name,
8792
                                  len(ial.result), ial.required_nodes),
8793
                                 errors.ECODE_FAULT)
8794

    
8795
    remote_node_name = ial.result[0]
8796

    
8797
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8798
               instance_name, remote_node_name)
8799

    
8800
    return remote_node_name
8801

    
8802
  def _FindFaultyDisks(self, node_name):
8803
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8804
                                    node_name, True)
8805

    
8806
  def _CheckDisksActivated(self, instance):
8807
    """Checks if the instance disks are activated.
8808

8809
    @param instance: The instance to check disks
8810
    @return: True if they are activated, False otherwise
8811

8812
    """
8813
    nodes = instance.all_nodes
8814

    
8815
    for idx, dev in enumerate(instance.disks):
8816
      for node in nodes:
8817
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
8818
        self.cfg.SetDiskID(dev, node)
8819

    
8820
        result = self.rpc.call_blockdev_find(node, dev)
8821

    
8822
        if result.offline:
8823
          continue
8824
        elif result.fail_msg or not result.payload:
8825
          return False
8826

    
8827
    return True
8828

    
8829
  def CheckPrereq(self):
8830
    """Check prerequisites.
8831

8832
    This checks that the instance is in the cluster.
8833

8834
    """
8835
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8836
    assert instance is not None, \
8837
      "Cannot retrieve locked instance %s" % self.instance_name
8838

    
8839
    if instance.disk_template != constants.DT_DRBD8:
8840
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8841
                                 " instances", errors.ECODE_INVAL)
8842

    
8843
    if len(instance.secondary_nodes) != 1:
8844
      raise errors.OpPrereqError("The instance has a strange layout,"
8845
                                 " expected one secondary but found %d" %
8846
                                 len(instance.secondary_nodes),
8847
                                 errors.ECODE_FAULT)
8848

    
8849
    if not self.delay_iallocator:
8850
      self._CheckPrereq2()
8851

    
8852
  def _CheckPrereq2(self):
8853
    """Check prerequisites, second part.
8854

8855
    This function should always be part of CheckPrereq. It was separated and is
8856
    now called from Exec because during node evacuation iallocator was only
8857
    called with an unmodified cluster model, not taking planned changes into
8858
    account.
8859

8860
    """
8861
    instance = self.instance
8862
    secondary_node = instance.secondary_nodes[0]
8863

    
8864
    if self.iallocator_name is None:
8865
      remote_node = self.remote_node
8866
    else:
8867
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8868
                                       instance.name, instance.secondary_nodes)
8869

    
8870
    if remote_node is None:
8871
      self.remote_node_info = None
8872
    else:
8873
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
8874
             "Remote node '%s' is not locked" % remote_node
8875

    
8876
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8877
      assert self.remote_node_info is not None, \
8878
        "Cannot retrieve locked node %s" % remote_node
8879

    
8880
    if remote_node == self.instance.primary_node:
8881
      raise errors.OpPrereqError("The specified node is the primary node of"
8882
                                 " the instance", errors.ECODE_INVAL)
8883

    
8884
    if remote_node == secondary_node:
8885
      raise errors.OpPrereqError("The specified node is already the"
8886
                                 " secondary node of the instance",
8887
                                 errors.ECODE_INVAL)
8888

    
8889
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8890
                                    constants.REPLACE_DISK_CHG):
8891
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8892
                                 errors.ECODE_INVAL)
8893

    
8894
    if self.mode == constants.REPLACE_DISK_AUTO:
8895
      if not self._CheckDisksActivated(instance):
8896
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
8897
                                   " first" % self.instance_name,
8898
                                   errors.ECODE_STATE)
8899
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8900
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8901

    
8902
      if faulty_primary and faulty_secondary:
8903
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8904
                                   " one node and can not be repaired"
8905
                                   " automatically" % self.instance_name,
8906
                                   errors.ECODE_STATE)
8907

    
8908
      if faulty_primary:
8909
        self.disks = faulty_primary
8910
        self.target_node = instance.primary_node
8911
        self.other_node = secondary_node
8912
        check_nodes = [self.target_node, self.other_node]
8913
      elif faulty_secondary:
8914
        self.disks = faulty_secondary
8915
        self.target_node = secondary_node
8916
        self.other_node = instance.primary_node
8917
        check_nodes = [self.target_node, self.other_node]
8918
      else:
8919
        self.disks = []
8920
        check_nodes = []
8921

    
8922
    else:
8923
      # Non-automatic modes
8924
      if self.mode == constants.REPLACE_DISK_PRI:
8925
        self.target_node = instance.primary_node
8926
        self.other_node = secondary_node
8927
        check_nodes = [self.target_node, self.other_node]
8928

    
8929
      elif self.mode == constants.REPLACE_DISK_SEC:
8930
        self.target_node = secondary_node
8931
        self.other_node = instance.primary_node
8932
        check_nodes = [self.target_node, self.other_node]
8933

    
8934
      elif self.mode == constants.REPLACE_DISK_CHG:
8935
        self.new_node = remote_node
8936
        self.other_node = instance.primary_node
8937
        self.target_node = secondary_node
8938
        check_nodes = [self.new_node, self.other_node]
8939

    
8940
        _CheckNodeNotDrained(self.lu, remote_node)
8941
        _CheckNodeVmCapable(self.lu, remote_node)
8942

    
8943
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8944
        assert old_node_info is not None
8945
        if old_node_info.offline and not self.early_release:
8946
          # doesn't make sense to delay the release
8947
          self.early_release = True
8948
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8949
                          " early-release mode", secondary_node)
8950

    
8951
      else:
8952
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8953
                                     self.mode)
8954

    
8955
      # If not specified all disks should be replaced
8956
      if not self.disks:
8957
        self.disks = range(len(self.instance.disks))
8958

    
8959
    for node in check_nodes:
8960
      _CheckNodeOnline(self.lu, node)
8961

    
8962
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
8963
                                                          self.other_node,
8964
                                                          self.target_node]
8965
                              if node_name is not None)
8966

    
8967
    # Release unneeded node locks
8968
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
8969

    
8970
    # Release any owned node group
8971
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
8972
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
8973

    
8974
    # Check whether disks are valid
8975
    for disk_idx in self.disks:
8976
      instance.FindDisk(disk_idx)
8977

    
8978
    # Get secondary node IP addresses
8979
    self.node_secondary_ip = \
8980
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
8981
           for node_name in touched_nodes)
8982

    
8983
  def Exec(self, feedback_fn):
8984
    """Execute disk replacement.
8985

8986
    This dispatches the disk replacement to the appropriate handler.
8987

8988
    """
8989
    if self.delay_iallocator:
8990
      self._CheckPrereq2()
8991

    
8992
    if __debug__:
8993
      # Verify owned locks before starting operation
8994
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
8995
      assert set(owned_locks) == set(self.node_secondary_ip), \
8996
          ("Incorrect node locks, owning %s, expected %s" %
8997
           (owned_locks, self.node_secondary_ip.keys()))
8998

    
8999
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9000
      assert list(owned_locks) == [self.instance_name], \
9001
          "Instance '%s' not locked" % self.instance_name
9002

    
9003
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9004
          "Should not own any node group lock at this point"
9005

    
9006
    if not self.disks:
9007
      feedback_fn("No disks need replacement")
9008
      return
9009

    
9010
    feedback_fn("Replacing disk(s) %s for %s" %
9011
                (utils.CommaJoin(self.disks), self.instance.name))
9012

    
9013
    activate_disks = (not self.instance.admin_up)
9014

    
9015
    # Activate the instance disks if we're replacing them on a down instance
9016
    if activate_disks:
9017
      _StartInstanceDisks(self.lu, self.instance, True)
9018

    
9019
    try:
9020
      # Should we replace the secondary node?
9021
      if self.new_node is not None:
9022
        fn = self._ExecDrbd8Secondary
9023
      else:
9024
        fn = self._ExecDrbd8DiskOnly
9025

    
9026
      result = fn(feedback_fn)
9027
    finally:
9028
      # Deactivate the instance disks if we're replacing them on a
9029
      # down instance
9030
      if activate_disks:
9031
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9032

    
9033
    if __debug__:
9034
      # Verify owned locks
9035
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9036
      nodes = frozenset(self.node_secondary_ip)
9037
      assert ((self.early_release and not owned_locks) or
9038
              (not self.early_release and not (set(owned_locks) - nodes))), \
9039
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9040
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9041

    
9042
    return result
9043

    
9044
  def _CheckVolumeGroup(self, nodes):
9045
    self.lu.LogInfo("Checking volume groups")
9046

    
9047
    vgname = self.cfg.GetVGName()
9048

    
9049
    # Make sure volume group exists on all involved nodes
9050
    results = self.rpc.call_vg_list(nodes)
9051
    if not results:
9052
      raise errors.OpExecError("Can't list volume groups on the nodes")
9053

    
9054
    for node in nodes:
9055
      res = results[node]
9056
      res.Raise("Error checking node %s" % node)
9057
      if vgname not in res.payload:
9058
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9059
                                 (vgname, node))
9060

    
9061
  def _CheckDisksExistence(self, nodes):
9062
    # Check disk existence
9063
    for idx, dev in enumerate(self.instance.disks):
9064
      if idx not in self.disks:
9065
        continue
9066

    
9067
      for node in nodes:
9068
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9069
        self.cfg.SetDiskID(dev, node)
9070

    
9071
        result = self.rpc.call_blockdev_find(node, dev)
9072

    
9073
        msg = result.fail_msg
9074
        if msg or not result.payload:
9075
          if not msg:
9076
            msg = "disk not found"
9077
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9078
                                   (idx, node, msg))
9079

    
9080
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9081
    for idx, dev in enumerate(self.instance.disks):
9082
      if idx not in self.disks:
9083
        continue
9084

    
9085
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9086
                      (idx, node_name))
9087

    
9088
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9089
                                   ldisk=ldisk):
9090
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9091
                                 " replace disks for instance %s" %
9092
                                 (node_name, self.instance.name))
9093

    
9094
  def _CreateNewStorage(self, node_name):
9095
    iv_names = {}
9096

    
9097
    for idx, dev in enumerate(self.instance.disks):
9098
      if idx not in self.disks:
9099
        continue
9100

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

    
9103
      self.cfg.SetDiskID(dev, node_name)
9104

    
9105
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9106
      names = _GenerateUniqueNames(self.lu, lv_names)
9107

    
9108
      vg_data = dev.children[0].logical_id[0]
9109
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9110
                             logical_id=(vg_data, names[0]))
9111
      vg_meta = dev.children[1].logical_id[0]
9112
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9113
                             logical_id=(vg_meta, names[1]))
9114

    
9115
      new_lvs = [lv_data, lv_meta]
9116
      old_lvs = dev.children
9117
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9118

    
9119
      # we pass force_create=True to force the LVM creation
9120
      for new_lv in new_lvs:
9121
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9122
                        _GetInstanceInfoText(self.instance), False)
9123

    
9124
    return iv_names
9125

    
9126
  def _CheckDevices(self, node_name, iv_names):
9127
    for name, (dev, _, _) in iv_names.iteritems():
9128
      self.cfg.SetDiskID(dev, node_name)
9129

    
9130
      result = self.rpc.call_blockdev_find(node_name, dev)
9131

    
9132
      msg = result.fail_msg
9133
      if msg or not result.payload:
9134
        if not msg:
9135
          msg = "disk not found"
9136
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9137
                                 (name, msg))
9138

    
9139
      if result.payload.is_degraded:
9140
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9141

    
9142
  def _RemoveOldStorage(self, node_name, iv_names):
9143
    for name, (_, old_lvs, _) in iv_names.iteritems():
9144
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9145

    
9146
      for lv in old_lvs:
9147
        self.cfg.SetDiskID(lv, node_name)
9148

    
9149
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9150
        if msg:
9151
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9152
                             hint="remove unused LVs manually")
9153

    
9154
  def _ExecDrbd8DiskOnly(self, feedback_fn):
9155
    """Replace a disk on the primary or secondary for DRBD 8.
9156

9157
    The algorithm for replace is quite complicated:
9158

9159
      1. for each disk to be replaced:
9160

9161
        1. create new LVs on the target node with unique names
9162
        1. detach old LVs from the drbd device
9163
        1. rename old LVs to name_replaced.<time_t>
9164
        1. rename new LVs to old LVs
9165
        1. attach the new LVs (with the old names now) to the drbd device
9166

9167
      1. wait for sync across all devices
9168

9169
      1. for each modified disk:
9170

9171
        1. remove old LVs (which have the name name_replaces.<time_t>)
9172

9173
    Failures are not very well handled.
9174

9175
    """
9176
    steps_total = 6
9177

    
9178
    # Step: check device activation
9179
    self.lu.LogStep(1, steps_total, "Check device existence")
9180
    self._CheckDisksExistence([self.other_node, self.target_node])
9181
    self._CheckVolumeGroup([self.target_node, self.other_node])
9182

    
9183
    # Step: check other node consistency
9184
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9185
    self._CheckDisksConsistency(self.other_node,
9186
                                self.other_node == self.instance.primary_node,
9187
                                False)
9188

    
9189
    # Step: create new storage
9190
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9191
    iv_names = self._CreateNewStorage(self.target_node)
9192

    
9193
    # Step: for each lv, detach+rename*2+attach
9194
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9195
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9196
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9197

    
9198
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9199
                                                     old_lvs)
9200
      result.Raise("Can't detach drbd from local storage on node"
9201
                   " %s for device %s" % (self.target_node, dev.iv_name))
9202
      #dev.children = []
9203
      #cfg.Update(instance)
9204

    
9205
      # ok, we created the new LVs, so now we know we have the needed
9206
      # storage; as such, we proceed on the target node to rename
9207
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9208
      # using the assumption that logical_id == physical_id (which in
9209
      # turn is the unique_id on that node)
9210

    
9211
      # FIXME(iustin): use a better name for the replaced LVs
9212
      temp_suffix = int(time.time())
9213
      ren_fn = lambda d, suff: (d.physical_id[0],
9214
                                d.physical_id[1] + "_replaced-%s" % suff)
9215

    
9216
      # Build the rename list based on what LVs exist on the node
9217
      rename_old_to_new = []
9218
      for to_ren in old_lvs:
9219
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9220
        if not result.fail_msg and result.payload:
9221
          # device exists
9222
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9223

    
9224
      self.lu.LogInfo("Renaming the old LVs on the target node")
9225
      result = self.rpc.call_blockdev_rename(self.target_node,
9226
                                             rename_old_to_new)
9227
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9228

    
9229
      # Now we rename the new LVs to the old LVs
9230
      self.lu.LogInfo("Renaming the new LVs on the target node")
9231
      rename_new_to_old = [(new, old.physical_id)
9232
                           for old, new in zip(old_lvs, new_lvs)]
9233
      result = self.rpc.call_blockdev_rename(self.target_node,
9234
                                             rename_new_to_old)
9235
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9236

    
9237
      for old, new in zip(old_lvs, new_lvs):
9238
        new.logical_id = old.logical_id
9239
        self.cfg.SetDiskID(new, self.target_node)
9240

    
9241
      for disk in old_lvs:
9242
        disk.logical_id = ren_fn(disk, temp_suffix)
9243
        self.cfg.SetDiskID(disk, self.target_node)
9244

    
9245
      # Now that the new lvs have the old name, we can add them to the device
9246
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9247
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9248
                                                  new_lvs)
9249
      msg = result.fail_msg
9250
      if msg:
9251
        for new_lv in new_lvs:
9252
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9253
                                               new_lv).fail_msg
9254
          if msg2:
9255
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9256
                               hint=("cleanup manually the unused logical"
9257
                                     "volumes"))
9258
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9259

    
9260
      dev.children = new_lvs
9261

    
9262
      self.cfg.Update(self.instance, feedback_fn)
9263

    
9264
    cstep = 5
9265
    if self.early_release:
9266
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9267
      cstep += 1
9268
      self._RemoveOldStorage(self.target_node, iv_names)
9269
      # WARNING: we release both node locks here, do not do other RPCs
9270
      # than WaitForSync to the primary node
9271
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9272
                    names=[self.target_node, self.other_node])
9273

    
9274
    # Wait for sync
9275
    # This can fail as the old devices are degraded and _WaitForSync
9276
    # does a combined result over all disks, so we don't check its return value
9277
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9278
    cstep += 1
9279
    _WaitForSync(self.lu, self.instance)
9280

    
9281
    # Check all devices manually
9282
    self._CheckDevices(self.instance.primary_node, iv_names)
9283

    
9284
    # Step: remove old storage
9285
    if not self.early_release:
9286
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9287
      cstep += 1
9288
      self._RemoveOldStorage(self.target_node, iv_names)
9289

    
9290
  def _ExecDrbd8Secondary(self, feedback_fn):
9291
    """Replace the secondary node for DRBD 8.
9292

9293
    The algorithm for replace is quite complicated:
9294
      - for all disks of the instance:
9295
        - create new LVs on the new node with same names
9296
        - shutdown the drbd device on the old secondary
9297
        - disconnect the drbd network on the primary
9298
        - create the drbd device on the new secondary
9299
        - network attach the drbd on the primary, using an artifice:
9300
          the drbd code for Attach() will connect to the network if it
9301
          finds a device which is connected to the good local disks but
9302
          not network enabled
9303
      - wait for sync across all devices
9304
      - remove all disks from the old secondary
9305

9306
    Failures are not very well handled.
9307

9308
    """
9309
    steps_total = 6
9310

    
9311
    # Step: check device activation
9312
    self.lu.LogStep(1, steps_total, "Check device existence")
9313
    self._CheckDisksExistence([self.instance.primary_node])
9314
    self._CheckVolumeGroup([self.instance.primary_node])
9315

    
9316
    # Step: check other node consistency
9317
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9318
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9319

    
9320
    # Step: create new storage
9321
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9322
    for idx, dev in enumerate(self.instance.disks):
9323
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9324
                      (self.new_node, idx))
9325
      # we pass force_create=True to force LVM creation
9326
      for new_lv in dev.children:
9327
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9328
                        _GetInstanceInfoText(self.instance), False)
9329

    
9330
    # Step 4: dbrd minors and drbd setups changes
9331
    # after this, we must manually remove the drbd minors on both the
9332
    # error and the success paths
9333
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9334
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9335
                                         for dev in self.instance.disks],
9336
                                        self.instance.name)
9337
    logging.debug("Allocated minors %r", minors)
9338

    
9339
    iv_names = {}
9340
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9341
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9342
                      (self.new_node, idx))
9343
      # create new devices on new_node; note that we create two IDs:
9344
      # one without port, so the drbd will be activated without
9345
      # networking information on the new node at this stage, and one
9346
      # with network, for the latter activation in step 4
9347
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9348
      if self.instance.primary_node == o_node1:
9349
        p_minor = o_minor1
9350
      else:
9351
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9352
        p_minor = o_minor2
9353

    
9354
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9355
                      p_minor, new_minor, o_secret)
9356
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9357
                    p_minor, new_minor, o_secret)
9358

    
9359
      iv_names[idx] = (dev, dev.children, new_net_id)
9360
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9361
                    new_net_id)
9362
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9363
                              logical_id=new_alone_id,
9364
                              children=dev.children,
9365
                              size=dev.size)
9366
      try:
9367
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9368
                              _GetInstanceInfoText(self.instance), False)
9369
      except errors.GenericError:
9370
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9371
        raise
9372

    
9373
    # We have new devices, shutdown the drbd on the old secondary
9374
    for idx, dev in enumerate(self.instance.disks):
9375
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9376
      self.cfg.SetDiskID(dev, self.target_node)
9377
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9378
      if msg:
9379
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9380
                           "node: %s" % (idx, msg),
9381
                           hint=("Please cleanup this device manually as"
9382
                                 " soon as possible"))
9383

    
9384
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9385
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9386
                                               self.node_secondary_ip,
9387
                                               self.instance.disks)\
9388
                                              [self.instance.primary_node]
9389

    
9390
    msg = result.fail_msg
9391
    if msg:
9392
      # detaches didn't succeed (unlikely)
9393
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9394
      raise errors.OpExecError("Can't detach the disks from the network on"
9395
                               " old node: %s" % (msg,))
9396

    
9397
    # if we managed to detach at least one, we update all the disks of
9398
    # the instance to point to the new secondary
9399
    self.lu.LogInfo("Updating instance configuration")
9400
    for dev, _, new_logical_id in iv_names.itervalues():
9401
      dev.logical_id = new_logical_id
9402
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9403

    
9404
    self.cfg.Update(self.instance, feedback_fn)
9405

    
9406
    # and now perform the drbd attach
9407
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9408
                    " (standalone => connected)")
9409
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9410
                                            self.new_node],
9411
                                           self.node_secondary_ip,
9412
                                           self.instance.disks,
9413
                                           self.instance.name,
9414
                                           False)
9415
    for to_node, to_result in result.items():
9416
      msg = to_result.fail_msg
9417
      if msg:
9418
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9419
                           to_node, msg,
9420
                           hint=("please do a gnt-instance info to see the"
9421
                                 " status of disks"))
9422
    cstep = 5
9423
    if self.early_release:
9424
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9425
      cstep += 1
9426
      self._RemoveOldStorage(self.target_node, iv_names)
9427
      # WARNING: we release all node locks here, do not do other RPCs
9428
      # than WaitForSync to the primary node
9429
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9430
                    names=[self.instance.primary_node,
9431
                           self.target_node,
9432
                           self.new_node])
9433

    
9434
    # Wait for sync
9435
    # This can fail as the old devices are degraded and _WaitForSync
9436
    # does a combined result over all disks, so we don't check its return value
9437
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9438
    cstep += 1
9439
    _WaitForSync(self.lu, self.instance)
9440

    
9441
    # Check all devices manually
9442
    self._CheckDevices(self.instance.primary_node, iv_names)
9443

    
9444
    # Step: remove old storage
9445
    if not self.early_release:
9446
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9447
      self._RemoveOldStorage(self.target_node, iv_names)
9448

    
9449

    
9450
class LURepairNodeStorage(NoHooksLU):
9451
  """Repairs the volume group on a node.
9452

9453
  """
9454
  REQ_BGL = False
9455

    
9456
  def CheckArguments(self):
9457
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9458

    
9459
    storage_type = self.op.storage_type
9460

    
9461
    if (constants.SO_FIX_CONSISTENCY not in
9462
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9463
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9464
                                 " repaired" % storage_type,
9465
                                 errors.ECODE_INVAL)
9466

    
9467
  def ExpandNames(self):
9468
    self.needed_locks = {
9469
      locking.LEVEL_NODE: [self.op.node_name],
9470
      }
9471

    
9472
  def _CheckFaultyDisks(self, instance, node_name):
9473
    """Ensure faulty disks abort the opcode or at least warn."""
9474
    try:
9475
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9476
                                  node_name, True):
9477
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9478
                                   " node '%s'" % (instance.name, node_name),
9479
                                   errors.ECODE_STATE)
9480
    except errors.OpPrereqError, err:
9481
      if self.op.ignore_consistency:
9482
        self.proc.LogWarning(str(err.args[0]))
9483
      else:
9484
        raise
9485

    
9486
  def CheckPrereq(self):
9487
    """Check prerequisites.
9488

9489
    """
9490
    # Check whether any instance on this node has faulty disks
9491
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9492
      if not inst.admin_up:
9493
        continue
9494
      check_nodes = set(inst.all_nodes)
9495
      check_nodes.discard(self.op.node_name)
9496
      for inst_node_name in check_nodes:
9497
        self._CheckFaultyDisks(inst, inst_node_name)
9498

    
9499
  def Exec(self, feedback_fn):
9500
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9501
                (self.op.name, self.op.node_name))
9502

    
9503
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9504
    result = self.rpc.call_storage_execute(self.op.node_name,
9505
                                           self.op.storage_type, st_args,
9506
                                           self.op.name,
9507
                                           constants.SO_FIX_CONSISTENCY)
9508
    result.Raise("Failed to repair storage unit '%s' on %s" %
9509
                 (self.op.name, self.op.node_name))
9510

    
9511

    
9512
class LUNodeEvacStrategy(NoHooksLU):
9513
  """Computes the node evacuation strategy.
9514

9515
  """
9516
  REQ_BGL = False
9517

    
9518
  def CheckArguments(self):
9519
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9520

    
9521
  def ExpandNames(self):
9522
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9523
    self.needed_locks = locks = {}
9524
    if self.op.remote_node is None:
9525
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9526
    else:
9527
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9528
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9529

    
9530
  def Exec(self, feedback_fn):
9531
    if self.op.remote_node is not None:
9532
      instances = []
9533
      for node in self.op.nodes:
9534
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9535
      result = []
9536
      for i in instances:
9537
        if i.primary_node == self.op.remote_node:
9538
          raise errors.OpPrereqError("Node %s is the primary node of"
9539
                                     " instance %s, cannot use it as"
9540
                                     " secondary" %
9541
                                     (self.op.remote_node, i.name),
9542
                                     errors.ECODE_INVAL)
9543
        result.append([i.name, self.op.remote_node])
9544
    else:
9545
      ial = IAllocator(self.cfg, self.rpc,
9546
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9547
                       evac_nodes=self.op.nodes)
9548
      ial.Run(self.op.iallocator, validate=True)
9549
      if not ial.success:
9550
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9551
                                 errors.ECODE_NORES)
9552
      result = ial.result
9553
    return result
9554

    
9555

    
9556
class LUInstanceGrowDisk(LogicalUnit):
9557
  """Grow a disk of an instance.
9558

9559
  """
9560
  HPATH = "disk-grow"
9561
  HTYPE = constants.HTYPE_INSTANCE
9562
  REQ_BGL = False
9563

    
9564
  def ExpandNames(self):
9565
    self._ExpandAndLockInstance()
9566
    self.needed_locks[locking.LEVEL_NODE] = []
9567
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9568

    
9569
  def DeclareLocks(self, level):
9570
    if level == locking.LEVEL_NODE:
9571
      self._LockInstancesNodes()
9572

    
9573
  def BuildHooksEnv(self):
9574
    """Build hooks env.
9575

9576
    This runs on the master, the primary and all the secondaries.
9577

9578
    """
9579
    env = {
9580
      "DISK": self.op.disk,
9581
      "AMOUNT": self.op.amount,
9582
      }
9583
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9584
    return env
9585

    
9586
  def BuildHooksNodes(self):
9587
    """Build hooks nodes.
9588

9589
    """
9590
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9591
    return (nl, nl)
9592

    
9593
  def CheckPrereq(self):
9594
    """Check prerequisites.
9595

9596
    This checks that the instance is in the cluster.
9597

9598
    """
9599
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9600
    assert instance is not None, \
9601
      "Cannot retrieve locked instance %s" % self.op.instance_name
9602
    nodenames = list(instance.all_nodes)
9603
    for node in nodenames:
9604
      _CheckNodeOnline(self, node)
9605

    
9606
    self.instance = instance
9607

    
9608
    if instance.disk_template not in constants.DTS_GROWABLE:
9609
      raise errors.OpPrereqError("Instance's disk layout does not support"
9610
                                 " growing", errors.ECODE_INVAL)
9611

    
9612
    self.disk = instance.FindDisk(self.op.disk)
9613

    
9614
    if instance.disk_template not in (constants.DT_FILE,
9615
                                      constants.DT_SHARED_FILE):
9616
      # TODO: check the free disk space for file, when that feature will be
9617
      # supported
9618
      _CheckNodesFreeDiskPerVG(self, nodenames,
9619
                               self.disk.ComputeGrowth(self.op.amount))
9620

    
9621
  def Exec(self, feedback_fn):
9622
    """Execute disk grow.
9623

9624
    """
9625
    instance = self.instance
9626
    disk = self.disk
9627

    
9628
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9629
    if not disks_ok:
9630
      raise errors.OpExecError("Cannot activate block device to grow")
9631

    
9632
    # First run all grow ops in dry-run mode
9633
    for node in instance.all_nodes:
9634
      self.cfg.SetDiskID(disk, node)
9635
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
9636
      result.Raise("Grow request failed to node %s" % node)
9637

    
9638
    # We know that (as far as we can test) operations across different
9639
    # nodes will succeed, time to run it for real
9640
    for node in instance.all_nodes:
9641
      self.cfg.SetDiskID(disk, node)
9642
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
9643
      result.Raise("Grow request failed to node %s" % node)
9644

    
9645
      # TODO: Rewrite code to work properly
9646
      # DRBD goes into sync mode for a short amount of time after executing the
9647
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9648
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9649
      # time is a work-around.
9650
      time.sleep(5)
9651

    
9652
    disk.RecordGrow(self.op.amount)
9653
    self.cfg.Update(instance, feedback_fn)
9654
    if self.op.wait_for_sync:
9655
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9656
      if disk_abort:
9657
        self.proc.LogWarning("Disk sync-ing has not returned a good"
9658
                             " status; please check the instance")
9659
      if not instance.admin_up:
9660
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9661
    elif not instance.admin_up:
9662
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9663
                           " not supposed to be running because no wait for"
9664
                           " sync mode was requested")
9665

    
9666

    
9667
class LUInstanceQueryData(NoHooksLU):
9668
  """Query runtime instance data.
9669

9670
  """
9671
  REQ_BGL = False
9672

    
9673
  def ExpandNames(self):
9674
    self.needed_locks = {}
9675

    
9676
    # Use locking if requested or when non-static information is wanted
9677
    if not (self.op.static or self.op.use_locking):
9678
      self.LogWarning("Non-static data requested, locks need to be acquired")
9679
      self.op.use_locking = True
9680

    
9681
    if self.op.instances or not self.op.use_locking:
9682
      # Expand instance names right here
9683
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
9684
    else:
9685
      # Will use acquired locks
9686
      self.wanted_names = None
9687

    
9688
    if self.op.use_locking:
9689
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9690

    
9691
      if self.wanted_names is None:
9692
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9693
      else:
9694
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9695

    
9696
      self.needed_locks[locking.LEVEL_NODE] = []
9697
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9698
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9699

    
9700
  def DeclareLocks(self, level):
9701
    if self.op.use_locking and level == locking.LEVEL_NODE:
9702
      self._LockInstancesNodes()
9703

    
9704
  def CheckPrereq(self):
9705
    """Check prerequisites.
9706

9707
    This only checks the optional instance list against the existing names.
9708

9709
    """
9710
    if self.wanted_names is None:
9711
      assert self.op.use_locking, "Locking was not used"
9712
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
9713

    
9714
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
9715
                             for name in self.wanted_names]
9716

    
9717
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9718
    """Returns the status of a block device
9719

9720
    """
9721
    if self.op.static or not node:
9722
      return None
9723

    
9724
    self.cfg.SetDiskID(dev, node)
9725

    
9726
    result = self.rpc.call_blockdev_find(node, dev)
9727
    if result.offline:
9728
      return None
9729

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

    
9732
    status = result.payload
9733
    if status is None:
9734
      return None
9735

    
9736
    return (status.dev_path, status.major, status.minor,
9737
            status.sync_percent, status.estimated_time,
9738
            status.is_degraded, status.ldisk_status)
9739

    
9740
  def _ComputeDiskStatus(self, instance, snode, dev):
9741
    """Compute block device status.
9742

9743
    """
9744
    if dev.dev_type in constants.LDS_DRBD:
9745
      # we change the snode then (otherwise we use the one passed in)
9746
      if dev.logical_id[0] == instance.primary_node:
9747
        snode = dev.logical_id[1]
9748
      else:
9749
        snode = dev.logical_id[0]
9750

    
9751
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9752
                                              instance.name, dev)
9753
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9754

    
9755
    if dev.children:
9756
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9757
                      for child in dev.children]
9758
    else:
9759
      dev_children = []
9760

    
9761
    return {
9762
      "iv_name": dev.iv_name,
9763
      "dev_type": dev.dev_type,
9764
      "logical_id": dev.logical_id,
9765
      "physical_id": dev.physical_id,
9766
      "pstatus": dev_pstatus,
9767
      "sstatus": dev_sstatus,
9768
      "children": dev_children,
9769
      "mode": dev.mode,
9770
      "size": dev.size,
9771
      }
9772

    
9773
  def Exec(self, feedback_fn):
9774
    """Gather and return data"""
9775
    result = {}
9776

    
9777
    cluster = self.cfg.GetClusterInfo()
9778

    
9779
    for instance in self.wanted_instances:
9780
      if not self.op.static:
9781
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9782
                                                  instance.name,
9783
                                                  instance.hypervisor)
9784
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9785
        remote_info = remote_info.payload
9786
        if remote_info and "state" in remote_info:
9787
          remote_state = "up"
9788
        else:
9789
          remote_state = "down"
9790
      else:
9791
        remote_state = None
9792
      if instance.admin_up:
9793
        config_state = "up"
9794
      else:
9795
        config_state = "down"
9796

    
9797
      disks = [self._ComputeDiskStatus(instance, None, device)
9798
               for device in instance.disks]
9799

    
9800
      result[instance.name] = {
9801
        "name": instance.name,
9802
        "config_state": config_state,
9803
        "run_state": remote_state,
9804
        "pnode": instance.primary_node,
9805
        "snodes": instance.secondary_nodes,
9806
        "os": instance.os,
9807
        # this happens to be the same format used for hooks
9808
        "nics": _NICListToTuple(self, instance.nics),
9809
        "disk_template": instance.disk_template,
9810
        "disks": disks,
9811
        "hypervisor": instance.hypervisor,
9812
        "network_port": instance.network_port,
9813
        "hv_instance": instance.hvparams,
9814
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9815
        "be_instance": instance.beparams,
9816
        "be_actual": cluster.FillBE(instance),
9817
        "os_instance": instance.osparams,
9818
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9819
        "serial_no": instance.serial_no,
9820
        "mtime": instance.mtime,
9821
        "ctime": instance.ctime,
9822
        "uuid": instance.uuid,
9823
        }
9824

    
9825
    return result
9826

    
9827

    
9828
class LUInstanceSetParams(LogicalUnit):
9829
  """Modifies an instances's parameters.
9830

9831
  """
9832
  HPATH = "instance-modify"
9833
  HTYPE = constants.HTYPE_INSTANCE
9834
  REQ_BGL = False
9835

    
9836
  def CheckArguments(self):
9837
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9838
            self.op.hvparams or self.op.beparams or self.op.os_name):
9839
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9840

    
9841
    if self.op.hvparams:
9842
      _CheckGlobalHvParams(self.op.hvparams)
9843

    
9844
    # Disk validation
9845
    disk_addremove = 0
9846
    for disk_op, disk_dict in self.op.disks:
9847
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9848
      if disk_op == constants.DDM_REMOVE:
9849
        disk_addremove += 1
9850
        continue
9851
      elif disk_op == constants.DDM_ADD:
9852
        disk_addremove += 1
9853
      else:
9854
        if not isinstance(disk_op, int):
9855
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9856
        if not isinstance(disk_dict, dict):
9857
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9858
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9859

    
9860
      if disk_op == constants.DDM_ADD:
9861
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
9862
        if mode not in constants.DISK_ACCESS_SET:
9863
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9864
                                     errors.ECODE_INVAL)
9865
        size = disk_dict.get(constants.IDISK_SIZE, None)
9866
        if size is None:
9867
          raise errors.OpPrereqError("Required disk parameter size missing",
9868
                                     errors.ECODE_INVAL)
9869
        try:
9870
          size = int(size)
9871
        except (TypeError, ValueError), err:
9872
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9873
                                     str(err), errors.ECODE_INVAL)
9874
        disk_dict[constants.IDISK_SIZE] = size
9875
      else:
9876
        # modification of disk
9877
        if constants.IDISK_SIZE in disk_dict:
9878
          raise errors.OpPrereqError("Disk size change not possible, use"
9879
                                     " grow-disk", errors.ECODE_INVAL)
9880

    
9881
    if disk_addremove > 1:
9882
      raise errors.OpPrereqError("Only one disk add or remove operation"
9883
                                 " supported at a time", errors.ECODE_INVAL)
9884

    
9885
    if self.op.disks and self.op.disk_template is not None:
9886
      raise errors.OpPrereqError("Disk template conversion and other disk"
9887
                                 " changes not supported at the same time",
9888
                                 errors.ECODE_INVAL)
9889

    
9890
    if (self.op.disk_template and
9891
        self.op.disk_template in constants.DTS_INT_MIRROR and
9892
        self.op.remote_node is None):
9893
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9894
                                 " one requires specifying a secondary node",
9895
                                 errors.ECODE_INVAL)
9896

    
9897
    # NIC validation
9898
    nic_addremove = 0
9899
    for nic_op, nic_dict in self.op.nics:
9900
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9901
      if nic_op == constants.DDM_REMOVE:
9902
        nic_addremove += 1
9903
        continue
9904
      elif nic_op == constants.DDM_ADD:
9905
        nic_addremove += 1
9906
      else:
9907
        if not isinstance(nic_op, int):
9908
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9909
        if not isinstance(nic_dict, dict):
9910
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9911
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9912

    
9913
      # nic_dict should be a dict
9914
      nic_ip = nic_dict.get(constants.INIC_IP, None)
9915
      if nic_ip is not None:
9916
        if nic_ip.lower() == constants.VALUE_NONE:
9917
          nic_dict[constants.INIC_IP] = None
9918
        else:
9919
          if not netutils.IPAddress.IsValid(nic_ip):
9920
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9921
                                       errors.ECODE_INVAL)
9922

    
9923
      nic_bridge = nic_dict.get('bridge', None)
9924
      nic_link = nic_dict.get(constants.INIC_LINK, None)
9925
      if nic_bridge and nic_link:
9926
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9927
                                   " at the same time", errors.ECODE_INVAL)
9928
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9929
        nic_dict['bridge'] = None
9930
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9931
        nic_dict[constants.INIC_LINK] = None
9932

    
9933
      if nic_op == constants.DDM_ADD:
9934
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
9935
        if nic_mac is None:
9936
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
9937

    
9938
      if constants.INIC_MAC in nic_dict:
9939
        nic_mac = nic_dict[constants.INIC_MAC]
9940
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9941
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9942

    
9943
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9944
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9945
                                     " modifying an existing nic",
9946
                                     errors.ECODE_INVAL)
9947

    
9948
    if nic_addremove > 1:
9949
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9950
                                 " supported at a time", errors.ECODE_INVAL)
9951

    
9952
  def ExpandNames(self):
9953
    self._ExpandAndLockInstance()
9954
    self.needed_locks[locking.LEVEL_NODE] = []
9955
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9956

    
9957
  def DeclareLocks(self, level):
9958
    if level == locking.LEVEL_NODE:
9959
      self._LockInstancesNodes()
9960
      if self.op.disk_template and self.op.remote_node:
9961
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9962
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9963

    
9964
  def BuildHooksEnv(self):
9965
    """Build hooks env.
9966

9967
    This runs on the master, primary and secondaries.
9968

9969
    """
9970
    args = dict()
9971
    if constants.BE_MEMORY in self.be_new:
9972
      args['memory'] = self.be_new[constants.BE_MEMORY]
9973
    if constants.BE_VCPUS in self.be_new:
9974
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9975
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9976
    # information at all.
9977
    if self.op.nics:
9978
      args['nics'] = []
9979
      nic_override = dict(self.op.nics)
9980
      for idx, nic in enumerate(self.instance.nics):
9981
        if idx in nic_override:
9982
          this_nic_override = nic_override[idx]
9983
        else:
9984
          this_nic_override = {}
9985
        if constants.INIC_IP in this_nic_override:
9986
          ip = this_nic_override[constants.INIC_IP]
9987
        else:
9988
          ip = nic.ip
9989
        if constants.INIC_MAC in this_nic_override:
9990
          mac = this_nic_override[constants.INIC_MAC]
9991
        else:
9992
          mac = nic.mac
9993
        if idx in self.nic_pnew:
9994
          nicparams = self.nic_pnew[idx]
9995
        else:
9996
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9997
        mode = nicparams[constants.NIC_MODE]
9998
        link = nicparams[constants.NIC_LINK]
9999
        args['nics'].append((ip, mac, mode, link))
10000
      if constants.DDM_ADD in nic_override:
10001
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10002
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10003
        nicparams = self.nic_pnew[constants.DDM_ADD]
10004
        mode = nicparams[constants.NIC_MODE]
10005
        link = nicparams[constants.NIC_LINK]
10006
        args['nics'].append((ip, mac, mode, link))
10007
      elif constants.DDM_REMOVE in nic_override:
10008
        del args['nics'][-1]
10009

    
10010
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10011
    if self.op.disk_template:
10012
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10013

    
10014
    return env
10015

    
10016
  def BuildHooksNodes(self):
10017
    """Build hooks nodes.
10018

10019
    """
10020
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10021
    return (nl, nl)
10022

    
10023
  def CheckPrereq(self):
10024
    """Check prerequisites.
10025

10026
    This only checks the instance list against the existing names.
10027

10028
    """
10029
    # checking the new params on the primary/secondary nodes
10030

    
10031
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10032
    cluster = self.cluster = self.cfg.GetClusterInfo()
10033
    assert self.instance is not None, \
10034
      "Cannot retrieve locked instance %s" % self.op.instance_name
10035
    pnode = instance.primary_node
10036
    nodelist = list(instance.all_nodes)
10037

    
10038
    # OS change
10039
    if self.op.os_name and not self.op.force:
10040
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10041
                      self.op.force_variant)
10042
      instance_os = self.op.os_name
10043
    else:
10044
      instance_os = instance.os
10045

    
10046
    if self.op.disk_template:
10047
      if instance.disk_template == self.op.disk_template:
10048
        raise errors.OpPrereqError("Instance already has disk template %s" %
10049
                                   instance.disk_template, errors.ECODE_INVAL)
10050

    
10051
      if (instance.disk_template,
10052
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10053
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10054
                                   " %s to %s" % (instance.disk_template,
10055
                                                  self.op.disk_template),
10056
                                   errors.ECODE_INVAL)
10057
      _CheckInstanceDown(self, instance, "cannot change disk template")
10058
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10059
        if self.op.remote_node == pnode:
10060
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10061
                                     " as the primary node of the instance" %
10062
                                     self.op.remote_node, errors.ECODE_STATE)
10063
        _CheckNodeOnline(self, self.op.remote_node)
10064
        _CheckNodeNotDrained(self, self.op.remote_node)
10065
        # FIXME: here we assume that the old instance type is DT_PLAIN
10066
        assert instance.disk_template == constants.DT_PLAIN
10067
        disks = [{constants.IDISK_SIZE: d.size,
10068
                  constants.IDISK_VG: d.logical_id[0]}
10069
                 for d in instance.disks]
10070
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10071
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10072

    
10073
    # hvparams processing
10074
    if self.op.hvparams:
10075
      hv_type = instance.hypervisor
10076
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10077
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10078
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10079

    
10080
      # local check
10081
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10082
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10083
      self.hv_new = hv_new # the new actual values
10084
      self.hv_inst = i_hvdict # the new dict (without defaults)
10085
    else:
10086
      self.hv_new = self.hv_inst = {}
10087

    
10088
    # beparams processing
10089
    if self.op.beparams:
10090
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10091
                                   use_none=True)
10092
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10093
      be_new = cluster.SimpleFillBE(i_bedict)
10094
      self.be_new = be_new # the new actual values
10095
      self.be_inst = i_bedict # the new dict (without defaults)
10096
    else:
10097
      self.be_new = self.be_inst = {}
10098
    be_old = cluster.FillBE(instance)
10099

    
10100
    # osparams processing
10101
    if self.op.osparams:
10102
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10103
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10104
      self.os_inst = i_osdict # the new dict (without defaults)
10105
    else:
10106
      self.os_inst = {}
10107

    
10108
    self.warn = []
10109

    
10110
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10111
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10112
      mem_check_list = [pnode]
10113
      if be_new[constants.BE_AUTO_BALANCE]:
10114
        # either we changed auto_balance to yes or it was from before
10115
        mem_check_list.extend(instance.secondary_nodes)
10116
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10117
                                                  instance.hypervisor)
10118
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10119
                                         instance.hypervisor)
10120
      pninfo = nodeinfo[pnode]
10121
      msg = pninfo.fail_msg
10122
      if msg:
10123
        # Assume the primary node is unreachable and go ahead
10124
        self.warn.append("Can't get info from primary node %s: %s" %
10125
                         (pnode,  msg))
10126
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10127
        self.warn.append("Node data from primary node %s doesn't contain"
10128
                         " free memory information" % pnode)
10129
      elif instance_info.fail_msg:
10130
        self.warn.append("Can't get instance runtime information: %s" %
10131
                        instance_info.fail_msg)
10132
      else:
10133
        if instance_info.payload:
10134
          current_mem = int(instance_info.payload['memory'])
10135
        else:
10136
          # Assume instance not running
10137
          # (there is a slight race condition here, but it's not very probable,
10138
          # and we have no other way to check)
10139
          current_mem = 0
10140
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10141
                    pninfo.payload['memory_free'])
10142
        if miss_mem > 0:
10143
          raise errors.OpPrereqError("This change will prevent the instance"
10144
                                     " from starting, due to %d MB of memory"
10145
                                     " missing on its primary node" % miss_mem,
10146
                                     errors.ECODE_NORES)
10147

    
10148
      if be_new[constants.BE_AUTO_BALANCE]:
10149
        for node, nres in nodeinfo.items():
10150
          if node not in instance.secondary_nodes:
10151
            continue
10152
          nres.Raise("Can't get info from secondary node %s" % node,
10153
                     prereq=True, ecode=errors.ECODE_STATE)
10154
          if not isinstance(nres.payload.get('memory_free', None), int):
10155
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10156
                                       " memory information" % node,
10157
                                       errors.ECODE_STATE)
10158
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10159
            raise errors.OpPrereqError("This change will prevent the instance"
10160
                                       " from failover to its secondary node"
10161
                                       " %s, due to not enough memory" % node,
10162
                                       errors.ECODE_STATE)
10163

    
10164
    # NIC processing
10165
    self.nic_pnew = {}
10166
    self.nic_pinst = {}
10167
    for nic_op, nic_dict in self.op.nics:
10168
      if nic_op == constants.DDM_REMOVE:
10169
        if not instance.nics:
10170
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10171
                                     errors.ECODE_INVAL)
10172
        continue
10173
      if nic_op != constants.DDM_ADD:
10174
        # an existing nic
10175
        if not instance.nics:
10176
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10177
                                     " no NICs" % nic_op,
10178
                                     errors.ECODE_INVAL)
10179
        if nic_op < 0 or nic_op >= len(instance.nics):
10180
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10181
                                     " are 0 to %d" %
10182
                                     (nic_op, len(instance.nics) - 1),
10183
                                     errors.ECODE_INVAL)
10184
        old_nic_params = instance.nics[nic_op].nicparams
10185
        old_nic_ip = instance.nics[nic_op].ip
10186
      else:
10187
        old_nic_params = {}
10188
        old_nic_ip = None
10189

    
10190
      update_params_dict = dict([(key, nic_dict[key])
10191
                                 for key in constants.NICS_PARAMETERS
10192
                                 if key in nic_dict])
10193

    
10194
      if 'bridge' in nic_dict:
10195
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10196

    
10197
      new_nic_params = _GetUpdatedParams(old_nic_params,
10198
                                         update_params_dict)
10199
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10200
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10201
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10202
      self.nic_pinst[nic_op] = new_nic_params
10203
      self.nic_pnew[nic_op] = new_filled_nic_params
10204
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10205

    
10206
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10207
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10208
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10209
        if msg:
10210
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10211
          if self.op.force:
10212
            self.warn.append(msg)
10213
          else:
10214
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10215
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10216
        if constants.INIC_IP in nic_dict:
10217
          nic_ip = nic_dict[constants.INIC_IP]
10218
        else:
10219
          nic_ip = old_nic_ip
10220
        if nic_ip is None:
10221
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10222
                                     ' on a routed nic', errors.ECODE_INVAL)
10223
      if constants.INIC_MAC in nic_dict:
10224
        nic_mac = nic_dict[constants.INIC_MAC]
10225
        if nic_mac is None:
10226
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10227
                                     errors.ECODE_INVAL)
10228
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10229
          # otherwise generate the mac
10230
          nic_dict[constants.INIC_MAC] = \
10231
            self.cfg.GenerateMAC(self.proc.GetECId())
10232
        else:
10233
          # or validate/reserve the current one
10234
          try:
10235
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10236
          except errors.ReservationError:
10237
            raise errors.OpPrereqError("MAC address %s already in use"
10238
                                       " in cluster" % nic_mac,
10239
                                       errors.ECODE_NOTUNIQUE)
10240

    
10241
    # DISK processing
10242
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10243
      raise errors.OpPrereqError("Disk operations not supported for"
10244
                                 " diskless instances",
10245
                                 errors.ECODE_INVAL)
10246
    for disk_op, _ in self.op.disks:
10247
      if disk_op == constants.DDM_REMOVE:
10248
        if len(instance.disks) == 1:
10249
          raise errors.OpPrereqError("Cannot remove the last disk of"
10250
                                     " an instance", errors.ECODE_INVAL)
10251
        _CheckInstanceDown(self, instance, "cannot remove disks")
10252

    
10253
      if (disk_op == constants.DDM_ADD and
10254
          len(instance.disks) >= constants.MAX_DISKS):
10255
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10256
                                   " add more" % constants.MAX_DISKS,
10257
                                   errors.ECODE_STATE)
10258
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10259
        # an existing disk
10260
        if disk_op < 0 or disk_op >= len(instance.disks):
10261
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10262
                                     " are 0 to %d" %
10263
                                     (disk_op, len(instance.disks)),
10264
                                     errors.ECODE_INVAL)
10265

    
10266
    return
10267

    
10268
  def _ConvertPlainToDrbd(self, feedback_fn):
10269
    """Converts an instance from plain to drbd.
10270

10271
    """
10272
    feedback_fn("Converting template to drbd")
10273
    instance = self.instance
10274
    pnode = instance.primary_node
10275
    snode = self.op.remote_node
10276

    
10277
    # create a fake disk info for _GenerateDiskTemplate
10278
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10279
                  constants.IDISK_VG: d.logical_id[0]}
10280
                 for d in instance.disks]
10281
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10282
                                      instance.name, pnode, [snode],
10283
                                      disk_info, None, None, 0, feedback_fn)
10284
    info = _GetInstanceInfoText(instance)
10285
    feedback_fn("Creating aditional volumes...")
10286
    # first, create the missing data and meta devices
10287
    for disk in new_disks:
10288
      # unfortunately this is... not too nice
10289
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10290
                            info, True)
10291
      for child in disk.children:
10292
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10293
    # at this stage, all new LVs have been created, we can rename the
10294
    # old ones
10295
    feedback_fn("Renaming original volumes...")
10296
    rename_list = [(o, n.children[0].logical_id)
10297
                   for (o, n) in zip(instance.disks, new_disks)]
10298
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10299
    result.Raise("Failed to rename original LVs")
10300

    
10301
    feedback_fn("Initializing DRBD devices...")
10302
    # all child devices are in place, we can now create the DRBD devices
10303
    for disk in new_disks:
10304
      for node in [pnode, snode]:
10305
        f_create = node == pnode
10306
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10307

    
10308
    # at this point, the instance has been modified
10309
    instance.disk_template = constants.DT_DRBD8
10310
    instance.disks = new_disks
10311
    self.cfg.Update(instance, feedback_fn)
10312

    
10313
    # disks are created, waiting for sync
10314
    disk_abort = not _WaitForSync(self, instance,
10315
                                  oneshot=not self.op.wait_for_sync)
10316
    if disk_abort:
10317
      raise errors.OpExecError("There are some degraded disks for"
10318
                               " this instance, please cleanup manually")
10319

    
10320
  def _ConvertDrbdToPlain(self, feedback_fn):
10321
    """Converts an instance from drbd to plain.
10322

10323
    """
10324
    instance = self.instance
10325
    assert len(instance.secondary_nodes) == 1
10326
    pnode = instance.primary_node
10327
    snode = instance.secondary_nodes[0]
10328
    feedback_fn("Converting template to plain")
10329

    
10330
    old_disks = instance.disks
10331
    new_disks = [d.children[0] for d in old_disks]
10332

    
10333
    # copy over size and mode
10334
    for parent, child in zip(old_disks, new_disks):
10335
      child.size = parent.size
10336
      child.mode = parent.mode
10337

    
10338
    # update instance structure
10339
    instance.disks = new_disks
10340
    instance.disk_template = constants.DT_PLAIN
10341
    self.cfg.Update(instance, feedback_fn)
10342

    
10343
    feedback_fn("Removing volumes on the secondary node...")
10344
    for disk in old_disks:
10345
      self.cfg.SetDiskID(disk, snode)
10346
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10347
      if msg:
10348
        self.LogWarning("Could not remove block device %s on node %s,"
10349
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10350

    
10351
    feedback_fn("Removing unneeded volumes on the primary node...")
10352
    for idx, disk in enumerate(old_disks):
10353
      meta = disk.children[1]
10354
      self.cfg.SetDiskID(meta, pnode)
10355
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10356
      if msg:
10357
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10358
                        " continuing anyway: %s", idx, pnode, msg)
10359

    
10360
  def Exec(self, feedback_fn):
10361
    """Modifies an instance.
10362

10363
    All parameters take effect only at the next restart of the instance.
10364

10365
    """
10366
    # Process here the warnings from CheckPrereq, as we don't have a
10367
    # feedback_fn there.
10368
    for warn in self.warn:
10369
      feedback_fn("WARNING: %s" % warn)
10370

    
10371
    result = []
10372
    instance = self.instance
10373
    # disk changes
10374
    for disk_op, disk_dict in self.op.disks:
10375
      if disk_op == constants.DDM_REMOVE:
10376
        # remove the last disk
10377
        device = instance.disks.pop()
10378
        device_idx = len(instance.disks)
10379
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10380
          self.cfg.SetDiskID(disk, node)
10381
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10382
          if msg:
10383
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10384
                            " continuing anyway", device_idx, node, msg)
10385
        result.append(("disk/%d" % device_idx, "remove"))
10386
      elif disk_op == constants.DDM_ADD:
10387
        # add a new disk
10388
        if instance.disk_template in (constants.DT_FILE,
10389
                                        constants.DT_SHARED_FILE):
10390
          file_driver, file_path = instance.disks[0].logical_id
10391
          file_path = os.path.dirname(file_path)
10392
        else:
10393
          file_driver = file_path = None
10394
        disk_idx_base = len(instance.disks)
10395
        new_disk = _GenerateDiskTemplate(self,
10396
                                         instance.disk_template,
10397
                                         instance.name, instance.primary_node,
10398
                                         instance.secondary_nodes,
10399
                                         [disk_dict],
10400
                                         file_path,
10401
                                         file_driver,
10402
                                         disk_idx_base, feedback_fn)[0]
10403
        instance.disks.append(new_disk)
10404
        info = _GetInstanceInfoText(instance)
10405

    
10406
        logging.info("Creating volume %s for instance %s",
10407
                     new_disk.iv_name, instance.name)
10408
        # Note: this needs to be kept in sync with _CreateDisks
10409
        #HARDCODE
10410
        for node in instance.all_nodes:
10411
          f_create = node == instance.primary_node
10412
          try:
10413
            _CreateBlockDev(self, node, instance, new_disk,
10414
                            f_create, info, f_create)
10415
          except errors.OpExecError, err:
10416
            self.LogWarning("Failed to create volume %s (%s) on"
10417
                            " node %s: %s",
10418
                            new_disk.iv_name, new_disk, node, err)
10419
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10420
                       (new_disk.size, new_disk.mode)))
10421
      else:
10422
        # change a given disk
10423
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10424
        result.append(("disk.mode/%d" % disk_op,
10425
                       disk_dict[constants.IDISK_MODE]))
10426

    
10427
    if self.op.disk_template:
10428
      r_shut = _ShutdownInstanceDisks(self, instance)
10429
      if not r_shut:
10430
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10431
                                 " proceed with disk template conversion")
10432
      mode = (instance.disk_template, self.op.disk_template)
10433
      try:
10434
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10435
      except:
10436
        self.cfg.ReleaseDRBDMinors(instance.name)
10437
        raise
10438
      result.append(("disk_template", self.op.disk_template))
10439

    
10440
    # NIC changes
10441
    for nic_op, nic_dict in self.op.nics:
10442
      if nic_op == constants.DDM_REMOVE:
10443
        # remove the last nic
10444
        del instance.nics[-1]
10445
        result.append(("nic.%d" % len(instance.nics), "remove"))
10446
      elif nic_op == constants.DDM_ADD:
10447
        # mac and bridge should be set, by now
10448
        mac = nic_dict[constants.INIC_MAC]
10449
        ip = nic_dict.get(constants.INIC_IP, None)
10450
        nicparams = self.nic_pinst[constants.DDM_ADD]
10451
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10452
        instance.nics.append(new_nic)
10453
        result.append(("nic.%d" % (len(instance.nics) - 1),
10454
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10455
                       (new_nic.mac, new_nic.ip,
10456
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10457
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10458
                       )))
10459
      else:
10460
        for key in (constants.INIC_MAC, constants.INIC_IP):
10461
          if key in nic_dict:
10462
            setattr(instance.nics[nic_op], key, nic_dict[key])
10463
        if nic_op in self.nic_pinst:
10464
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10465
        for key, val in nic_dict.iteritems():
10466
          result.append(("nic.%s/%d" % (key, nic_op), val))
10467

    
10468
    # hvparams changes
10469
    if self.op.hvparams:
10470
      instance.hvparams = self.hv_inst
10471
      for key, val in self.op.hvparams.iteritems():
10472
        result.append(("hv/%s" % key, val))
10473

    
10474
    # beparams changes
10475
    if self.op.beparams:
10476
      instance.beparams = self.be_inst
10477
      for key, val in self.op.beparams.iteritems():
10478
        result.append(("be/%s" % key, val))
10479

    
10480
    # OS change
10481
    if self.op.os_name:
10482
      instance.os = self.op.os_name
10483

    
10484
    # osparams changes
10485
    if self.op.osparams:
10486
      instance.osparams = self.os_inst
10487
      for key, val in self.op.osparams.iteritems():
10488
        result.append(("os/%s" % key, val))
10489

    
10490
    self.cfg.Update(instance, feedback_fn)
10491

    
10492
    return result
10493

    
10494
  _DISK_CONVERSIONS = {
10495
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10496
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10497
    }
10498

    
10499

    
10500
class LUBackupQuery(NoHooksLU):
10501
  """Query the exports list
10502

10503
  """
10504
  REQ_BGL = False
10505

    
10506
  def ExpandNames(self):
10507
    self.needed_locks = {}
10508
    self.share_locks[locking.LEVEL_NODE] = 1
10509
    if not self.op.nodes:
10510
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10511
    else:
10512
      self.needed_locks[locking.LEVEL_NODE] = \
10513
        _GetWantedNodes(self, self.op.nodes)
10514

    
10515
  def Exec(self, feedback_fn):
10516
    """Compute the list of all the exported system images.
10517

10518
    @rtype: dict
10519
    @return: a dictionary with the structure node->(export-list)
10520
        where export-list is a list of the instances exported on
10521
        that node.
10522

10523
    """
10524
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10525
    rpcresult = self.rpc.call_export_list(self.nodes)
10526
    result = {}
10527
    for node in rpcresult:
10528
      if rpcresult[node].fail_msg:
10529
        result[node] = False
10530
      else:
10531
        result[node] = rpcresult[node].payload
10532

    
10533
    return result
10534

    
10535

    
10536
class LUBackupPrepare(NoHooksLU):
10537
  """Prepares an instance for an export and returns useful information.
10538

10539
  """
10540
  REQ_BGL = False
10541

    
10542
  def ExpandNames(self):
10543
    self._ExpandAndLockInstance()
10544

    
10545
  def CheckPrereq(self):
10546
    """Check prerequisites.
10547

10548
    """
10549
    instance_name = self.op.instance_name
10550

    
10551
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10552
    assert self.instance is not None, \
10553
          "Cannot retrieve locked instance %s" % self.op.instance_name
10554
    _CheckNodeOnline(self, self.instance.primary_node)
10555

    
10556
    self._cds = _GetClusterDomainSecret()
10557

    
10558
  def Exec(self, feedback_fn):
10559
    """Prepares an instance for an export.
10560

10561
    """
10562
    instance = self.instance
10563

    
10564
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10565
      salt = utils.GenerateSecret(8)
10566

    
10567
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10568
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10569
                                              constants.RIE_CERT_VALIDITY)
10570
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10571

    
10572
      (name, cert_pem) = result.payload
10573

    
10574
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10575
                                             cert_pem)
10576

    
10577
      return {
10578
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10579
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10580
                          salt),
10581
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10582
        }
10583

    
10584
    return None
10585

    
10586

    
10587
class LUBackupExport(LogicalUnit):
10588
  """Export an instance to an image in the cluster.
10589

10590
  """
10591
  HPATH = "instance-export"
10592
  HTYPE = constants.HTYPE_INSTANCE
10593
  REQ_BGL = False
10594

    
10595
  def CheckArguments(self):
10596
    """Check the arguments.
10597

10598
    """
10599
    self.x509_key_name = self.op.x509_key_name
10600
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10601

    
10602
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10603
      if not self.x509_key_name:
10604
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10605
                                   errors.ECODE_INVAL)
10606

    
10607
      if not self.dest_x509_ca_pem:
10608
        raise errors.OpPrereqError("Missing destination X509 CA",
10609
                                   errors.ECODE_INVAL)
10610

    
10611
  def ExpandNames(self):
10612
    self._ExpandAndLockInstance()
10613

    
10614
    # Lock all nodes for local exports
10615
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10616
      # FIXME: lock only instance primary and destination node
10617
      #
10618
      # Sad but true, for now we have do lock all nodes, as we don't know where
10619
      # the previous export might be, and in this LU we search for it and
10620
      # remove it from its current node. In the future we could fix this by:
10621
      #  - making a tasklet to search (share-lock all), then create the
10622
      #    new one, then one to remove, after
10623
      #  - removing the removal operation altogether
10624
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10625

    
10626
  def DeclareLocks(self, level):
10627
    """Last minute lock declaration."""
10628
    # All nodes are locked anyway, so nothing to do here.
10629

    
10630
  def BuildHooksEnv(self):
10631
    """Build hooks env.
10632

10633
    This will run on the master, primary node and target node.
10634

10635
    """
10636
    env = {
10637
      "EXPORT_MODE": self.op.mode,
10638
      "EXPORT_NODE": self.op.target_node,
10639
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10640
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10641
      # TODO: Generic function for boolean env variables
10642
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10643
      }
10644

    
10645
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10646

    
10647
    return env
10648

    
10649
  def BuildHooksNodes(self):
10650
    """Build hooks nodes.
10651

10652
    """
10653
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10654

    
10655
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10656
      nl.append(self.op.target_node)
10657

    
10658
    return (nl, nl)
10659

    
10660
  def CheckPrereq(self):
10661
    """Check prerequisites.
10662

10663
    This checks that the instance and node names are valid.
10664

10665
    """
10666
    instance_name = self.op.instance_name
10667

    
10668
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10669
    assert self.instance is not None, \
10670
          "Cannot retrieve locked instance %s" % self.op.instance_name
10671
    _CheckNodeOnline(self, self.instance.primary_node)
10672

    
10673
    if (self.op.remove_instance and self.instance.admin_up and
10674
        not self.op.shutdown):
10675
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10676
                                 " down before")
10677

    
10678
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10679
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10680
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10681
      assert self.dst_node is not None
10682

    
10683
      _CheckNodeOnline(self, self.dst_node.name)
10684
      _CheckNodeNotDrained(self, self.dst_node.name)
10685

    
10686
      self._cds = None
10687
      self.dest_disk_info = None
10688
      self.dest_x509_ca = None
10689

    
10690
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10691
      self.dst_node = None
10692

    
10693
      if len(self.op.target_node) != len(self.instance.disks):
10694
        raise errors.OpPrereqError(("Received destination information for %s"
10695
                                    " disks, but instance %s has %s disks") %
10696
                                   (len(self.op.target_node), instance_name,
10697
                                    len(self.instance.disks)),
10698
                                   errors.ECODE_INVAL)
10699

    
10700
      cds = _GetClusterDomainSecret()
10701

    
10702
      # Check X509 key name
10703
      try:
10704
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10705
      except (TypeError, ValueError), err:
10706
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10707

    
10708
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10709
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10710
                                   errors.ECODE_INVAL)
10711

    
10712
      # Load and verify CA
10713
      try:
10714
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10715
      except OpenSSL.crypto.Error, err:
10716
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10717
                                   (err, ), errors.ECODE_INVAL)
10718

    
10719
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10720
      if errcode is not None:
10721
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10722
                                   (msg, ), errors.ECODE_INVAL)
10723

    
10724
      self.dest_x509_ca = cert
10725

    
10726
      # Verify target information
10727
      disk_info = []
10728
      for idx, disk_data in enumerate(self.op.target_node):
10729
        try:
10730
          (host, port, magic) = \
10731
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10732
        except errors.GenericError, err:
10733
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10734
                                     (idx, err), errors.ECODE_INVAL)
10735

    
10736
        disk_info.append((host, port, magic))
10737

    
10738
      assert len(disk_info) == len(self.op.target_node)
10739
      self.dest_disk_info = disk_info
10740

    
10741
    else:
10742
      raise errors.ProgrammerError("Unhandled export mode %r" %
10743
                                   self.op.mode)
10744

    
10745
    # instance disk type verification
10746
    # TODO: Implement export support for file-based disks
10747
    for disk in self.instance.disks:
10748
      if disk.dev_type == constants.LD_FILE:
10749
        raise errors.OpPrereqError("Export not supported for instances with"
10750
                                   " file-based disks", errors.ECODE_INVAL)
10751

    
10752
  def _CleanupExports(self, feedback_fn):
10753
    """Removes exports of current instance from all other nodes.
10754

10755
    If an instance in a cluster with nodes A..D was exported to node C, its
10756
    exports will be removed from the nodes A, B and D.
10757

10758
    """
10759
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10760

    
10761
    nodelist = self.cfg.GetNodeList()
10762
    nodelist.remove(self.dst_node.name)
10763

    
10764
    # on one-node clusters nodelist will be empty after the removal
10765
    # if we proceed the backup would be removed because OpBackupQuery
10766
    # substitutes an empty list with the full cluster node list.
10767
    iname = self.instance.name
10768
    if nodelist:
10769
      feedback_fn("Removing old exports for instance %s" % iname)
10770
      exportlist = self.rpc.call_export_list(nodelist)
10771
      for node in exportlist:
10772
        if exportlist[node].fail_msg:
10773
          continue
10774
        if iname in exportlist[node].payload:
10775
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10776
          if msg:
10777
            self.LogWarning("Could not remove older export for instance %s"
10778
                            " on node %s: %s", iname, node, msg)
10779

    
10780
  def Exec(self, feedback_fn):
10781
    """Export an instance to an image in the cluster.
10782

10783
    """
10784
    assert self.op.mode in constants.EXPORT_MODES
10785

    
10786
    instance = self.instance
10787
    src_node = instance.primary_node
10788

    
10789
    if self.op.shutdown:
10790
      # shutdown the instance, but not the disks
10791
      feedback_fn("Shutting down instance %s" % instance.name)
10792
      result = self.rpc.call_instance_shutdown(src_node, instance,
10793
                                               self.op.shutdown_timeout)
10794
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10795
      result.Raise("Could not shutdown instance %s on"
10796
                   " node %s" % (instance.name, src_node))
10797

    
10798
    # set the disks ID correctly since call_instance_start needs the
10799
    # correct drbd minor to create the symlinks
10800
    for disk in instance.disks:
10801
      self.cfg.SetDiskID(disk, src_node)
10802

    
10803
    activate_disks = (not instance.admin_up)
10804

    
10805
    if activate_disks:
10806
      # Activate the instance disks if we'exporting a stopped instance
10807
      feedback_fn("Activating disks for %s" % instance.name)
10808
      _StartInstanceDisks(self, instance, None)
10809

    
10810
    try:
10811
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10812
                                                     instance)
10813

    
10814
      helper.CreateSnapshots()
10815
      try:
10816
        if (self.op.shutdown and instance.admin_up and
10817
            not self.op.remove_instance):
10818
          assert not activate_disks
10819
          feedback_fn("Starting instance %s" % instance.name)
10820
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10821
          msg = result.fail_msg
10822
          if msg:
10823
            feedback_fn("Failed to start instance: %s" % msg)
10824
            _ShutdownInstanceDisks(self, instance)
10825
            raise errors.OpExecError("Could not start instance: %s" % msg)
10826

    
10827
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10828
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10829
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10830
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10831
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10832

    
10833
          (key_name, _, _) = self.x509_key_name
10834

    
10835
          dest_ca_pem = \
10836
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10837
                                            self.dest_x509_ca)
10838

    
10839
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10840
                                                     key_name, dest_ca_pem,
10841
                                                     timeouts)
10842
      finally:
10843
        helper.Cleanup()
10844

    
10845
      # Check for backwards compatibility
10846
      assert len(dresults) == len(instance.disks)
10847
      assert compat.all(isinstance(i, bool) for i in dresults), \
10848
             "Not all results are boolean: %r" % dresults
10849

    
10850
    finally:
10851
      if activate_disks:
10852
        feedback_fn("Deactivating disks for %s" % instance.name)
10853
        _ShutdownInstanceDisks(self, instance)
10854

    
10855
    if not (compat.all(dresults) and fin_resu):
10856
      failures = []
10857
      if not fin_resu:
10858
        failures.append("export finalization")
10859
      if not compat.all(dresults):
10860
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10861
                               if not dsk)
10862
        failures.append("disk export: disk(s) %s" % fdsk)
10863

    
10864
      raise errors.OpExecError("Export failed, errors in %s" %
10865
                               utils.CommaJoin(failures))
10866

    
10867
    # At this point, the export was successful, we can cleanup/finish
10868

    
10869
    # Remove instance if requested
10870
    if self.op.remove_instance:
10871
      feedback_fn("Removing instance %s" % instance.name)
10872
      _RemoveInstance(self, feedback_fn, instance,
10873
                      self.op.ignore_remove_failures)
10874

    
10875
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10876
      self._CleanupExports(feedback_fn)
10877

    
10878
    return fin_resu, dresults
10879

    
10880

    
10881
class LUBackupRemove(NoHooksLU):
10882
  """Remove exports related to the named instance.
10883

10884
  """
10885
  REQ_BGL = False
10886

    
10887
  def ExpandNames(self):
10888
    self.needed_locks = {}
10889
    # We need all nodes to be locked in order for RemoveExport to work, but we
10890
    # don't need to lock the instance itself, as nothing will happen to it (and
10891
    # we can remove exports also for a removed instance)
10892
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10893

    
10894
  def Exec(self, feedback_fn):
10895
    """Remove any export.
10896

10897
    """
10898
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10899
    # If the instance was not found we'll try with the name that was passed in.
10900
    # This will only work if it was an FQDN, though.
10901
    fqdn_warn = False
10902
    if not instance_name:
10903
      fqdn_warn = True
10904
      instance_name = self.op.instance_name
10905

    
10906
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
10907
    exportlist = self.rpc.call_export_list(locked_nodes)
10908
    found = False
10909
    for node in exportlist:
10910
      msg = exportlist[node].fail_msg
10911
      if msg:
10912
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10913
        continue
10914
      if instance_name in exportlist[node].payload:
10915
        found = True
10916
        result = self.rpc.call_export_remove(node, instance_name)
10917
        msg = result.fail_msg
10918
        if msg:
10919
          logging.error("Could not remove export for instance %s"
10920
                        " on node %s: %s", instance_name, node, msg)
10921

    
10922
    if fqdn_warn and not found:
10923
      feedback_fn("Export not found. If trying to remove an export belonging"
10924
                  " to a deleted instance please use its Fully Qualified"
10925
                  " Domain Name.")
10926

    
10927

    
10928
class LUGroupAdd(LogicalUnit):
10929
  """Logical unit for creating node groups.
10930

10931
  """
10932
  HPATH = "group-add"
10933
  HTYPE = constants.HTYPE_GROUP
10934
  REQ_BGL = False
10935

    
10936
  def ExpandNames(self):
10937
    # We need the new group's UUID here so that we can create and acquire the
10938
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10939
    # that it should not check whether the UUID exists in the configuration.
10940
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10941
    self.needed_locks = {}
10942
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10943

    
10944
  def CheckPrereq(self):
10945
    """Check prerequisites.
10946

10947
    This checks that the given group name is not an existing node group
10948
    already.
10949

10950
    """
10951
    try:
10952
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10953
    except errors.OpPrereqError:
10954
      pass
10955
    else:
10956
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10957
                                 " node group (UUID: %s)" %
10958
                                 (self.op.group_name, existing_uuid),
10959
                                 errors.ECODE_EXISTS)
10960

    
10961
    if self.op.ndparams:
10962
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10963

    
10964
  def BuildHooksEnv(self):
10965
    """Build hooks env.
10966

10967
    """
10968
    return {
10969
      "GROUP_NAME": self.op.group_name,
10970
      }
10971

    
10972
  def BuildHooksNodes(self):
10973
    """Build hooks nodes.
10974

10975
    """
10976
    mn = self.cfg.GetMasterNode()
10977
    return ([mn], [mn])
10978

    
10979
  def Exec(self, feedback_fn):
10980
    """Add the node group to the cluster.
10981

10982
    """
10983
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10984
                                  uuid=self.group_uuid,
10985
                                  alloc_policy=self.op.alloc_policy,
10986
                                  ndparams=self.op.ndparams)
10987

    
10988
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10989
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10990

    
10991

    
10992
class LUGroupAssignNodes(NoHooksLU):
10993
  """Logical unit for assigning nodes to groups.
10994

10995
  """
10996
  REQ_BGL = False
10997

    
10998
  def ExpandNames(self):
10999
    # These raise errors.OpPrereqError on their own:
11000
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11001
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11002

    
11003
    # We want to lock all the affected nodes and groups. We have readily
11004
    # available the list of nodes, and the *destination* group. To gather the
11005
    # list of "source" groups, we need to fetch node information later on.
11006
    self.needed_locks = {
11007
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11008
      locking.LEVEL_NODE: self.op.nodes,
11009
      }
11010

    
11011
  def DeclareLocks(self, level):
11012
    if level == locking.LEVEL_NODEGROUP:
11013
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11014

    
11015
      # Try to get all affected nodes' groups without having the group or node
11016
      # lock yet. Needs verification later in the code flow.
11017
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11018

    
11019
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11020

    
11021
  def CheckPrereq(self):
11022
    """Check prerequisites.
11023

11024
    """
11025
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11026
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11027
            frozenset(self.op.nodes))
11028

    
11029
    expected_locks = (set([self.group_uuid]) |
11030
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11031
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11032
    if actual_locks != expected_locks:
11033
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11034
                               " current groups are '%s', used to be '%s'" %
11035
                               (utils.CommaJoin(expected_locks),
11036
                                utils.CommaJoin(actual_locks)))
11037

    
11038
    self.node_data = self.cfg.GetAllNodesInfo()
11039
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11040
    instance_data = self.cfg.GetAllInstancesInfo()
11041

    
11042
    if self.group is None:
11043
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11044
                               (self.op.group_name, self.group_uuid))
11045

    
11046
    (new_splits, previous_splits) = \
11047
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11048
                                             for node in self.op.nodes],
11049
                                            self.node_data, instance_data)
11050

    
11051
    if new_splits:
11052
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11053

    
11054
      if not self.op.force:
11055
        raise errors.OpExecError("The following instances get split by this"
11056
                                 " change and --force was not given: %s" %
11057
                                 fmt_new_splits)
11058
      else:
11059
        self.LogWarning("This operation will split the following instances: %s",
11060
                        fmt_new_splits)
11061

    
11062
        if previous_splits:
11063
          self.LogWarning("In addition, these already-split instances continue"
11064
                          " to be split across groups: %s",
11065
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11066

    
11067
  def Exec(self, feedback_fn):
11068
    """Assign nodes to a new group.
11069

11070
    """
11071
    for node in self.op.nodes:
11072
      self.node_data[node].group = self.group_uuid
11073

    
11074
    # FIXME: Depends on side-effects of modifying the result of
11075
    # C{cfg.GetAllNodesInfo}
11076

    
11077
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11078

    
11079
  @staticmethod
11080
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11081
    """Check for split instances after a node assignment.
11082

11083
    This method considers a series of node assignments as an atomic operation,
11084
    and returns information about split instances after applying the set of
11085
    changes.
11086

11087
    In particular, it returns information about newly split instances, and
11088
    instances that were already split, and remain so after the change.
11089

11090
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11091
    considered.
11092

11093
    @type changes: list of (node_name, new_group_uuid) pairs.
11094
    @param changes: list of node assignments to consider.
11095
    @param node_data: a dict with data for all nodes
11096
    @param instance_data: a dict with all instances to consider
11097
    @rtype: a two-tuple
11098
    @return: a list of instances that were previously okay and result split as a
11099
      consequence of this change, and a list of instances that were previously
11100
      split and this change does not fix.
11101

11102
    """
11103
    changed_nodes = dict((node, group) for node, group in changes
11104
                         if node_data[node].group != group)
11105

    
11106
    all_split_instances = set()
11107
    previously_split_instances = set()
11108

    
11109
    def InstanceNodes(instance):
11110
      return [instance.primary_node] + list(instance.secondary_nodes)
11111

    
11112
    for inst in instance_data.values():
11113
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11114
        continue
11115

    
11116
      instance_nodes = InstanceNodes(inst)
11117

    
11118
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11119
        previously_split_instances.add(inst.name)
11120

    
11121
      if len(set(changed_nodes.get(node, node_data[node].group)
11122
                 for node in instance_nodes)) > 1:
11123
        all_split_instances.add(inst.name)
11124

    
11125
    return (list(all_split_instances - previously_split_instances),
11126
            list(previously_split_instances & all_split_instances))
11127

    
11128

    
11129
class _GroupQuery(_QueryBase):
11130
  FIELDS = query.GROUP_FIELDS
11131

    
11132
  def ExpandNames(self, lu):
11133
    lu.needed_locks = {}
11134

    
11135
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11136
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11137

    
11138
    if not self.names:
11139
      self.wanted = [name_to_uuid[name]
11140
                     for name in utils.NiceSort(name_to_uuid.keys())]
11141
    else:
11142
      # Accept names to be either names or UUIDs.
11143
      missing = []
11144
      self.wanted = []
11145
      all_uuid = frozenset(self._all_groups.keys())
11146

    
11147
      for name in self.names:
11148
        if name in all_uuid:
11149
          self.wanted.append(name)
11150
        elif name in name_to_uuid:
11151
          self.wanted.append(name_to_uuid[name])
11152
        else:
11153
          missing.append(name)
11154

    
11155
      if missing:
11156
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11157
                                   utils.CommaJoin(missing),
11158
                                   errors.ECODE_NOENT)
11159

    
11160
  def DeclareLocks(self, lu, level):
11161
    pass
11162

    
11163
  def _GetQueryData(self, lu):
11164
    """Computes the list of node groups and their attributes.
11165

11166
    """
11167
    do_nodes = query.GQ_NODE in self.requested_data
11168
    do_instances = query.GQ_INST in self.requested_data
11169

    
11170
    group_to_nodes = None
11171
    group_to_instances = None
11172

    
11173
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11174
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11175
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11176
    # instance->node. Hence, we will need to process nodes even if we only need
11177
    # instance information.
11178
    if do_nodes or do_instances:
11179
      all_nodes = lu.cfg.GetAllNodesInfo()
11180
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11181
      node_to_group = {}
11182

    
11183
      for node in all_nodes.values():
11184
        if node.group in group_to_nodes:
11185
          group_to_nodes[node.group].append(node.name)
11186
          node_to_group[node.name] = node.group
11187

    
11188
      if do_instances:
11189
        all_instances = lu.cfg.GetAllInstancesInfo()
11190
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11191

    
11192
        for instance in all_instances.values():
11193
          node = instance.primary_node
11194
          if node in node_to_group:
11195
            group_to_instances[node_to_group[node]].append(instance.name)
11196

    
11197
        if not do_nodes:
11198
          # Do not pass on node information if it was not requested.
11199
          group_to_nodes = None
11200

    
11201
    return query.GroupQueryData([self._all_groups[uuid]
11202
                                 for uuid in self.wanted],
11203
                                group_to_nodes, group_to_instances)
11204

    
11205

    
11206
class LUGroupQuery(NoHooksLU):
11207
  """Logical unit for querying node groups.
11208

11209
  """
11210
  REQ_BGL = False
11211

    
11212
  def CheckArguments(self):
11213
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11214
                          self.op.output_fields, False)
11215

    
11216
  def ExpandNames(self):
11217
    self.gq.ExpandNames(self)
11218

    
11219
  def Exec(self, feedback_fn):
11220
    return self.gq.OldStyleQuery(self)
11221

    
11222

    
11223
class LUGroupSetParams(LogicalUnit):
11224
  """Modifies the parameters of a node group.
11225

11226
  """
11227
  HPATH = "group-modify"
11228
  HTYPE = constants.HTYPE_GROUP
11229
  REQ_BGL = False
11230

    
11231
  def CheckArguments(self):
11232
    all_changes = [
11233
      self.op.ndparams,
11234
      self.op.alloc_policy,
11235
      ]
11236

    
11237
    if all_changes.count(None) == len(all_changes):
11238
      raise errors.OpPrereqError("Please pass at least one modification",
11239
                                 errors.ECODE_INVAL)
11240

    
11241
  def ExpandNames(self):
11242
    # This raises errors.OpPrereqError on its own:
11243
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11244

    
11245
    self.needed_locks = {
11246
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11247
      }
11248

    
11249
  def CheckPrereq(self):
11250
    """Check prerequisites.
11251

11252
    """
11253
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11254

    
11255
    if self.group is None:
11256
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11257
                               (self.op.group_name, self.group_uuid))
11258

    
11259
    if self.op.ndparams:
11260
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11261
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11262
      self.new_ndparams = new_ndparams
11263

    
11264
  def BuildHooksEnv(self):
11265
    """Build hooks env.
11266

11267
    """
11268
    return {
11269
      "GROUP_NAME": self.op.group_name,
11270
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11271
      }
11272

    
11273
  def BuildHooksNodes(self):
11274
    """Build hooks nodes.
11275

11276
    """
11277
    mn = self.cfg.GetMasterNode()
11278
    return ([mn], [mn])
11279

    
11280
  def Exec(self, feedback_fn):
11281
    """Modifies the node group.
11282

11283
    """
11284
    result = []
11285

    
11286
    if self.op.ndparams:
11287
      self.group.ndparams = self.new_ndparams
11288
      result.append(("ndparams", str(self.group.ndparams)))
11289

    
11290
    if self.op.alloc_policy:
11291
      self.group.alloc_policy = self.op.alloc_policy
11292

    
11293
    self.cfg.Update(self.group, feedback_fn)
11294
    return result
11295

    
11296

    
11297

    
11298
class LUGroupRemove(LogicalUnit):
11299
  HPATH = "group-remove"
11300
  HTYPE = constants.HTYPE_GROUP
11301
  REQ_BGL = False
11302

    
11303
  def ExpandNames(self):
11304
    # This will raises errors.OpPrereqError on its own:
11305
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11306
    self.needed_locks = {
11307
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11308
      }
11309

    
11310
  def CheckPrereq(self):
11311
    """Check prerequisites.
11312

11313
    This checks that the given group name exists as a node group, that is
11314
    empty (i.e., contains no nodes), and that is not the last group of the
11315
    cluster.
11316

11317
    """
11318
    # Verify that the group is empty.
11319
    group_nodes = [node.name
11320
                   for node in self.cfg.GetAllNodesInfo().values()
11321
                   if node.group == self.group_uuid]
11322

    
11323
    if group_nodes:
11324
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11325
                                 " nodes: %s" %
11326
                                 (self.op.group_name,
11327
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11328
                                 errors.ECODE_STATE)
11329

    
11330
    # Verify the cluster would not be left group-less.
11331
    if len(self.cfg.GetNodeGroupList()) == 1:
11332
      raise errors.OpPrereqError("Group '%s' is the only group,"
11333
                                 " cannot be removed" %
11334
                                 self.op.group_name,
11335
                                 errors.ECODE_STATE)
11336

    
11337
  def BuildHooksEnv(self):
11338
    """Build hooks env.
11339

11340
    """
11341
    return {
11342
      "GROUP_NAME": self.op.group_name,
11343
      }
11344

    
11345
  def BuildHooksNodes(self):
11346
    """Build hooks nodes.
11347

11348
    """
11349
    mn = self.cfg.GetMasterNode()
11350
    return ([mn], [mn])
11351

    
11352
  def Exec(self, feedback_fn):
11353
    """Remove the node group.
11354

11355
    """
11356
    try:
11357
      self.cfg.RemoveNodeGroup(self.group_uuid)
11358
    except errors.ConfigurationError:
11359
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11360
                               (self.op.group_name, self.group_uuid))
11361

    
11362
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11363

    
11364

    
11365
class LUGroupRename(LogicalUnit):
11366
  HPATH = "group-rename"
11367
  HTYPE = constants.HTYPE_GROUP
11368
  REQ_BGL = False
11369

    
11370
  def ExpandNames(self):
11371
    # This raises errors.OpPrereqError on its own:
11372
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11373

    
11374
    self.needed_locks = {
11375
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11376
      }
11377

    
11378
  def CheckPrereq(self):
11379
    """Check prerequisites.
11380

11381
    Ensures requested new name is not yet used.
11382

11383
    """
11384
    try:
11385
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11386
    except errors.OpPrereqError:
11387
      pass
11388
    else:
11389
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11390
                                 " node group (UUID: %s)" %
11391
                                 (self.op.new_name, new_name_uuid),
11392
                                 errors.ECODE_EXISTS)
11393

    
11394
  def BuildHooksEnv(self):
11395
    """Build hooks env.
11396

11397
    """
11398
    return {
11399
      "OLD_NAME": self.op.group_name,
11400
      "NEW_NAME": self.op.new_name,
11401
      }
11402

    
11403
  def BuildHooksNodes(self):
11404
    """Build hooks nodes.
11405

11406
    """
11407
    mn = self.cfg.GetMasterNode()
11408

    
11409
    all_nodes = self.cfg.GetAllNodesInfo()
11410
    all_nodes.pop(mn, None)
11411

    
11412
    run_nodes = [mn]
11413
    run_nodes.extend(node.name for node in all_nodes.values()
11414
                     if node.group == self.group_uuid)
11415

    
11416
    return (run_nodes, run_nodes)
11417

    
11418
  def Exec(self, feedback_fn):
11419
    """Rename the node group.
11420

11421
    """
11422
    group = self.cfg.GetNodeGroup(self.group_uuid)
11423

    
11424
    if group is None:
11425
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11426
                               (self.op.group_name, self.group_uuid))
11427

    
11428
    group.name = self.op.new_name
11429
    self.cfg.Update(group, feedback_fn)
11430

    
11431
    return self.op.new_name
11432

    
11433

    
11434
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11435
  """Generic tags LU.
11436

11437
  This is an abstract class which is the parent of all the other tags LUs.
11438

11439
  """
11440
  def ExpandNames(self):
11441
    self.group_uuid = None
11442
    self.needed_locks = {}
11443
    if self.op.kind == constants.TAG_NODE:
11444
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11445
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11446
    elif self.op.kind == constants.TAG_INSTANCE:
11447
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11448
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11449
    elif self.op.kind == constants.TAG_NODEGROUP:
11450
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
11451

    
11452
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11453
    # not possible to acquire the BGL based on opcode parameters)
11454

    
11455
  def CheckPrereq(self):
11456
    """Check prerequisites.
11457

11458
    """
11459
    if self.op.kind == constants.TAG_CLUSTER:
11460
      self.target = self.cfg.GetClusterInfo()
11461
    elif self.op.kind == constants.TAG_NODE:
11462
      self.target = self.cfg.GetNodeInfo(self.op.name)
11463
    elif self.op.kind == constants.TAG_INSTANCE:
11464
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11465
    elif self.op.kind == constants.TAG_NODEGROUP:
11466
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
11467
    else:
11468
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11469
                                 str(self.op.kind), errors.ECODE_INVAL)
11470

    
11471

    
11472
class LUTagsGet(TagsLU):
11473
  """Returns the tags of a given object.
11474

11475
  """
11476
  REQ_BGL = False
11477

    
11478
  def ExpandNames(self):
11479
    TagsLU.ExpandNames(self)
11480

    
11481
    # Share locks as this is only a read operation
11482
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11483

    
11484
  def Exec(self, feedback_fn):
11485
    """Returns the tag list.
11486

11487
    """
11488
    return list(self.target.GetTags())
11489

    
11490

    
11491
class LUTagsSearch(NoHooksLU):
11492
  """Searches the tags for a given pattern.
11493

11494
  """
11495
  REQ_BGL = False
11496

    
11497
  def ExpandNames(self):
11498
    self.needed_locks = {}
11499

    
11500
  def CheckPrereq(self):
11501
    """Check prerequisites.
11502

11503
    This checks the pattern passed for validity by compiling it.
11504

11505
    """
11506
    try:
11507
      self.re = re.compile(self.op.pattern)
11508
    except re.error, err:
11509
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11510
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11511

    
11512
  def Exec(self, feedback_fn):
11513
    """Returns the tag list.
11514

11515
    """
11516
    cfg = self.cfg
11517
    tgts = [("/cluster", cfg.GetClusterInfo())]
11518
    ilist = cfg.GetAllInstancesInfo().values()
11519
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11520
    nlist = cfg.GetAllNodesInfo().values()
11521
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11522
    tgts.extend(("/nodegroup/%s" % n.name, n)
11523
                for n in cfg.GetAllNodeGroupsInfo().values())
11524
    results = []
11525
    for path, target in tgts:
11526
      for tag in target.GetTags():
11527
        if self.re.search(tag):
11528
          results.append((path, tag))
11529
    return results
11530

    
11531

    
11532
class LUTagsSet(TagsLU):
11533
  """Sets a tag on a given object.
11534

11535
  """
11536
  REQ_BGL = False
11537

    
11538
  def CheckPrereq(self):
11539
    """Check prerequisites.
11540

11541
    This checks the type and length of the tag name and value.
11542

11543
    """
11544
    TagsLU.CheckPrereq(self)
11545
    for tag in self.op.tags:
11546
      objects.TaggableObject.ValidateTag(tag)
11547

    
11548
  def Exec(self, feedback_fn):
11549
    """Sets the tag.
11550

11551
    """
11552
    try:
11553
      for tag in self.op.tags:
11554
        self.target.AddTag(tag)
11555
    except errors.TagError, err:
11556
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11557
    self.cfg.Update(self.target, feedback_fn)
11558

    
11559

    
11560
class LUTagsDel(TagsLU):
11561
  """Delete a list of tags from a given object.
11562

11563
  """
11564
  REQ_BGL = False
11565

    
11566
  def CheckPrereq(self):
11567
    """Check prerequisites.
11568

11569
    This checks that we have the given tag.
11570

11571
    """
11572
    TagsLU.CheckPrereq(self)
11573
    for tag in self.op.tags:
11574
      objects.TaggableObject.ValidateTag(tag)
11575
    del_tags = frozenset(self.op.tags)
11576
    cur_tags = self.target.GetTags()
11577

    
11578
    diff_tags = del_tags - cur_tags
11579
    if diff_tags:
11580
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11581
      raise errors.OpPrereqError("Tag(s) %s not found" %
11582
                                 (utils.CommaJoin(diff_names), ),
11583
                                 errors.ECODE_NOENT)
11584

    
11585
  def Exec(self, feedback_fn):
11586
    """Remove the tag from the object.
11587

11588
    """
11589
    for tag in self.op.tags:
11590
      self.target.RemoveTag(tag)
11591
    self.cfg.Update(self.target, feedback_fn)
11592

    
11593

    
11594
class LUTestDelay(NoHooksLU):
11595
  """Sleep for a specified amount of time.
11596

11597
  This LU sleeps on the master and/or nodes for a specified amount of
11598
  time.
11599

11600
  """
11601
  REQ_BGL = False
11602

    
11603
  def ExpandNames(self):
11604
    """Expand names and set required locks.
11605

11606
    This expands the node list, if any.
11607

11608
    """
11609
    self.needed_locks = {}
11610
    if self.op.on_nodes:
11611
      # _GetWantedNodes can be used here, but is not always appropriate to use
11612
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11613
      # more information.
11614
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11615
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11616

    
11617
  def _TestDelay(self):
11618
    """Do the actual sleep.
11619

11620
    """
11621
    if self.op.on_master:
11622
      if not utils.TestDelay(self.op.duration):
11623
        raise errors.OpExecError("Error during master delay test")
11624
    if self.op.on_nodes:
11625
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11626
      for node, node_result in result.items():
11627
        node_result.Raise("Failure during rpc call to node %s" % node)
11628

    
11629
  def Exec(self, feedback_fn):
11630
    """Execute the test delay opcode, with the wanted repetitions.
11631

11632
    """
11633
    if self.op.repeat == 0:
11634
      self._TestDelay()
11635
    else:
11636
      top_value = self.op.repeat - 1
11637
      for i in range(self.op.repeat):
11638
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11639
        self._TestDelay()
11640

    
11641

    
11642
class LUTestJqueue(NoHooksLU):
11643
  """Utility LU to test some aspects of the job queue.
11644

11645
  """
11646
  REQ_BGL = False
11647

    
11648
  # Must be lower than default timeout for WaitForJobChange to see whether it
11649
  # notices changed jobs
11650
  _CLIENT_CONNECT_TIMEOUT = 20.0
11651
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11652

    
11653
  @classmethod
11654
  def _NotifyUsingSocket(cls, cb, errcls):
11655
    """Opens a Unix socket and waits for another program to connect.
11656

11657
    @type cb: callable
11658
    @param cb: Callback to send socket name to client
11659
    @type errcls: class
11660
    @param errcls: Exception class to use for errors
11661

11662
    """
11663
    # Using a temporary directory as there's no easy way to create temporary
11664
    # sockets without writing a custom loop around tempfile.mktemp and
11665
    # socket.bind
11666
    tmpdir = tempfile.mkdtemp()
11667
    try:
11668
      tmpsock = utils.PathJoin(tmpdir, "sock")
11669

    
11670
      logging.debug("Creating temporary socket at %s", tmpsock)
11671
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11672
      try:
11673
        sock.bind(tmpsock)
11674
        sock.listen(1)
11675

    
11676
        # Send details to client
11677
        cb(tmpsock)
11678

    
11679
        # Wait for client to connect before continuing
11680
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11681
        try:
11682
          (conn, _) = sock.accept()
11683
        except socket.error, err:
11684
          raise errcls("Client didn't connect in time (%s)" % err)
11685
      finally:
11686
        sock.close()
11687
    finally:
11688
      # Remove as soon as client is connected
11689
      shutil.rmtree(tmpdir)
11690

    
11691
    # Wait for client to close
11692
    try:
11693
      try:
11694
        # pylint: disable-msg=E1101
11695
        # Instance of '_socketobject' has no ... member
11696
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11697
        conn.recv(1)
11698
      except socket.error, err:
11699
        raise errcls("Client failed to confirm notification (%s)" % err)
11700
    finally:
11701
      conn.close()
11702

    
11703
  def _SendNotification(self, test, arg, sockname):
11704
    """Sends a notification to the client.
11705

11706
    @type test: string
11707
    @param test: Test name
11708
    @param arg: Test argument (depends on test)
11709
    @type sockname: string
11710
    @param sockname: Socket path
11711

11712
    """
11713
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11714

    
11715
  def _Notify(self, prereq, test, arg):
11716
    """Notifies the client of a test.
11717

11718
    @type prereq: bool
11719
    @param prereq: Whether this is a prereq-phase test
11720
    @type test: string
11721
    @param test: Test name
11722
    @param arg: Test argument (depends on test)
11723

11724
    """
11725
    if prereq:
11726
      errcls = errors.OpPrereqError
11727
    else:
11728
      errcls = errors.OpExecError
11729

    
11730
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11731
                                                  test, arg),
11732
                                   errcls)
11733

    
11734
  def CheckArguments(self):
11735
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11736
    self.expandnames_calls = 0
11737

    
11738
  def ExpandNames(self):
11739
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11740
    if checkargs_calls < 1:
11741
      raise errors.ProgrammerError("CheckArguments was not called")
11742

    
11743
    self.expandnames_calls += 1
11744

    
11745
    if self.op.notify_waitlock:
11746
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11747

    
11748
    self.LogInfo("Expanding names")
11749

    
11750
    # Get lock on master node (just to get a lock, not for a particular reason)
11751
    self.needed_locks = {
11752
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11753
      }
11754

    
11755
  def Exec(self, feedback_fn):
11756
    if self.expandnames_calls < 1:
11757
      raise errors.ProgrammerError("ExpandNames was not called")
11758

    
11759
    if self.op.notify_exec:
11760
      self._Notify(False, constants.JQT_EXEC, None)
11761

    
11762
    self.LogInfo("Executing")
11763

    
11764
    if self.op.log_messages:
11765
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11766
      for idx, msg in enumerate(self.op.log_messages):
11767
        self.LogInfo("Sending log message %s", idx + 1)
11768
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11769
        # Report how many test messages have been sent
11770
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11771

    
11772
    if self.op.fail:
11773
      raise errors.OpExecError("Opcode failure was requested")
11774

    
11775
    return True
11776

    
11777

    
11778
class IAllocator(object):
11779
  """IAllocator framework.
11780

11781
  An IAllocator instance has three sets of attributes:
11782
    - cfg that is needed to query the cluster
11783
    - input data (all members of the _KEYS class attribute are required)
11784
    - four buffer attributes (in|out_data|text), that represent the
11785
      input (to the external script) in text and data structure format,
11786
      and the output from it, again in two formats
11787
    - the result variables from the script (success, info, nodes) for
11788
      easy usage
11789

11790
  """
11791
  # pylint: disable-msg=R0902
11792
  # lots of instance attributes
11793

    
11794
  def __init__(self, cfg, rpc, mode, **kwargs):
11795
    self.cfg = cfg
11796
    self.rpc = rpc
11797
    # init buffer variables
11798
    self.in_text = self.out_text = self.in_data = self.out_data = None
11799
    # init all input fields so that pylint is happy
11800
    self.mode = mode
11801
    self.mem_size = self.disks = self.disk_template = None
11802
    self.os = self.tags = self.nics = self.vcpus = None
11803
    self.hypervisor = None
11804
    self.relocate_from = None
11805
    self.name = None
11806
    self.evac_nodes = None
11807
    self.instances = None
11808
    self.reloc_mode = None
11809
    self.target_groups = None
11810
    # computed fields
11811
    self.required_nodes = None
11812
    # init result fields
11813
    self.success = self.info = self.result = None
11814

    
11815
    try:
11816
      (fn, keyset, self._result_check) = self._MODE_DATA[self.mode]
11817
    except KeyError:
11818
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11819
                                   " IAllocator" % self.mode)
11820

    
11821
    for key in kwargs:
11822
      if key not in keyset:
11823
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11824
                                     " IAllocator" % key)
11825
      setattr(self, key, kwargs[key])
11826

    
11827
    for key in keyset:
11828
      if key not in kwargs:
11829
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11830
                                     " IAllocator" % key)
11831
    self._BuildInputData(compat.partial(fn, self))
11832

    
11833
  def _ComputeClusterData(self):
11834
    """Compute the generic allocator input data.
11835

11836
    This is the data that is independent of the actual operation.
11837

11838
    """
11839
    cfg = self.cfg
11840
    cluster_info = cfg.GetClusterInfo()
11841
    # cluster data
11842
    data = {
11843
      "version": constants.IALLOCATOR_VERSION,
11844
      "cluster_name": cfg.GetClusterName(),
11845
      "cluster_tags": list(cluster_info.GetTags()),
11846
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11847
      # we don't have job IDs
11848
      }
11849
    ninfo = cfg.GetAllNodesInfo()
11850
    iinfo = cfg.GetAllInstancesInfo().values()
11851
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11852

    
11853
    # node data
11854
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11855

    
11856
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11857
      hypervisor_name = self.hypervisor
11858
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11859
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11860
    elif self.mode in (constants.IALLOCATOR_MODE_MEVAC,
11861
                       constants.IALLOCATOR_MODE_MRELOC):
11862
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11863

    
11864
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11865
                                        hypervisor_name)
11866
    node_iinfo = \
11867
      self.rpc.call_all_instances_info(node_list,
11868
                                       cluster_info.enabled_hypervisors)
11869

    
11870
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11871

    
11872
    config_ndata = self._ComputeBasicNodeData(ninfo)
11873
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
11874
                                                 i_list, config_ndata)
11875
    assert len(data["nodes"]) == len(ninfo), \
11876
        "Incomplete node data computed"
11877

    
11878
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
11879

    
11880
    self.in_data = data
11881

    
11882
  @staticmethod
11883
  def _ComputeNodeGroupData(cfg):
11884
    """Compute node groups data.
11885

11886
    """
11887
    ng = dict((guuid, {
11888
      "name": gdata.name,
11889
      "alloc_policy": gdata.alloc_policy,
11890
      })
11891
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
11892

    
11893
    return ng
11894

    
11895
  @staticmethod
11896
  def _ComputeBasicNodeData(node_cfg):
11897
    """Compute global node data.
11898

11899
    @rtype: dict
11900
    @returns: a dict of name: (node dict, node config)
11901

11902
    """
11903
    # fill in static (config-based) values
11904
    node_results = dict((ninfo.name, {
11905
      "tags": list(ninfo.GetTags()),
11906
      "primary_ip": ninfo.primary_ip,
11907
      "secondary_ip": ninfo.secondary_ip,
11908
      "offline": ninfo.offline,
11909
      "drained": ninfo.drained,
11910
      "master_candidate": ninfo.master_candidate,
11911
      "group": ninfo.group,
11912
      "master_capable": ninfo.master_capable,
11913
      "vm_capable": ninfo.vm_capable,
11914
      })
11915
      for ninfo in node_cfg.values())
11916

    
11917
    return node_results
11918

    
11919
  @staticmethod
11920
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
11921
                              node_results):
11922
    """Compute global node data.
11923

11924
    @param node_results: the basic node structures as filled from the config
11925

11926
    """
11927
    # make a copy of the current dict
11928
    node_results = dict(node_results)
11929
    for nname, nresult in node_data.items():
11930
      assert nname in node_results, "Missing basic data for node %s" % nname
11931
      ninfo = node_cfg[nname]
11932

    
11933
      if not (ninfo.offline or ninfo.drained):
11934
        nresult.Raise("Can't get data for node %s" % nname)
11935
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11936
                                nname)
11937
        remote_info = nresult.payload
11938

    
11939
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11940
                     'vg_size', 'vg_free', 'cpu_total']:
11941
          if attr not in remote_info:
11942
            raise errors.OpExecError("Node '%s' didn't return attribute"
11943
                                     " '%s'" % (nname, attr))
11944
          if not isinstance(remote_info[attr], int):
11945
            raise errors.OpExecError("Node '%s' returned invalid value"
11946
                                     " for '%s': %s" %
11947
                                     (nname, attr, remote_info[attr]))
11948
        # compute memory used by primary instances
11949
        i_p_mem = i_p_up_mem = 0
11950
        for iinfo, beinfo in i_list:
11951
          if iinfo.primary_node == nname:
11952
            i_p_mem += beinfo[constants.BE_MEMORY]
11953
            if iinfo.name not in node_iinfo[nname].payload:
11954
              i_used_mem = 0
11955
            else:
11956
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11957
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11958
            remote_info['memory_free'] -= max(0, i_mem_diff)
11959

    
11960
            if iinfo.admin_up:
11961
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11962

    
11963
        # compute memory used by instances
11964
        pnr_dyn = {
11965
          "total_memory": remote_info['memory_total'],
11966
          "reserved_memory": remote_info['memory_dom0'],
11967
          "free_memory": remote_info['memory_free'],
11968
          "total_disk": remote_info['vg_size'],
11969
          "free_disk": remote_info['vg_free'],
11970
          "total_cpus": remote_info['cpu_total'],
11971
          "i_pri_memory": i_p_mem,
11972
          "i_pri_up_memory": i_p_up_mem,
11973
          }
11974
        pnr_dyn.update(node_results[nname])
11975
        node_results[nname] = pnr_dyn
11976

    
11977
    return node_results
11978

    
11979
  @staticmethod
11980
  def _ComputeInstanceData(cluster_info, i_list):
11981
    """Compute global instance data.
11982

11983
    """
11984
    instance_data = {}
11985
    for iinfo, beinfo in i_list:
11986
      nic_data = []
11987
      for nic in iinfo.nics:
11988
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11989
        nic_dict = {
11990
          "mac": nic.mac,
11991
          "ip": nic.ip,
11992
          "mode": filled_params[constants.NIC_MODE],
11993
          "link": filled_params[constants.NIC_LINK],
11994
          }
11995
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11996
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11997
        nic_data.append(nic_dict)
11998
      pir = {
11999
        "tags": list(iinfo.GetTags()),
12000
        "admin_up": iinfo.admin_up,
12001
        "vcpus": beinfo[constants.BE_VCPUS],
12002
        "memory": beinfo[constants.BE_MEMORY],
12003
        "os": iinfo.os,
12004
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12005
        "nics": nic_data,
12006
        "disks": [{constants.IDISK_SIZE: dsk.size,
12007
                   constants.IDISK_MODE: dsk.mode}
12008
                  for dsk in iinfo.disks],
12009
        "disk_template": iinfo.disk_template,
12010
        "hypervisor": iinfo.hypervisor,
12011
        }
12012
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12013
                                                 pir["disks"])
12014
      instance_data[iinfo.name] = pir
12015

    
12016
    return instance_data
12017

    
12018
  def _AddNewInstance(self):
12019
    """Add new instance data to allocator structure.
12020

12021
    This in combination with _AllocatorGetClusterData will create the
12022
    correct structure needed as input for the allocator.
12023

12024
    The checks for the completeness of the opcode must have already been
12025
    done.
12026

12027
    """
12028
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12029

    
12030
    if self.disk_template in constants.DTS_INT_MIRROR:
12031
      self.required_nodes = 2
12032
    else:
12033
      self.required_nodes = 1
12034

    
12035
    request = {
12036
      "name": self.name,
12037
      "disk_template": self.disk_template,
12038
      "tags": self.tags,
12039
      "os": self.os,
12040
      "vcpus": self.vcpus,
12041
      "memory": self.mem_size,
12042
      "disks": self.disks,
12043
      "disk_space_total": disk_space,
12044
      "nics": self.nics,
12045
      "required_nodes": self.required_nodes,
12046
      }
12047

    
12048
    return request
12049

    
12050
  def _AddRelocateInstance(self):
12051
    """Add relocate instance data to allocator structure.
12052

12053
    This in combination with _IAllocatorGetClusterData will create the
12054
    correct structure needed as input for the allocator.
12055

12056
    The checks for the completeness of the opcode must have already been
12057
    done.
12058

12059
    """
12060
    instance = self.cfg.GetInstanceInfo(self.name)
12061
    if instance is None:
12062
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12063
                                   " IAllocator" % self.name)
12064

    
12065
    if instance.disk_template not in constants.DTS_MIRRORED:
12066
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12067
                                 errors.ECODE_INVAL)
12068

    
12069
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12070
        len(instance.secondary_nodes) != 1:
12071
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12072
                                 errors.ECODE_STATE)
12073

    
12074
    self.required_nodes = 1
12075
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12076
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12077

    
12078
    request = {
12079
      "name": self.name,
12080
      "disk_space_total": disk_space,
12081
      "required_nodes": self.required_nodes,
12082
      "relocate_from": self.relocate_from,
12083
      }
12084
    return request
12085

    
12086
  def _AddEvacuateNodes(self):
12087
    """Add evacuate nodes data to allocator structure.
12088

12089
    """
12090
    request = {
12091
      "evac_nodes": self.evac_nodes
12092
      }
12093
    return request
12094

    
12095
  def _AddMultiRelocate(self):
12096
    """Get data for multi-relocate requests.
12097

12098
    """
12099
    return {
12100
      "instances": self.instances,
12101
      "reloc_mode": self.reloc_mode,
12102
      "target_groups": self.target_groups,
12103
      }
12104

    
12105
  def _BuildInputData(self, fn):
12106
    """Build input data structures.
12107

12108
    """
12109
    self._ComputeClusterData()
12110

    
12111
    request = fn()
12112
    request["type"] = self.mode
12113
    self.in_data["request"] = request
12114

    
12115
    self.in_text = serializer.Dump(self.in_data)
12116

    
12117
  _MODE_DATA = {
12118
    constants.IALLOCATOR_MODE_ALLOC:
12119
      (_AddNewInstance,
12120
       ["name", "mem_size", "disks", "disk_template", "os", "tags", "nics",
12121
        "vcpus", "hypervisor"], ht.TList),
12122
    constants.IALLOCATOR_MODE_RELOC:
12123
      (_AddRelocateInstance, ["name", "relocate_from"], ht.TList),
12124
    constants.IALLOCATOR_MODE_MEVAC:
12125
      (_AddEvacuateNodes, ["evac_nodes"],
12126
       ht.TListOf(ht.TAnd(ht.TIsLength(2),
12127
                          ht.TListOf(ht.TString)))),
12128
    constants.IALLOCATOR_MODE_MRELOC:
12129
      (_AddMultiRelocate, ["instances", "reloc_mode", "target_groups"],
12130
       ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12131
         # pylint: disable-msg=E1101
12132
         # Class '...' has no 'OP_ID' member
12133
         "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12134
                              opcodes.OpInstanceMigrate.OP_ID,
12135
                              opcodes.OpInstanceReplaceDisks.OP_ID])
12136
         })))),
12137
    }
12138

    
12139
  def Run(self, name, validate=True, call_fn=None):
12140
    """Run an instance allocator and return the results.
12141

12142
    """
12143
    if call_fn is None:
12144
      call_fn = self.rpc.call_iallocator_runner
12145

    
12146
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12147
    result.Raise("Failure while running the iallocator script")
12148

    
12149
    self.out_text = result.payload
12150
    if validate:
12151
      self._ValidateResult()
12152

    
12153
  def _ValidateResult(self):
12154
    """Process the allocator results.
12155

12156
    This will process and if successful save the result in
12157
    self.out_data and the other parameters.
12158

12159
    """
12160
    try:
12161
      rdict = serializer.Load(self.out_text)
12162
    except Exception, err:
12163
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12164

    
12165
    if not isinstance(rdict, dict):
12166
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12167

    
12168
    # TODO: remove backwards compatiblity in later versions
12169
    if "nodes" in rdict and "result" not in rdict:
12170
      rdict["result"] = rdict["nodes"]
12171
      del rdict["nodes"]
12172

    
12173
    for key in "success", "info", "result":
12174
      if key not in rdict:
12175
        raise errors.OpExecError("Can't parse iallocator results:"
12176
                                 " missing key '%s'" % key)
12177
      setattr(self, key, rdict[key])
12178

    
12179
    if not self._result_check(self.result):
12180
      raise errors.OpExecError("Iallocator returned invalid result,"
12181
                               " expected %s, got %s" %
12182
                               (self._result_check, self.result),
12183
                               errors.ECODE_INVAL)
12184

    
12185
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12186
                     constants.IALLOCATOR_MODE_MEVAC):
12187
      node2group = dict((name, ndata["group"])
12188
                        for (name, ndata) in self.in_data["nodes"].items())
12189

    
12190
      fn = compat.partial(self._NodesToGroups, node2group,
12191
                          self.in_data["nodegroups"])
12192

    
12193
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12194
        assert self.relocate_from is not None
12195
        assert self.required_nodes == 1
12196

    
12197
        request_groups = fn(self.relocate_from)
12198
        result_groups = fn(rdict["result"])
12199

    
12200
        if result_groups != request_groups:
12201
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12202
                                   " differ from original groups (%s)" %
12203
                                   (utils.CommaJoin(result_groups),
12204
                                    utils.CommaJoin(request_groups)))
12205
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12206
        request_groups = fn(self.evac_nodes)
12207
        for (instance_name, secnode) in self.result:
12208
          result_groups = fn([secnode])
12209
          if result_groups != request_groups:
12210
            raise errors.OpExecError("Iallocator returned new secondary node"
12211
                                     " '%s' (group '%s') for instance '%s'"
12212
                                     " which is not in original group '%s'" %
12213
                                     (secnode, utils.CommaJoin(result_groups),
12214
                                      instance_name,
12215
                                      utils.CommaJoin(request_groups)))
12216
      else:
12217
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12218

    
12219
    self.out_data = rdict
12220

    
12221
  @staticmethod
12222
  def _NodesToGroups(node2group, groups, nodes):
12223
    """Returns a list of unique group names for a list of nodes.
12224

12225
    @type node2group: dict
12226
    @param node2group: Map from node name to group UUID
12227
    @type groups: dict
12228
    @param groups: Group information
12229
    @type nodes: list
12230
    @param nodes: Node names
12231

12232
    """
12233
    result = set()
12234

    
12235
    for node in nodes:
12236
      try:
12237
        group_uuid = node2group[node]
12238
      except KeyError:
12239
        # Ignore unknown node
12240
        pass
12241
      else:
12242
        try:
12243
          group = groups[group_uuid]
12244
        except KeyError:
12245
          # Can't find group, let's use UUID
12246
          group_name = group_uuid
12247
        else:
12248
          group_name = group["name"]
12249

    
12250
        result.add(group_name)
12251

    
12252
    return sorted(result)
12253

    
12254

    
12255
class LUTestAllocator(NoHooksLU):
12256
  """Run allocator tests.
12257

12258
  This LU runs the allocator tests
12259

12260
  """
12261
  def CheckPrereq(self):
12262
    """Check prerequisites.
12263

12264
    This checks the opcode parameters depending on the director and mode test.
12265

12266
    """
12267
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12268
      for attr in ["mem_size", "disks", "disk_template",
12269
                   "os", "tags", "nics", "vcpus"]:
12270
        if not hasattr(self.op, attr):
12271
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12272
                                     attr, errors.ECODE_INVAL)
12273
      iname = self.cfg.ExpandInstanceName(self.op.name)
12274
      if iname is not None:
12275
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12276
                                   iname, errors.ECODE_EXISTS)
12277
      if not isinstance(self.op.nics, list):
12278
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12279
                                   errors.ECODE_INVAL)
12280
      if not isinstance(self.op.disks, list):
12281
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12282
                                   errors.ECODE_INVAL)
12283
      for row in self.op.disks:
12284
        if (not isinstance(row, dict) or
12285
            "size" not in row or
12286
            not isinstance(row["size"], int) or
12287
            "mode" not in row or
12288
            row["mode"] not in ['r', 'w']):
12289
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12290
                                     " parameter", errors.ECODE_INVAL)
12291
      if self.op.hypervisor is None:
12292
        self.op.hypervisor = self.cfg.GetHypervisorType()
12293
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12294
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12295
      self.op.name = fname
12296
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12297
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12298
      if not hasattr(self.op, "evac_nodes"):
12299
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12300
                                   " opcode input", errors.ECODE_INVAL)
12301
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12302
      if self.op.instances:
12303
        self.op.instances = _GetWantedInstances(self, self.op.instances)
12304
      else:
12305
        raise errors.OpPrereqError("Missing instances to relocate",
12306
                                   errors.ECODE_INVAL)
12307
    else:
12308
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12309
                                 self.op.mode, errors.ECODE_INVAL)
12310

    
12311
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12312
      if self.op.allocator is None:
12313
        raise errors.OpPrereqError("Missing allocator name",
12314
                                   errors.ECODE_INVAL)
12315
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12316
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12317
                                 self.op.direction, errors.ECODE_INVAL)
12318

    
12319
  def Exec(self, feedback_fn):
12320
    """Run the allocator test.
12321

12322
    """
12323
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12324
      ial = IAllocator(self.cfg, self.rpc,
12325
                       mode=self.op.mode,
12326
                       name=self.op.name,
12327
                       mem_size=self.op.mem_size,
12328
                       disks=self.op.disks,
12329
                       disk_template=self.op.disk_template,
12330
                       os=self.op.os,
12331
                       tags=self.op.tags,
12332
                       nics=self.op.nics,
12333
                       vcpus=self.op.vcpus,
12334
                       hypervisor=self.op.hypervisor,
12335
                       )
12336
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12337
      ial = IAllocator(self.cfg, self.rpc,
12338
                       mode=self.op.mode,
12339
                       name=self.op.name,
12340
                       relocate_from=list(self.relocate_from),
12341
                       )
12342
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12343
      ial = IAllocator(self.cfg, self.rpc,
12344
                       mode=self.op.mode,
12345
                       evac_nodes=self.op.evac_nodes)
12346
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12347
      ial = IAllocator(self.cfg, self.rpc,
12348
                       mode=self.op.mode,
12349
                       instances=self.op.instances,
12350
                       reloc_mode=self.op.reloc_mode,
12351
                       target_groups=self.op.target_groups)
12352
    else:
12353
      raise errors.ProgrammerError("Uncatched mode %s in"
12354
                                   " LUTestAllocator.Exec", self.op.mode)
12355

    
12356
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
12357
      result = ial.in_text
12358
    else:
12359
      ial.Run(self.op.allocator, validate=False)
12360
      result = ial.out_text
12361
    return result
12362

    
12363

    
12364
#: Query type implementations
12365
_QUERY_IMPL = {
12366
  constants.QR_INSTANCE: _InstanceQuery,
12367
  constants.QR_NODE: _NodeQuery,
12368
  constants.QR_GROUP: _GroupQuery,
12369
  constants.QR_OS: _OsQuery,
12370
  }
12371

    
12372
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
12373

    
12374

    
12375
def _GetQueryImplementation(name):
12376
  """Returns the implemtnation for a query type.
12377

12378
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
12379

12380
  """
12381
  try:
12382
    return _QUERY_IMPL[name]
12383
  except KeyError:
12384
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
12385
                               errors.ECODE_INVAL)