Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ fb44c6db

History | View | Annotate | Download (472.9 kB)

1
#
2
#
3

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

    
21

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

    
24
# pylint: disable=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
import operator
44

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

    
63
import ganeti.masterd.instance # pylint: disable=W0611
64

    
65

    
66
class ResultWithJobs:
67
  """Data container for LU results with jobs.
68

69
  Instances of this class returned from L{LogicalUnit.Exec} will be recognized
70
  by L{mcpu.Processor._ProcessResult}. The latter will then submit the jobs
71
  contained in the C{jobs} attribute and include the job IDs in the opcode
72
  result.
73

74
  """
75
  def __init__(self, jobs, **kwargs):
76
    """Initializes this class.
77

78
    Additional return values can be specified as keyword arguments.
79

80
    @type jobs: list of lists of L{opcode.OpCode}
81
    @param jobs: A list of lists of opcode objects
82

83
    """
84
    self.jobs = jobs
85
    self.other = kwargs
86

    
87

    
88
class LogicalUnit(object):
89
  """Logical Unit base class.
90

91
  Subclasses must follow these rules:
92
    - implement ExpandNames
93
    - implement CheckPrereq (except when tasklets are used)
94
    - implement Exec (except when tasklets are used)
95
    - implement BuildHooksEnv
96
    - implement BuildHooksNodes
97
    - redefine HPATH and HTYPE
98
    - optionally redefine their run requirements:
99
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
100

101
  Note that all commands require root permissions.
102

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

106
  """
107
  HPATH = None
108
  HTYPE = None
109
  REQ_BGL = True
110

    
111
  def __init__(self, processor, op, context, rpc):
112
    """Constructor for LogicalUnit.
113

114
    This needs to be overridden in derived classes in order to check op
115
    validity.
116

117
    """
118
    self.proc = processor
119
    self.op = op
120
    self.cfg = context.cfg
121
    self.glm = context.glm
122
    # readability alias
123
    self.owned_locks = context.glm.list_owned
124
    self.context = context
125
    self.rpc = rpc
126
    # Dicts used to declare locking needs to mcpu
127
    self.needed_locks = None
128
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
129
    self.add_locks = {}
130
    self.remove_locks = {}
131
    # Used to force good behavior when calling helper functions
132
    self.recalculate_locks = {}
133
    # logging
134
    self.Log = processor.Log # pylint: disable=C0103
135
    self.LogWarning = processor.LogWarning # pylint: disable=C0103
136
    self.LogInfo = processor.LogInfo # pylint: disable=C0103
137
    self.LogStep = processor.LogStep # pylint: disable=C0103
138
    # support for dry-run
139
    self.dry_run_result = None
140
    # support for generic debug attribute
141
    if (not hasattr(self.op, "debug_level") or
142
        not isinstance(self.op.debug_level, int)):
143
      self.op.debug_level = 0
144

    
145
    # Tasklets
146
    self.tasklets = None
147

    
148
    # Validate opcode parameters and set defaults
149
    self.op.Validate(True)
150

    
151
    self.CheckArguments()
152

    
153
  def CheckArguments(self):
154
    """Check syntactic validity for the opcode arguments.
155

156
    This method is for doing a simple syntactic check and ensure
157
    validity of opcode parameters, without any cluster-related
158
    checks. While the same can be accomplished in ExpandNames and/or
159
    CheckPrereq, doing these separate is better because:
160

161
      - ExpandNames is left as as purely a lock-related function
162
      - CheckPrereq is run after we have acquired locks (and possible
163
        waited for them)
164

165
    The function is allowed to change the self.op attribute so that
166
    later methods can no longer worry about missing parameters.
167

168
    """
169
    pass
170

    
171
  def ExpandNames(self):
172
    """Expand names for this LU.
173

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

179
    LUs which implement this method must also populate the self.needed_locks
180
    member, as a dict with lock levels as keys, and a list of needed lock names
181
    as values. Rules:
182

183
      - use an empty dict if you don't need any lock
184
      - if you don't need any lock at a particular level omit that level
185
      - don't put anything for the BGL level
186
      - if you want all locks at a level use locking.ALL_SET as a value
187

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

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

196
    Examples::
197

198
      # Acquire all nodes and one instance
199
      self.needed_locks = {
200
        locking.LEVEL_NODE: locking.ALL_SET,
201
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
202
      }
203
      # Acquire just two nodes
204
      self.needed_locks = {
205
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
206
      }
207
      # Acquire no locks
208
      self.needed_locks = {} # No, you can't leave it to the default value None
209

210
    """
211
    # The implementation of this method is mandatory only if the new LU is
212
    # concurrent, so that old LUs don't need to be changed all at the same
213
    # time.
214
    if self.REQ_BGL:
215
      self.needed_locks = {} # Exclusive LUs don't need locks.
216
    else:
217
      raise NotImplementedError
218

    
219
  def DeclareLocks(self, level):
220
    """Declare LU locking needs for a level
221

222
    While most LUs can just declare their locking needs at ExpandNames time,
223
    sometimes there's the need to calculate some locks after having acquired
224
    the ones before. This function is called just before acquiring locks at a
225
    particular level, but after acquiring the ones at lower levels, and permits
226
    such calculations. It can be used to modify self.needed_locks, and by
227
    default it does nothing.
228

229
    This function is only called if you have something already set in
230
    self.needed_locks for the level.
231

232
    @param level: Locking level which is going to be locked
233
    @type level: member of ganeti.locking.LEVELS
234

235
    """
236

    
237
  def CheckPrereq(self):
238
    """Check prerequisites for this LU.
239

240
    This method should check that the prerequisites for the execution
241
    of this LU are fulfilled. It can do internode communication, but
242
    it should be idempotent - no cluster or system changes are
243
    allowed.
244

245
    The method should raise errors.OpPrereqError in case something is
246
    not fulfilled. Its return value is ignored.
247

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

251
    """
252
    if self.tasklets is not None:
253
      for (idx, tl) in enumerate(self.tasklets):
254
        logging.debug("Checking prerequisites for tasklet %s/%s",
255
                      idx + 1, len(self.tasklets))
256
        tl.CheckPrereq()
257
    else:
258
      pass
259

    
260
  def Exec(self, feedback_fn):
261
    """Execute the LU.
262

263
    This method should implement the actual work. It should raise
264
    errors.OpExecError for failures that are somewhat dealt with in
265
    code, or expected.
266

267
    """
268
    if self.tasklets is not None:
269
      for (idx, tl) in enumerate(self.tasklets):
270
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
271
        tl.Exec(feedback_fn)
272
    else:
273
      raise NotImplementedError
274

    
275
  def BuildHooksEnv(self):
276
    """Build hooks environment for this LU.
277

278
    @rtype: dict
279
    @return: Dictionary containing the environment that will be used for
280
      running the hooks for this LU. The keys of the dict must not be prefixed
281
      with "GANETI_"--that'll be added by the hooks runner. The hooks runner
282
      will extend the environment with additional variables. If no environment
283
      should be defined, an empty dictionary should be returned (not C{None}).
284
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
285
      will not be called.
286

287
    """
288
    raise NotImplementedError
289

    
290
  def BuildHooksNodes(self):
291
    """Build list of nodes to run LU's hooks.
292

293
    @rtype: tuple; (list, list)
294
    @return: Tuple containing a list of node names on which the hook
295
      should run before the execution and a list of node names on which the
296
      hook should run after the execution. No nodes should be returned as an
297
      empty list (and not None).
298
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
299
      will not be called.
300

301
    """
302
    raise NotImplementedError
303

    
304
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
305
    """Notify the LU about the results of its hooks.
306

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

313
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
314
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
315
    @param hook_results: the results of the multi-node hooks rpc call
316
    @param feedback_fn: function used send feedback back to the caller
317
    @param lu_result: the previous Exec result this LU had, or None
318
        in the PRE phase
319
    @return: the new Exec result, based on the previous result
320
        and hook results
321

322
    """
323
    # API must be kept, thus we ignore the unused argument and could
324
    # be a function warnings
325
    # pylint: disable=W0613,R0201
326
    return lu_result
327

    
328
  def _ExpandAndLockInstance(self):
329
    """Helper function to expand and lock an instance.
330

331
    Many LUs that work on an instance take its name in self.op.instance_name
332
    and need to expand it and then declare the expanded name for locking. This
333
    function does it, and then updates self.op.instance_name to the expanded
334
    name. It also initializes needed_locks as a dict, if this hasn't been done
335
    before.
336

337
    """
338
    if self.needed_locks is None:
339
      self.needed_locks = {}
340
    else:
341
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
342
        "_ExpandAndLockInstance called with instance-level locks set"
343
    self.op.instance_name = _ExpandInstanceName(self.cfg,
344
                                                self.op.instance_name)
345
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
346

    
347
  def _LockInstancesNodes(self, primary_only=False):
348
    """Helper function to declare instances' nodes for locking.
349

350
    This function should be called after locking one or more instances to lock
351
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
352
    with all primary or secondary nodes for instances already locked and
353
    present in self.needed_locks[locking.LEVEL_INSTANCE].
354

355
    It should be called from DeclareLocks, and for safety only works if
356
    self.recalculate_locks[locking.LEVEL_NODE] is set.
357

358
    In the future it may grow parameters to just lock some instance's nodes, or
359
    to just lock primaries or secondary nodes, if needed.
360

361
    If should be called in DeclareLocks in a way similar to::
362

363
      if level == locking.LEVEL_NODE:
364
        self._LockInstancesNodes()
365

366
    @type primary_only: boolean
367
    @param primary_only: only lock primary nodes of locked instances
368

369
    """
370
    assert locking.LEVEL_NODE in self.recalculate_locks, \
371
      "_LockInstancesNodes helper function called with no nodes to recalculate"
372

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

    
375
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
376
    # future we might want to have different behaviors depending on the value
377
    # of self.recalculate_locks[locking.LEVEL_NODE]
378
    wanted_nodes = []
379
    locked_i = self.owned_locks(locking.LEVEL_INSTANCE)
380
    for _, instance in self.cfg.GetMultiInstanceInfo(locked_i):
381
      wanted_nodes.append(instance.primary_node)
382
      if not primary_only:
383
        wanted_nodes.extend(instance.secondary_nodes)
384

    
385
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
386
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
387
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
388
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
389

    
390
    del self.recalculate_locks[locking.LEVEL_NODE]
391

    
392

    
393
class NoHooksLU(LogicalUnit): # pylint: disable=W0223
394
  """Simple LU which runs no hooks.
395

396
  This LU is intended as a parent for other LogicalUnits which will
397
  run no hooks, in order to reduce duplicate code.
398

399
  """
400
  HPATH = None
401
  HTYPE = None
402

    
403
  def BuildHooksEnv(self):
404
    """Empty BuildHooksEnv for NoHooksLu.
405

406
    This just raises an error.
407

408
    """
409
    raise AssertionError("BuildHooksEnv called for NoHooksLUs")
410

    
411
  def BuildHooksNodes(self):
412
    """Empty BuildHooksNodes for NoHooksLU.
413

414
    """
415
    raise AssertionError("BuildHooksNodes called for NoHooksLU")
416

    
417

    
418
class Tasklet:
419
  """Tasklet base class.
420

421
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
422
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
423
  tasklets know nothing about locks.
424

425
  Subclasses must follow these rules:
426
    - Implement CheckPrereq
427
    - Implement Exec
428

429
  """
430
  def __init__(self, lu):
431
    self.lu = lu
432

    
433
    # Shortcuts
434
    self.cfg = lu.cfg
435
    self.rpc = lu.rpc
436

    
437
  def CheckPrereq(self):
438
    """Check prerequisites for this tasklets.
439

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

444
    The method should raise errors.OpPrereqError in case something is not
445
    fulfilled. Its return value is ignored.
446

447
    This method should also update all parameters to their canonical form if it
448
    hasn't been done before.
449

450
    """
451
    pass
452

    
453
  def Exec(self, feedback_fn):
454
    """Execute the tasklet.
455

456
    This method should implement the actual work. It should raise
457
    errors.OpExecError for failures that are somewhat dealt with in code, or
458
    expected.
459

460
    """
461
    raise NotImplementedError
462

    
463

    
464
class _QueryBase:
465
  """Base for query utility classes.
466

467
  """
468
  #: Attribute holding field definitions
469
  FIELDS = None
470

    
471
  def __init__(self, filter_, fields, use_locking):
472
    """Initializes this class.
473

474
    """
475
    self.use_locking = use_locking
476

    
477
    self.query = query.Query(self.FIELDS, fields, filter_=filter_,
478
                             namefield="name")
479
    self.requested_data = self.query.RequestedData()
480
    self.names = self.query.RequestedNames()
481

    
482
    # Sort only if no names were requested
483
    self.sort_by_name = not self.names
484

    
485
    self.do_locking = None
486
    self.wanted = None
487

    
488
  def _GetNames(self, lu, all_names, lock_level):
489
    """Helper function to determine names asked for in the query.
490

491
    """
492
    if self.do_locking:
493
      names = lu.owned_locks(lock_level)
494
    else:
495
      names = all_names
496

    
497
    if self.wanted == locking.ALL_SET:
498
      assert not self.names
499
      # caller didn't specify names, so ordering is not important
500
      return utils.NiceSort(names)
501

    
502
    # caller specified names and we must keep the same order
503
    assert self.names
504
    assert not self.do_locking or lu.glm.is_owned(lock_level)
505

    
506
    missing = set(self.wanted).difference(names)
507
    if missing:
508
      raise errors.OpExecError("Some items were removed before retrieving"
509
                               " their data: %s" % missing)
510

    
511
    # Return expanded names
512
    return self.wanted
513

    
514
  def ExpandNames(self, lu):
515
    """Expand names for this query.
516

517
    See L{LogicalUnit.ExpandNames}.
518

519
    """
520
    raise NotImplementedError()
521

    
522
  def DeclareLocks(self, lu, level):
523
    """Declare locks for this query.
524

525
    See L{LogicalUnit.DeclareLocks}.
526

527
    """
528
    raise NotImplementedError()
529

    
530
  def _GetQueryData(self, lu):
531
    """Collects all data for this query.
532

533
    @return: Query data object
534

535
    """
536
    raise NotImplementedError()
537

    
538
  def NewStyleQuery(self, lu):
539
    """Collect data and execute query.
540

541
    """
542
    return query.GetQueryResponse(self.query, self._GetQueryData(lu),
543
                                  sort_by_name=self.sort_by_name)
544

    
545
  def OldStyleQuery(self, lu):
546
    """Collect data and execute query.
547

548
    """
549
    return self.query.OldStyleQuery(self._GetQueryData(lu),
550
                                    sort_by_name=self.sort_by_name)
551

    
552

    
553
def _ShareAll():
554
  """Returns a dict declaring all lock levels shared.
555

556
  """
557
  return dict.fromkeys(locking.LEVELS, 1)
558

    
559

    
560
def _CheckInstanceNodeGroups(cfg, instance_name, owned_groups):
561
  """Checks if the owned node groups are still correct for an instance.
562

563
  @type cfg: L{config.ConfigWriter}
564
  @param cfg: The cluster configuration
565
  @type instance_name: string
566
  @param instance_name: Instance name
567
  @type owned_groups: set or frozenset
568
  @param owned_groups: List of currently owned node groups
569

570
  """
571
  inst_groups = cfg.GetInstanceNodeGroups(instance_name)
572

    
573
  if not owned_groups.issuperset(inst_groups):
574
    raise errors.OpPrereqError("Instance %s's node groups changed since"
575
                               " locks were acquired, current groups are"
576
                               " are '%s', owning groups '%s'; retry the"
577
                               " operation" %
578
                               (instance_name,
579
                                utils.CommaJoin(inst_groups),
580
                                utils.CommaJoin(owned_groups)),
581
                               errors.ECODE_STATE)
582

    
583
  return inst_groups
584

    
585

    
586
def _CheckNodeGroupInstances(cfg, group_uuid, owned_instances):
587
  """Checks if the instances in a node group are still correct.
588

589
  @type cfg: L{config.ConfigWriter}
590
  @param cfg: The cluster configuration
591
  @type group_uuid: string
592
  @param group_uuid: Node group UUID
593
  @type owned_instances: set or frozenset
594
  @param owned_instances: List of currently owned instances
595

596
  """
597
  wanted_instances = cfg.GetNodeGroupInstances(group_uuid)
598
  if owned_instances != wanted_instances:
599
    raise errors.OpPrereqError("Instances in node group '%s' changed since"
600
                               " locks were acquired, wanted '%s', have '%s';"
601
                               " retry the operation" %
602
                               (group_uuid,
603
                                utils.CommaJoin(wanted_instances),
604
                                utils.CommaJoin(owned_instances)),
605
                               errors.ECODE_STATE)
606

    
607
  return wanted_instances
608

    
609

    
610
def _SupportsOob(cfg, node):
611
  """Tells if node supports OOB.
612

613
  @type cfg: L{config.ConfigWriter}
614
  @param cfg: The cluster configuration
615
  @type node: L{objects.Node}
616
  @param node: The node
617
  @return: The OOB script if supported or an empty string otherwise
618

619
  """
620
  return cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM]
621

    
622

    
623
def _GetWantedNodes(lu, nodes):
624
  """Returns list of checked and expanded node names.
625

626
  @type lu: L{LogicalUnit}
627
  @param lu: the logical unit on whose behalf we execute
628
  @type nodes: list
629
  @param nodes: list of node names or None for all nodes
630
  @rtype: list
631
  @return: the list of nodes, sorted
632
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
633

634
  """
635
  if nodes:
636
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
637

    
638
  return utils.NiceSort(lu.cfg.GetNodeList())
639

    
640

    
641
def _GetWantedInstances(lu, instances):
642
  """Returns list of checked and expanded instance names.
643

644
  @type lu: L{LogicalUnit}
645
  @param lu: the logical unit on whose behalf we execute
646
  @type instances: list
647
  @param instances: list of instance names or None for all instances
648
  @rtype: list
649
  @return: the list of instances, sorted
650
  @raise errors.OpPrereqError: if the instances parameter is wrong type
651
  @raise errors.OpPrereqError: if any of the passed instances is not found
652

653
  """
654
  if instances:
655
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
656
  else:
657
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
658
  return wanted
659

    
660

    
661
def _GetUpdatedParams(old_params, update_dict,
662
                      use_default=True, use_none=False):
663
  """Return the new version of a parameter dictionary.
664

665
  @type old_params: dict
666
  @param old_params: old parameters
667
  @type update_dict: dict
668
  @param update_dict: dict containing new parameter values, or
669
      constants.VALUE_DEFAULT to reset the parameter to its default
670
      value
671
  @param use_default: boolean
672
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
673
      values as 'to be deleted' values
674
  @param use_none: boolean
675
  @type use_none: whether to recognise C{None} values as 'to be
676
      deleted' values
677
  @rtype: dict
678
  @return: the new parameter dictionary
679

680
  """
681
  params_copy = copy.deepcopy(old_params)
682
  for key, val in update_dict.iteritems():
683
    if ((use_default and val == constants.VALUE_DEFAULT) or
684
        (use_none and val is None)):
685
      try:
686
        del params_copy[key]
687
      except KeyError:
688
        pass
689
    else:
690
      params_copy[key] = val
691
  return params_copy
692

    
693

    
694
def _ReleaseLocks(lu, level, names=None, keep=None):
695
  """Releases locks owned by an LU.
696

697
  @type lu: L{LogicalUnit}
698
  @param level: Lock level
699
  @type names: list or None
700
  @param names: Names of locks to release
701
  @type keep: list or None
702
  @param keep: Names of locks to retain
703

704
  """
705
  assert not (keep is not None and names is not None), \
706
         "Only one of the 'names' and the 'keep' parameters can be given"
707

    
708
  if names is not None:
709
    should_release = names.__contains__
710
  elif keep:
711
    should_release = lambda name: name not in keep
712
  else:
713
    should_release = None
714

    
715
  if should_release:
716
    retain = []
717
    release = []
718

    
719
    # Determine which locks to release
720
    for name in lu.owned_locks(level):
721
      if should_release(name):
722
        release.append(name)
723
      else:
724
        retain.append(name)
725

    
726
    assert len(lu.owned_locks(level)) == (len(retain) + len(release))
727

    
728
    # Release just some locks
729
    lu.glm.release(level, names=release)
730

    
731
    assert frozenset(lu.owned_locks(level)) == frozenset(retain)
732
  else:
733
    # Release everything
734
    lu.glm.release(level)
735

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

    
738

    
739
def _MapInstanceDisksToNodes(instances):
740
  """Creates a map from (node, volume) to instance name.
741

742
  @type instances: list of L{objects.Instance}
743
  @rtype: dict; tuple of (node name, volume name) as key, instance name as value
744

745
  """
746
  return dict(((node, vol), inst.name)
747
              for inst in instances
748
              for (node, vols) in inst.MapLVsByNode().items()
749
              for vol in vols)
750

    
751

    
752
def _RunPostHook(lu, node_name):
753
  """Runs the post-hook for an opcode on a single node.
754

755
  """
756
  hm = lu.proc.hmclass(lu.rpc.call_hooks_runner, lu)
757
  try:
758
    hm.RunPhase(constants.HOOKS_PHASE_POST, nodes=[node_name])
759
  except:
760
    # pylint: disable=W0702
761
    lu.LogWarning("Errors occurred running hooks on %s" % node_name)
762

    
763

    
764
def _CheckOutputFields(static, dynamic, selected):
765
  """Checks whether all selected fields are valid.
766

767
  @type static: L{utils.FieldSet}
768
  @param static: static fields set
769
  @type dynamic: L{utils.FieldSet}
770
  @param dynamic: dynamic fields set
771

772
  """
773
  f = utils.FieldSet()
774
  f.Extend(static)
775
  f.Extend(dynamic)
776

    
777
  delta = f.NonMatching(selected)
778
  if delta:
779
    raise errors.OpPrereqError("Unknown output fields selected: %s"
780
                               % ",".join(delta), errors.ECODE_INVAL)
781

    
782

    
783
def _CheckGlobalHvParams(params):
784
  """Validates that given hypervisor params are not global ones.
785

786
  This will ensure that instances don't get customised versions of
787
  global params.
788

789
  """
790
  used_globals = constants.HVC_GLOBALS.intersection(params)
791
  if used_globals:
792
    msg = ("The following hypervisor parameters are global and cannot"
793
           " be customized at instance level, please modify them at"
794
           " cluster level: %s" % utils.CommaJoin(used_globals))
795
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
796

    
797

    
798
def _CheckNodeOnline(lu, node, msg=None):
799
  """Ensure that a given node is online.
800

801
  @param lu: the LU on behalf of which we make the check
802
  @param node: the node to check
803
  @param msg: if passed, should be a message to replace the default one
804
  @raise errors.OpPrereqError: if the node is offline
805

806
  """
807
  if msg is None:
808
    msg = "Can't use offline node"
809
  if lu.cfg.GetNodeInfo(node).offline:
810
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
811

    
812

    
813
def _CheckNodeNotDrained(lu, node):
814
  """Ensure that a given node is not drained.
815

816
  @param lu: the LU on behalf of which we make the check
817
  @param node: the node to check
818
  @raise errors.OpPrereqError: if the node is drained
819

820
  """
821
  if lu.cfg.GetNodeInfo(node).drained:
822
    raise errors.OpPrereqError("Can't use drained node %s" % node,
823
                               errors.ECODE_STATE)
824

    
825

    
826
def _CheckNodeVmCapable(lu, node):
827
  """Ensure that a given node is vm capable.
828

829
  @param lu: the LU on behalf of which we make the check
830
  @param node: the node to check
831
  @raise errors.OpPrereqError: if the node is not vm capable
832

833
  """
834
  if not lu.cfg.GetNodeInfo(node).vm_capable:
835
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
836
                               errors.ECODE_STATE)
837

    
838

    
839
def _CheckNodeHasOS(lu, node, os_name, force_variant):
840
  """Ensure that a node supports a given OS.
841

842
  @param lu: the LU on behalf of which we make the check
843
  @param node: the node to check
844
  @param os_name: the OS to query about
845
  @param force_variant: whether to ignore variant errors
846
  @raise errors.OpPrereqError: if the node is not supporting the OS
847

848
  """
849
  result = lu.rpc.call_os_get(node, os_name)
850
  result.Raise("OS '%s' not in supported OS list for node %s" %
851
               (os_name, node),
852
               prereq=True, ecode=errors.ECODE_INVAL)
853
  if not force_variant:
854
    _CheckOSVariant(result.payload, os_name)
855

    
856

    
857
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
858
  """Ensure that a node has the given secondary ip.
859

860
  @type lu: L{LogicalUnit}
861
  @param lu: the LU on behalf of which we make the check
862
  @type node: string
863
  @param node: the node to check
864
  @type secondary_ip: string
865
  @param secondary_ip: the ip to check
866
  @type prereq: boolean
867
  @param prereq: whether to throw a prerequisite or an execute error
868
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
869
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
870

871
  """
872
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
873
  result.Raise("Failure checking secondary ip on node %s" % node,
874
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
875
  if not result.payload:
876
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
877
           " please fix and re-run this command" % secondary_ip)
878
    if prereq:
879
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
880
    else:
881
      raise errors.OpExecError(msg)
882

    
883

    
884
def _GetClusterDomainSecret():
885
  """Reads the cluster domain secret.
886

887
  """
888
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
889
                               strict=True)
890

    
891

    
892
def _CheckInstanceDown(lu, instance, reason):
893
  """Ensure that an instance is not running."""
894
  if instance.admin_up:
895
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
896
                               (instance.name, reason), errors.ECODE_STATE)
897

    
898
  pnode = instance.primary_node
899
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
900
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
901
              prereq=True, ecode=errors.ECODE_ENVIRON)
902

    
903
  if instance.name in ins_l.payload:
904
    raise errors.OpPrereqError("Instance %s is running, %s" %
905
                               (instance.name, reason), errors.ECODE_STATE)
906

    
907

    
908
def _ExpandItemName(fn, name, kind):
909
  """Expand an item name.
910

911
  @param fn: the function to use for expansion
912
  @param name: requested item name
913
  @param kind: text description ('Node' or 'Instance')
914
  @return: the resolved (full) name
915
  @raise errors.OpPrereqError: if the item is not found
916

917
  """
918
  full_name = fn(name)
919
  if full_name is None:
920
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
921
                               errors.ECODE_NOENT)
922
  return full_name
923

    
924

    
925
def _ExpandNodeName(cfg, name):
926
  """Wrapper over L{_ExpandItemName} for nodes."""
927
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
928

    
929

    
930
def _ExpandInstanceName(cfg, name):
931
  """Wrapper over L{_ExpandItemName} for instance."""
932
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
933

    
934

    
935
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
936
                          memory, vcpus, nics, disk_template, disks,
937
                          bep, hvp, hypervisor_name, tags):
938
  """Builds instance related env variables for hooks
939

940
  This builds the hook environment from individual variables.
941

942
  @type name: string
943
  @param name: the name of the instance
944
  @type primary_node: string
945
  @param primary_node: the name of the instance's primary node
946
  @type secondary_nodes: list
947
  @param secondary_nodes: list of secondary nodes as strings
948
  @type os_type: string
949
  @param os_type: the name of the instance's OS
950
  @type status: boolean
951
  @param status: the should_run status of the instance
952
  @type memory: string
953
  @param memory: the memory size of the instance
954
  @type vcpus: string
955
  @param vcpus: the count of VCPUs the instance has
956
  @type nics: list
957
  @param nics: list of tuples (ip, mac, mode, link) representing
958
      the NICs the instance has
959
  @type disk_template: string
960
  @param disk_template: the disk template of the instance
961
  @type disks: list
962
  @param disks: the list of (size, mode) pairs
963
  @type bep: dict
964
  @param bep: the backend parameters for the instance
965
  @type hvp: dict
966
  @param hvp: the hypervisor parameters for the instance
967
  @type hypervisor_name: string
968
  @param hypervisor_name: the hypervisor for the instance
969
  @type tags: list
970
  @param tags: list of instance tags as strings
971
  @rtype: dict
972
  @return: the hook environment for this instance
973

974
  """
975
  if status:
976
    str_status = "up"
977
  else:
978
    str_status = "down"
979
  env = {
980
    "OP_TARGET": name,
981
    "INSTANCE_NAME": name,
982
    "INSTANCE_PRIMARY": primary_node,
983
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
984
    "INSTANCE_OS_TYPE": os_type,
985
    "INSTANCE_STATUS": str_status,
986
    "INSTANCE_MEMORY": memory,
987
    "INSTANCE_VCPUS": vcpus,
988
    "INSTANCE_DISK_TEMPLATE": disk_template,
989
    "INSTANCE_HYPERVISOR": hypervisor_name,
990
  }
991

    
992
  if nics:
993
    nic_count = len(nics)
994
    for idx, (ip, mac, mode, link) in enumerate(nics):
995
      if ip is None:
996
        ip = ""
997
      env["INSTANCE_NIC%d_IP" % idx] = ip
998
      env["INSTANCE_NIC%d_MAC" % idx] = mac
999
      env["INSTANCE_NIC%d_MODE" % idx] = mode
1000
      env["INSTANCE_NIC%d_LINK" % idx] = link
1001
      if mode == constants.NIC_MODE_BRIDGED:
1002
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
1003
  else:
1004
    nic_count = 0
1005

    
1006
  env["INSTANCE_NIC_COUNT"] = nic_count
1007

    
1008
  if disks:
1009
    disk_count = len(disks)
1010
    for idx, (size, mode) in enumerate(disks):
1011
      env["INSTANCE_DISK%d_SIZE" % idx] = size
1012
      env["INSTANCE_DISK%d_MODE" % idx] = mode
1013
  else:
1014
    disk_count = 0
1015

    
1016
  env["INSTANCE_DISK_COUNT"] = disk_count
1017

    
1018
  if not tags:
1019
    tags = []
1020

    
1021
  env["INSTANCE_TAGS"] = " ".join(tags)
1022

    
1023
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
1024
    for key, value in source.items():
1025
      env["INSTANCE_%s_%s" % (kind, key)] = value
1026

    
1027
  return env
1028

    
1029

    
1030
def _NICListToTuple(lu, nics):
1031
  """Build a list of nic information tuples.
1032

1033
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
1034
  value in LUInstanceQueryData.
1035

1036
  @type lu:  L{LogicalUnit}
1037
  @param lu: the logical unit on whose behalf we execute
1038
  @type nics: list of L{objects.NIC}
1039
  @param nics: list of nics to convert to hooks tuples
1040

1041
  """
1042
  hooks_nics = []
1043
  cluster = lu.cfg.GetClusterInfo()
1044
  for nic in nics:
1045
    ip = nic.ip
1046
    mac = nic.mac
1047
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
1048
    mode = filled_params[constants.NIC_MODE]
1049
    link = filled_params[constants.NIC_LINK]
1050
    hooks_nics.append((ip, mac, mode, link))
1051
  return hooks_nics
1052

    
1053

    
1054
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
1055
  """Builds instance related env variables for hooks from an object.
1056

1057
  @type lu: L{LogicalUnit}
1058
  @param lu: the logical unit on whose behalf we execute
1059
  @type instance: L{objects.Instance}
1060
  @param instance: the instance for which we should build the
1061
      environment
1062
  @type override: dict
1063
  @param override: dictionary with key/values that will override
1064
      our values
1065
  @rtype: dict
1066
  @return: the hook environment dictionary
1067

1068
  """
1069
  cluster = lu.cfg.GetClusterInfo()
1070
  bep = cluster.FillBE(instance)
1071
  hvp = cluster.FillHV(instance)
1072
  args = {
1073
    "name": instance.name,
1074
    "primary_node": instance.primary_node,
1075
    "secondary_nodes": instance.secondary_nodes,
1076
    "os_type": instance.os,
1077
    "status": instance.admin_up,
1078
    "memory": bep[constants.BE_MEMORY],
1079
    "vcpus": bep[constants.BE_VCPUS],
1080
    "nics": _NICListToTuple(lu, instance.nics),
1081
    "disk_template": instance.disk_template,
1082
    "disks": [(disk.size, disk.mode) for disk in instance.disks],
1083
    "bep": bep,
1084
    "hvp": hvp,
1085
    "hypervisor_name": instance.hypervisor,
1086
    "tags": instance.tags,
1087
  }
1088
  if override:
1089
    args.update(override)
1090
  return _BuildInstanceHookEnv(**args) # pylint: disable=W0142
1091

    
1092

    
1093
def _AdjustCandidatePool(lu, exceptions):
1094
  """Adjust the candidate pool after node operations.
1095

1096
  """
1097
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1098
  if mod_list:
1099
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1100
               utils.CommaJoin(node.name for node in mod_list))
1101
    for name in mod_list:
1102
      lu.context.ReaddNode(name)
1103
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1104
  if mc_now > mc_max:
1105
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1106
               (mc_now, mc_max))
1107

    
1108

    
1109
def _DecideSelfPromotion(lu, exceptions=None):
1110
  """Decide whether I should promote myself as a master candidate.
1111

1112
  """
1113
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1114
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1115
  # the new node will increase mc_max with one, so:
1116
  mc_should = min(mc_should + 1, cp_size)
1117
  return mc_now < mc_should
1118

    
1119

    
1120
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1121
  """Check that the brigdes needed by a list of nics exist.
1122

1123
  """
1124
  cluster = lu.cfg.GetClusterInfo()
1125
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1126
  brlist = [params[constants.NIC_LINK] for params in paramslist
1127
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1128
  if brlist:
1129
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1130
    result.Raise("Error checking bridges on destination node '%s'" %
1131
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1132

    
1133

    
1134
def _CheckInstanceBridgesExist(lu, instance, node=None):
1135
  """Check that the brigdes needed by an instance exist.
1136

1137
  """
1138
  if node is None:
1139
    node = instance.primary_node
1140
  _CheckNicsBridgesExist(lu, instance.nics, node)
1141

    
1142

    
1143
def _CheckOSVariant(os_obj, name):
1144
  """Check whether an OS name conforms to the os variants specification.
1145

1146
  @type os_obj: L{objects.OS}
1147
  @param os_obj: OS object to check
1148
  @type name: string
1149
  @param name: OS name passed by the user, to check for validity
1150

1151
  """
1152
  variant = objects.OS.GetVariant(name)
1153
  if not os_obj.supported_variants:
1154
    if variant:
1155
      raise errors.OpPrereqError("OS '%s' doesn't support variants ('%s'"
1156
                                 " passed)" % (os_obj.name, variant),
1157
                                 errors.ECODE_INVAL)
1158
    return
1159
  if not variant:
1160
    raise errors.OpPrereqError("OS name must include a variant",
1161
                               errors.ECODE_INVAL)
1162

    
1163
  if variant not in os_obj.supported_variants:
1164
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1165

    
1166

    
1167
def _GetNodeInstancesInner(cfg, fn):
1168
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1169

    
1170

    
1171
def _GetNodeInstances(cfg, node_name):
1172
  """Returns a list of all primary and secondary instances on a node.
1173

1174
  """
1175

    
1176
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1177

    
1178

    
1179
def _GetNodePrimaryInstances(cfg, node_name):
1180
  """Returns primary instances on a node.
1181

1182
  """
1183
  return _GetNodeInstancesInner(cfg,
1184
                                lambda inst: node_name == inst.primary_node)
1185

    
1186

    
1187
def _GetNodeSecondaryInstances(cfg, node_name):
1188
  """Returns secondary instances on a node.
1189

1190
  """
1191
  return _GetNodeInstancesInner(cfg,
1192
                                lambda inst: node_name in inst.secondary_nodes)
1193

    
1194

    
1195
def _GetStorageTypeArgs(cfg, storage_type):
1196
  """Returns the arguments for a storage type.
1197

1198
  """
1199
  # Special case for file storage
1200
  if storage_type == constants.ST_FILE:
1201
    # storage.FileStorage wants a list of storage directories
1202
    return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1203

    
1204
  return []
1205

    
1206

    
1207
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1208
  faulty = []
1209

    
1210
  for dev in instance.disks:
1211
    cfg.SetDiskID(dev, node_name)
1212

    
1213
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1214
  result.Raise("Failed to get disk status from node %s" % node_name,
1215
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1216

    
1217
  for idx, bdev_status in enumerate(result.payload):
1218
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1219
      faulty.append(idx)
1220

    
1221
  return faulty
1222

    
1223

    
1224
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1225
  """Check the sanity of iallocator and node arguments and use the
1226
  cluster-wide iallocator if appropriate.
1227

1228
  Check that at most one of (iallocator, node) is specified. If none is
1229
  specified, then the LU's opcode's iallocator slot is filled with the
1230
  cluster-wide default iallocator.
1231

1232
  @type iallocator_slot: string
1233
  @param iallocator_slot: the name of the opcode iallocator slot
1234
  @type node_slot: string
1235
  @param node_slot: the name of the opcode target node slot
1236

1237
  """
1238
  node = getattr(lu.op, node_slot, None)
1239
  iallocator = getattr(lu.op, iallocator_slot, None)
1240

    
1241
  if node is not None and iallocator is not None:
1242
    raise errors.OpPrereqError("Do not specify both, iallocator and node",
1243
                               errors.ECODE_INVAL)
1244
  elif node is None and iallocator is None:
1245
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1246
    if default_iallocator:
1247
      setattr(lu.op, iallocator_slot, default_iallocator)
1248
    else:
1249
      raise errors.OpPrereqError("No iallocator or node given and no"
1250
                                 " cluster-wide default iallocator found;"
1251
                                 " please specify either an iallocator or a"
1252
                                 " node, or set a cluster-wide default"
1253
                                 " iallocator")
1254

    
1255

    
1256
def _GetDefaultIAllocator(cfg, iallocator):
1257
  """Decides on which iallocator to use.
1258

1259
  @type cfg: L{config.ConfigWriter}
1260
  @param cfg: Cluster configuration object
1261
  @type iallocator: string or None
1262
  @param iallocator: Iallocator specified in opcode
1263
  @rtype: string
1264
  @return: Iallocator name
1265

1266
  """
1267
  if not iallocator:
1268
    # Use default iallocator
1269
    iallocator = cfg.GetDefaultIAllocator()
1270

    
1271
  if not iallocator:
1272
    raise errors.OpPrereqError("No iallocator was specified, neither in the"
1273
                               " opcode nor as a cluster-wide default",
1274
                               errors.ECODE_INVAL)
1275

    
1276
  return iallocator
1277

    
1278

    
1279
class LUClusterPostInit(LogicalUnit):
1280
  """Logical unit for running hooks after cluster initialization.
1281

1282
  """
1283
  HPATH = "cluster-init"
1284
  HTYPE = constants.HTYPE_CLUSTER
1285

    
1286
  def BuildHooksEnv(self):
1287
    """Build hooks env.
1288

1289
    """
1290
    return {
1291
      "OP_TARGET": self.cfg.GetClusterName(),
1292
      }
1293

    
1294
  def BuildHooksNodes(self):
1295
    """Build hooks nodes.
1296

1297
    """
1298
    return ([], [self.cfg.GetMasterNode()])
1299

    
1300
  def Exec(self, feedback_fn):
1301
    """Nothing to do.
1302

1303
    """
1304
    return True
1305

    
1306

    
1307
class LUClusterDestroy(LogicalUnit):
1308
  """Logical unit for destroying the cluster.
1309

1310
  """
1311
  HPATH = "cluster-destroy"
1312
  HTYPE = constants.HTYPE_CLUSTER
1313

    
1314
  def BuildHooksEnv(self):
1315
    """Build hooks env.
1316

1317
    """
1318
    return {
1319
      "OP_TARGET": self.cfg.GetClusterName(),
1320
      }
1321

    
1322
  def BuildHooksNodes(self):
1323
    """Build hooks nodes.
1324

1325
    """
1326
    return ([], [])
1327

    
1328
  def CheckPrereq(self):
1329
    """Check prerequisites.
1330

1331
    This checks whether the cluster is empty.
1332

1333
    Any errors are signaled by raising errors.OpPrereqError.
1334

1335
    """
1336
    master = self.cfg.GetMasterNode()
1337

    
1338
    nodelist = self.cfg.GetNodeList()
1339
    if len(nodelist) != 1 or nodelist[0] != master:
1340
      raise errors.OpPrereqError("There are still %d node(s) in"
1341
                                 " this cluster." % (len(nodelist) - 1),
1342
                                 errors.ECODE_INVAL)
1343
    instancelist = self.cfg.GetInstanceList()
1344
    if instancelist:
1345
      raise errors.OpPrereqError("There are still %d instance(s) in"
1346
                                 " this cluster." % len(instancelist),
1347
                                 errors.ECODE_INVAL)
1348

    
1349
  def Exec(self, feedback_fn):
1350
    """Destroys the cluster.
1351

1352
    """
1353
    master = self.cfg.GetMasterNode()
1354

    
1355
    # Run post hooks on master node before it's removed
1356
    _RunPostHook(self, master)
1357

    
1358
    result = self.rpc.call_node_deactivate_master_ip(master)
1359
    result.Raise("Could not disable the master role")
1360

    
1361
    return master
1362

    
1363

    
1364
def _VerifyCertificate(filename):
1365
  """Verifies a certificate for L{LUClusterVerifyConfig}.
1366

1367
  @type filename: string
1368
  @param filename: Path to PEM file
1369

1370
  """
1371
  try:
1372
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1373
                                           utils.ReadFile(filename))
1374
  except Exception, err: # pylint: disable=W0703
1375
    return (LUClusterVerifyConfig.ETYPE_ERROR,
1376
            "Failed to load X509 certificate %s: %s" % (filename, err))
1377

    
1378
  (errcode, msg) = \
1379
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1380
                                constants.SSL_CERT_EXPIRATION_ERROR)
1381

    
1382
  if msg:
1383
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1384
  else:
1385
    fnamemsg = None
1386

    
1387
  if errcode is None:
1388
    return (None, fnamemsg)
1389
  elif errcode == utils.CERT_WARNING:
1390
    return (LUClusterVerifyConfig.ETYPE_WARNING, fnamemsg)
1391
  elif errcode == utils.CERT_ERROR:
1392
    return (LUClusterVerifyConfig.ETYPE_ERROR, fnamemsg)
1393

    
1394
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1395

    
1396

    
1397
def _GetAllHypervisorParameters(cluster, instances):
1398
  """Compute the set of all hypervisor parameters.
1399

1400
  @type cluster: L{objects.Cluster}
1401
  @param cluster: the cluster object
1402
  @param instances: list of L{objects.Instance}
1403
  @param instances: additional instances from which to obtain parameters
1404
  @rtype: list of (origin, hypervisor, parameters)
1405
  @return: a list with all parameters found, indicating the hypervisor they
1406
       apply to, and the origin (can be "cluster", "os X", or "instance Y")
1407

1408
  """
1409
  hvp_data = []
1410

    
1411
  for hv_name in cluster.enabled_hypervisors:
1412
    hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
1413

    
1414
  for os_name, os_hvp in cluster.os_hvp.items():
1415
    for hv_name, hv_params in os_hvp.items():
1416
      if hv_params:
1417
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
1418
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
1419

    
1420
  # TODO: collapse identical parameter values in a single one
1421
  for instance in instances:
1422
    if instance.hvparams:
1423
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
1424
                       cluster.FillHV(instance)))
1425

    
1426
  return hvp_data
1427

    
1428

    
1429
class _VerifyErrors(object):
1430
  """Mix-in for cluster/group verify LUs.
1431

1432
  It provides _Error and _ErrorIf, and updates the self.bad boolean. (Expects
1433
  self.op and self._feedback_fn to be available.)
1434

1435
  """
1436
  TCLUSTER = "cluster"
1437
  TNODE = "node"
1438
  TINSTANCE = "instance"
1439

    
1440
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1441
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1442
  ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1443
  ECLUSTERDANGLINGNODES = (TNODE, "ECLUSTERDANGLINGNODES")
1444
  ECLUSTERDANGLINGINST = (TNODE, "ECLUSTERDANGLINGINST")
1445
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1446
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1447
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1448
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1449
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1450
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1451
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1452
  ENODEDRBD = (TNODE, "ENODEDRBD")
1453
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1454
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1455
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1456
  ENODEHV = (TNODE, "ENODEHV")
1457
  ENODELVM = (TNODE, "ENODELVM")
1458
  ENODEN1 = (TNODE, "ENODEN1")
1459
  ENODENET = (TNODE, "ENODENET")
1460
  ENODEOS = (TNODE, "ENODEOS")
1461
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1462
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1463
  ENODERPC = (TNODE, "ENODERPC")
1464
  ENODESSH = (TNODE, "ENODESSH")
1465
  ENODEVERSION = (TNODE, "ENODEVERSION")
1466
  ENODESETUP = (TNODE, "ENODESETUP")
1467
  ENODETIME = (TNODE, "ENODETIME")
1468
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1469

    
1470
  ETYPE_FIELD = "code"
1471
  ETYPE_ERROR = "ERROR"
1472
  ETYPE_WARNING = "WARNING"
1473

    
1474
  def _Error(self, ecode, item, msg, *args, **kwargs):
1475
    """Format an error message.
1476

1477
    Based on the opcode's error_codes parameter, either format a
1478
    parseable error code, or a simpler error string.
1479

1480
    This must be called only from Exec and functions called from Exec.
1481

1482
    """
1483
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1484
    itype, etxt = ecode
1485
    # first complete the msg
1486
    if args:
1487
      msg = msg % args
1488
    # then format the whole message
1489
    if self.op.error_codes: # This is a mix-in. pylint: disable=E1101
1490
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1491
    else:
1492
      if item:
1493
        item = " " + item
1494
      else:
1495
        item = ""
1496
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1497
    # and finally report it via the feedback_fn
1498
    self._feedback_fn("  - %s" % msg) # Mix-in. pylint: disable=E1101
1499

    
1500
  def _ErrorIf(self, cond, *args, **kwargs):
1501
    """Log an error message if the passed condition is True.
1502

1503
    """
1504
    cond = (bool(cond)
1505
            or self.op.debug_simulate_errors) # pylint: disable=E1101
1506
    if cond:
1507
      self._Error(*args, **kwargs)
1508
    # do not mark the operation as failed for WARN cases only
1509
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1510
      self.bad = self.bad or cond
1511

    
1512

    
1513
class LUClusterVerify(NoHooksLU):
1514
  """Submits all jobs necessary to verify the cluster.
1515

1516
  """
1517
  REQ_BGL = False
1518

    
1519
  def ExpandNames(self):
1520
    self.needed_locks = {}
1521

    
1522
  def Exec(self, feedback_fn):
1523
    jobs = []
1524

    
1525
    if self.op.group_name:
1526
      groups = [self.op.group_name]
1527
      depends_fn = lambda: None
1528
    else:
1529
      groups = self.cfg.GetNodeGroupList()
1530

    
1531
      # Verify global configuration
1532
      jobs.append([opcodes.OpClusterVerifyConfig()])
1533

    
1534
      # Always depend on global verification
1535
      depends_fn = lambda: [(-len(jobs), [])]
1536

    
1537
    jobs.extend([opcodes.OpClusterVerifyGroup(group_name=group,
1538
                                              depends=depends_fn())]
1539
                for group in groups)
1540

    
1541
    # Fix up all parameters
1542
    for op in itertools.chain(*jobs): # pylint: disable=W0142
1543
      op.debug_simulate_errors = self.op.debug_simulate_errors
1544
      op.verbose = self.op.verbose
1545
      op.error_codes = self.op.error_codes
1546
      try:
1547
        op.skip_checks = self.op.skip_checks
1548
      except AttributeError:
1549
        assert not isinstance(op, opcodes.OpClusterVerifyGroup)
1550

    
1551
    return ResultWithJobs(jobs)
1552

    
1553

    
1554
class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1555
  """Verifies the cluster config.
1556

1557
  """
1558
  REQ_BGL = True
1559

    
1560
  def _VerifyHVP(self, hvp_data):
1561
    """Verifies locally the syntax of the hypervisor parameters.
1562

1563
    """
1564
    for item, hv_name, hv_params in hvp_data:
1565
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
1566
             (item, hv_name))
1567
      try:
1568
        hv_class = hypervisor.GetHypervisor(hv_name)
1569
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1570
        hv_class.CheckParameterSyntax(hv_params)
1571
      except errors.GenericError, err:
1572
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
1573

    
1574
  def ExpandNames(self):
1575
    # Information can be safely retrieved as the BGL is acquired in exclusive
1576
    # mode
1577
    assert locking.BGL in self.owned_locks(locking.LEVEL_CLUSTER)
1578
    self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1579
    self.all_node_info = self.cfg.GetAllNodesInfo()
1580
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1581
    self.needed_locks = {}
1582

    
1583
  def Exec(self, feedback_fn):
1584
    """Verify integrity of cluster, performing various test on nodes.
1585

1586
    """
1587
    self.bad = False
1588
    self._feedback_fn = feedback_fn
1589

    
1590
    feedback_fn("* Verifying cluster config")
1591

    
1592
    for msg in self.cfg.VerifyConfig():
1593
      self._ErrorIf(True, self.ECLUSTERCFG, None, msg)
1594

    
1595
    feedback_fn("* Verifying cluster certificate files")
1596

    
1597
    for cert_filename in constants.ALL_CERT_FILES:
1598
      (errcode, msg) = _VerifyCertificate(cert_filename)
1599
      self._ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1600

    
1601
    feedback_fn("* Verifying hypervisor parameters")
1602

    
1603
    self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1604
                                                self.all_inst_info.values()))
1605

    
1606
    feedback_fn("* Verifying all nodes belong to an existing group")
1607

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

    
1612
    dangling_nodes = set(node.name for node in self.all_node_info.values()
1613
                         if node.group not in self.all_group_info)
1614

    
1615
    dangling_instances = {}
1616
    no_node_instances = []
1617

    
1618
    for inst in self.all_inst_info.values():
1619
      if inst.primary_node in dangling_nodes:
1620
        dangling_instances.setdefault(inst.primary_node, []).append(inst.name)
1621
      elif inst.primary_node not in self.all_node_info:
1622
        no_node_instances.append(inst.name)
1623

    
1624
    pretty_dangling = [
1625
        "%s (%s)" %
1626
        (node.name,
1627
         utils.CommaJoin(dangling_instances.get(node.name,
1628
                                                ["no instances"])))
1629
        for node in dangling_nodes]
1630

    
1631
    self._ErrorIf(bool(dangling_nodes), self.ECLUSTERDANGLINGNODES, None,
1632
                  "the following nodes (and their instances) belong to a non"
1633
                  " existing group: %s", utils.CommaJoin(pretty_dangling))
1634

    
1635
    self._ErrorIf(bool(no_node_instances), self.ECLUSTERDANGLINGINST, None,
1636
                  "the following instances have a non-existing primary-node:"
1637
                  " %s", utils.CommaJoin(no_node_instances))
1638

    
1639
    return not self.bad
1640

    
1641

    
1642
class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1643
  """Verifies the status of a node group.
1644

1645
  """
1646
  HPATH = "cluster-verify"
1647
  HTYPE = constants.HTYPE_CLUSTER
1648
  REQ_BGL = False
1649

    
1650
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1651

    
1652
  class NodeImage(object):
1653
    """A class representing the logical and physical status of a node.
1654

1655
    @type name: string
1656
    @ivar name: the node name to which this object refers
1657
    @ivar volumes: a structure as returned from
1658
        L{ganeti.backend.GetVolumeList} (runtime)
1659
    @ivar instances: a list of running instances (runtime)
1660
    @ivar pinst: list of configured primary instances (config)
1661
    @ivar sinst: list of configured secondary instances (config)
1662
    @ivar sbp: dictionary of {primary-node: list of instances} for all
1663
        instances for which this node is secondary (config)
1664
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1665
    @ivar dfree: free disk, as reported by the node (runtime)
1666
    @ivar offline: the offline status (config)
1667
    @type rpc_fail: boolean
1668
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1669
        not whether the individual keys were correct) (runtime)
1670
    @type lvm_fail: boolean
1671
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1672
    @type hyp_fail: boolean
1673
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1674
    @type ghost: boolean
1675
    @ivar ghost: whether this is a known node or not (config)
1676
    @type os_fail: boolean
1677
    @ivar os_fail: whether the RPC call didn't return valid OS data
1678
    @type oslist: list
1679
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1680
    @type vm_capable: boolean
1681
    @ivar vm_capable: whether the node can host instances
1682

1683
    """
1684
    def __init__(self, offline=False, name=None, vm_capable=True):
1685
      self.name = name
1686
      self.volumes = {}
1687
      self.instances = []
1688
      self.pinst = []
1689
      self.sinst = []
1690
      self.sbp = {}
1691
      self.mfree = 0
1692
      self.dfree = 0
1693
      self.offline = offline
1694
      self.vm_capable = vm_capable
1695
      self.rpc_fail = False
1696
      self.lvm_fail = False
1697
      self.hyp_fail = False
1698
      self.ghost = False
1699
      self.os_fail = False
1700
      self.oslist = {}
1701

    
1702
  def ExpandNames(self):
1703
    # This raises errors.OpPrereqError on its own:
1704
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1705

    
1706
    # Get instances in node group; this is unsafe and needs verification later
1707
    inst_names = self.cfg.GetNodeGroupInstances(self.group_uuid)
1708

    
1709
    self.needed_locks = {
1710
      locking.LEVEL_INSTANCE: inst_names,
1711
      locking.LEVEL_NODEGROUP: [self.group_uuid],
1712
      locking.LEVEL_NODE: [],
1713
      }
1714

    
1715
    self.share_locks = _ShareAll()
1716

    
1717
  def DeclareLocks(self, level):
1718
    if level == locking.LEVEL_NODE:
1719
      # Get members of node group; this is unsafe and needs verification later
1720
      nodes = set(self.cfg.GetNodeGroup(self.group_uuid).members)
1721

    
1722
      all_inst_info = self.cfg.GetAllInstancesInfo()
1723

    
1724
      # In Exec(), we warn about mirrored instances that have primary and
1725
      # secondary living in separate node groups. To fully verify that
1726
      # volumes for these instances are healthy, we will need to do an
1727
      # extra call to their secondaries. We ensure here those nodes will
1728
      # be locked.
1729
      for inst in self.owned_locks(locking.LEVEL_INSTANCE):
1730
        # Important: access only the instances whose lock is owned
1731
        if all_inst_info[inst].disk_template in constants.DTS_INT_MIRROR:
1732
          nodes.update(all_inst_info[inst].secondary_nodes)
1733

    
1734
      self.needed_locks[locking.LEVEL_NODE] = nodes
1735

    
1736
  def CheckPrereq(self):
1737
    assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
1738
    self.group_info = self.cfg.GetNodeGroup(self.group_uuid)
1739

    
1740
    group_nodes = set(self.group_info.members)
1741
    group_instances = self.cfg.GetNodeGroupInstances(self.group_uuid)
1742

    
1743
    unlocked_nodes = \
1744
        group_nodes.difference(self.owned_locks(locking.LEVEL_NODE))
1745

    
1746
    unlocked_instances = \
1747
        group_instances.difference(self.owned_locks(locking.LEVEL_INSTANCE))
1748

    
1749
    if unlocked_nodes:
1750
      raise errors.OpPrereqError("Missing lock for nodes: %s" %
1751
                                 utils.CommaJoin(unlocked_nodes))
1752

    
1753
    if unlocked_instances:
1754
      raise errors.OpPrereqError("Missing lock for instances: %s" %
1755
                                 utils.CommaJoin(unlocked_instances))
1756

    
1757
    self.all_node_info = self.cfg.GetAllNodesInfo()
1758
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1759

    
1760
    self.my_node_names = utils.NiceSort(group_nodes)
1761
    self.my_inst_names = utils.NiceSort(group_instances)
1762

    
1763
    self.my_node_info = dict((name, self.all_node_info[name])
1764
                             for name in self.my_node_names)
1765

    
1766
    self.my_inst_info = dict((name, self.all_inst_info[name])
1767
                             for name in self.my_inst_names)
1768

    
1769
    # We detect here the nodes that will need the extra RPC calls for verifying
1770
    # split LV volumes; they should be locked.
1771
    extra_lv_nodes = set()
1772

    
1773
    for inst in self.my_inst_info.values():
1774
      if inst.disk_template in constants.DTS_INT_MIRROR:
1775
        group = self.my_node_info[inst.primary_node].group
1776
        for nname in inst.secondary_nodes:
1777
          if self.all_node_info[nname].group != group:
1778
            extra_lv_nodes.add(nname)
1779

    
1780
    unlocked_lv_nodes = \
1781
        extra_lv_nodes.difference(self.owned_locks(locking.LEVEL_NODE))
1782

    
1783
    if unlocked_lv_nodes:
1784
      raise errors.OpPrereqError("these nodes could be locked: %s" %
1785
                                 utils.CommaJoin(unlocked_lv_nodes))
1786
    self.extra_lv_nodes = list(extra_lv_nodes)
1787

    
1788
  def _VerifyNode(self, ninfo, nresult):
1789
    """Perform some basic validation on data returned from a node.
1790

1791
      - check the result data structure is well formed and has all the
1792
        mandatory fields
1793
      - check ganeti version
1794

1795
    @type ninfo: L{objects.Node}
1796
    @param ninfo: the node to check
1797
    @param nresult: the results from the node
1798
    @rtype: boolean
1799
    @return: whether overall this call was successful (and we can expect
1800
         reasonable values in the respose)
1801

1802
    """
1803
    node = ninfo.name
1804
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
1805

    
1806
    # main result, nresult should be a non-empty dict
1807
    test = not nresult or not isinstance(nresult, dict)
1808
    _ErrorIf(test, self.ENODERPC, node,
1809
                  "unable to verify node: no data returned")
1810
    if test:
1811
      return False
1812

    
1813
    # compares ganeti version
1814
    local_version = constants.PROTOCOL_VERSION
1815
    remote_version = nresult.get("version", None)
1816
    test = not (remote_version and
1817
                isinstance(remote_version, (list, tuple)) and
1818
                len(remote_version) == 2)
1819
    _ErrorIf(test, self.ENODERPC, node,
1820
             "connection to node returned invalid data")
1821
    if test:
1822
      return False
1823

    
1824
    test = local_version != remote_version[0]
1825
    _ErrorIf(test, self.ENODEVERSION, node,
1826
             "incompatible protocol versions: master %s,"
1827
             " node %s", local_version, remote_version[0])
1828
    if test:
1829
      return False
1830

    
1831
    # node seems compatible, we can actually try to look into its results
1832

    
1833
    # full package version
1834
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1835
                  self.ENODEVERSION, node,
1836
                  "software version mismatch: master %s, node %s",
1837
                  constants.RELEASE_VERSION, remote_version[1],
1838
                  code=self.ETYPE_WARNING)
1839

    
1840
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1841
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1842
      for hv_name, hv_result in hyp_result.iteritems():
1843
        test = hv_result is not None
1844
        _ErrorIf(test, self.ENODEHV, node,
1845
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1846

    
1847
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1848
    if ninfo.vm_capable and isinstance(hvp_result, list):
1849
      for item, hv_name, hv_result in hvp_result:
1850
        _ErrorIf(True, self.ENODEHV, node,
1851
                 "hypervisor %s parameter verify failure (source %s): %s",
1852
                 hv_name, item, hv_result)
1853

    
1854
    test = nresult.get(constants.NV_NODESETUP,
1855
                       ["Missing NODESETUP results"])
1856
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1857
             "; ".join(test))
1858

    
1859
    return True
1860

    
1861
  def _VerifyNodeTime(self, ninfo, nresult,
1862
                      nvinfo_starttime, nvinfo_endtime):
1863
    """Check the node time.
1864

1865
    @type ninfo: L{objects.Node}
1866
    @param ninfo: the node to check
1867
    @param nresult: the remote results for the node
1868
    @param nvinfo_starttime: the start time of the RPC call
1869
    @param nvinfo_endtime: the end time of the RPC call
1870

1871
    """
1872
    node = ninfo.name
1873
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
1874

    
1875
    ntime = nresult.get(constants.NV_TIME, None)
1876
    try:
1877
      ntime_merged = utils.MergeTime(ntime)
1878
    except (ValueError, TypeError):
1879
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1880
      return
1881

    
1882
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1883
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1884
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1885
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1886
    else:
1887
      ntime_diff = None
1888

    
1889
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1890
             "Node time diverges by at least %s from master node time",
1891
             ntime_diff)
1892

    
1893
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1894
    """Check the node LVM results.
1895

1896
    @type ninfo: L{objects.Node}
1897
    @param ninfo: the node to check
1898
    @param nresult: the remote results for the node
1899
    @param vg_name: the configured VG name
1900

1901
    """
1902
    if vg_name is None:
1903
      return
1904

    
1905
    node = ninfo.name
1906
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
1907

    
1908
    # checks vg existence and size > 20G
1909
    vglist = nresult.get(constants.NV_VGLIST, None)
1910
    test = not vglist
1911
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1912
    if not test:
1913
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1914
                                            constants.MIN_VG_SIZE)
1915
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1916

    
1917
    # check pv names
1918
    pvlist = nresult.get(constants.NV_PVLIST, None)
1919
    test = pvlist is None
1920
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1921
    if not test:
1922
      # check that ':' is not present in PV names, since it's a
1923
      # special character for lvcreate (denotes the range of PEs to
1924
      # use on the PV)
1925
      for _, pvname, owner_vg in pvlist:
1926
        test = ":" in pvname
1927
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1928
                 " '%s' of VG '%s'", pvname, owner_vg)
1929

    
1930
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1931
    """Check the node bridges.
1932

1933
    @type ninfo: L{objects.Node}
1934
    @param ninfo: the node to check
1935
    @param nresult: the remote results for the node
1936
    @param bridges: the expected list of bridges
1937

1938
    """
1939
    if not bridges:
1940
      return
1941

    
1942
    node = ninfo.name
1943
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
1944

    
1945
    missing = nresult.get(constants.NV_BRIDGES, None)
1946
    test = not isinstance(missing, list)
1947
    _ErrorIf(test, self.ENODENET, node,
1948
             "did not return valid bridge information")
1949
    if not test:
1950
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1951
               utils.CommaJoin(sorted(missing)))
1952

    
1953
  def _VerifyNodeNetwork(self, ninfo, nresult):
1954
    """Check the node network connectivity results.
1955

1956
    @type ninfo: L{objects.Node}
1957
    @param ninfo: the node to check
1958
    @param nresult: the remote results for the node
1959

1960
    """
1961
    node = ninfo.name
1962
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
1963

    
1964
    test = constants.NV_NODELIST not in nresult
1965
    _ErrorIf(test, self.ENODESSH, node,
1966
             "node hasn't returned node ssh connectivity data")
1967
    if not test:
1968
      if nresult[constants.NV_NODELIST]:
1969
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1970
          _ErrorIf(True, self.ENODESSH, node,
1971
                   "ssh communication with node '%s': %s", a_node, a_msg)
1972

    
1973
    test = constants.NV_NODENETTEST not in nresult
1974
    _ErrorIf(test, self.ENODENET, node,
1975
             "node hasn't returned node tcp connectivity data")
1976
    if not test:
1977
      if nresult[constants.NV_NODENETTEST]:
1978
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1979
        for anode in nlist:
1980
          _ErrorIf(True, self.ENODENET, node,
1981
                   "tcp communication with node '%s': %s",
1982
                   anode, nresult[constants.NV_NODENETTEST][anode])
1983

    
1984
    test = constants.NV_MASTERIP not in nresult
1985
    _ErrorIf(test, self.ENODENET, node,
1986
             "node hasn't returned node master IP reachability data")
1987
    if not test:
1988
      if not nresult[constants.NV_MASTERIP]:
1989
        if node == self.master_node:
1990
          msg = "the master node cannot reach the master IP (not configured?)"
1991
        else:
1992
          msg = "cannot reach the master IP"
1993
        _ErrorIf(True, self.ENODENET, node, msg)
1994

    
1995
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1996
                      diskstatus):
1997
    """Verify an instance.
1998

1999
    This function checks to see if the required block devices are
2000
    available on the instance's node.
2001

2002
    """
2003
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2004
    node_current = instanceconfig.primary_node
2005

    
2006
    node_vol_should = {}
2007
    instanceconfig.MapLVsByNode(node_vol_should)
2008

    
2009
    for node in node_vol_should:
2010
      n_img = node_image[node]
2011
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
2012
        # ignore missing volumes on offline or broken nodes
2013
        continue
2014
      for volume in node_vol_should[node]:
2015
        test = volume not in n_img.volumes
2016
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
2017
                 "volume %s missing on node %s", volume, node)
2018

    
2019
    if instanceconfig.admin_up:
2020
      pri_img = node_image[node_current]
2021
      test = instance not in pri_img.instances and not pri_img.offline
2022
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
2023
               "instance not running on its primary node %s",
2024
               node_current)
2025

    
2026
    diskdata = [(nname, success, status, idx)
2027
                for (nname, disks) in diskstatus.items()
2028
                for idx, (success, status) in enumerate(disks)]
2029

    
2030
    for nname, success, bdev_status, idx in diskdata:
2031
      # the 'ghost node' construction in Exec() ensures that we have a
2032
      # node here
2033
      snode = node_image[nname]
2034
      bad_snode = snode.ghost or snode.offline
2035
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
2036
               self.EINSTANCEFAULTYDISK, instance,
2037
               "couldn't retrieve status for disk/%s on %s: %s",
2038
               idx, nname, bdev_status)
2039
      _ErrorIf((instanceconfig.admin_up and success and
2040
                bdev_status.ldisk_status == constants.LDS_FAULTY),
2041
               self.EINSTANCEFAULTYDISK, instance,
2042
               "disk/%s on %s is faulty", idx, nname)
2043

    
2044
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
2045
    """Verify if there are any unknown volumes in the cluster.
2046

2047
    The .os, .swap and backup volumes are ignored. All other volumes are
2048
    reported as unknown.
2049

2050
    @type reserved: L{ganeti.utils.FieldSet}
2051
    @param reserved: a FieldSet of reserved volume names
2052

2053
    """
2054
    for node, n_img in node_image.items():
2055
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
2056
        # skip non-healthy nodes
2057
        continue
2058
      for volume in n_img.volumes:
2059
        test = ((node not in node_vol_should or
2060
                volume not in node_vol_should[node]) and
2061
                not reserved.Matches(volume))
2062
        self._ErrorIf(test, self.ENODEORPHANLV, node,
2063
                      "volume %s is unknown", volume)
2064

    
2065
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
2066
    """Verify N+1 Memory Resilience.
2067

2068
    Check that if one single node dies we can still start all the
2069
    instances it was primary for.
2070

2071
    """
2072
    cluster_info = self.cfg.GetClusterInfo()
2073
    for node, n_img in node_image.items():
2074
      # This code checks that every node which is now listed as
2075
      # secondary has enough memory to host all instances it is
2076
      # supposed to should a single other node in the cluster fail.
2077
      # FIXME: not ready for failover to an arbitrary node
2078
      # FIXME: does not support file-backed instances
2079
      # WARNING: we currently take into account down instances as well
2080
      # as up ones, considering that even if they're down someone
2081
      # might want to start them even in the event of a node failure.
2082
      if n_img.offline:
2083
        # we're skipping offline nodes from the N+1 warning, since
2084
        # most likely we don't have good memory infromation from them;
2085
        # we already list instances living on such nodes, and that's
2086
        # enough warning
2087
        continue
2088
      for prinode, instances in n_img.sbp.items():
2089
        needed_mem = 0
2090
        for instance in instances:
2091
          bep = cluster_info.FillBE(instance_cfg[instance])
2092
          if bep[constants.BE_AUTO_BALANCE]:
2093
            needed_mem += bep[constants.BE_MEMORY]
2094
        test = n_img.mfree < needed_mem
2095
        self._ErrorIf(test, self.ENODEN1, node,
2096
                      "not enough memory to accomodate instance failovers"
2097
                      " should node %s fail (%dMiB needed, %dMiB available)",
2098
                      prinode, needed_mem, n_img.mfree)
2099

    
2100
  @classmethod
2101
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
2102
                   (files_all, files_all_opt, files_mc, files_vm)):
2103
    """Verifies file checksums collected from all nodes.
2104

2105
    @param errorif: Callback for reporting errors
2106
    @param nodeinfo: List of L{objects.Node} objects
2107
    @param master_node: Name of master node
2108
    @param all_nvinfo: RPC results
2109

2110
    """
2111
    node_names = frozenset(node.name for node in nodeinfo if not node.offline)
2112

    
2113
    assert master_node in node_names
2114
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
2115
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
2116
           "Found file listed in more than one file list"
2117

    
2118
    # Define functions determining which nodes to consider for a file
2119
    file2nodefn = dict([(filename, fn)
2120
      for (files, fn) in [(files_all, None),
2121
                          (files_all_opt, None),
2122
                          (files_mc, lambda node: (node.master_candidate or
2123
                                                   node.name == master_node)),
2124
                          (files_vm, lambda node: node.vm_capable)]
2125
      for filename in files])
2126

    
2127
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
2128

    
2129
    for node in nodeinfo:
2130
      if node.offline:
2131
        continue
2132

    
2133
      nresult = all_nvinfo[node.name]
2134

    
2135
      if nresult.fail_msg or not nresult.payload:
2136
        node_files = None
2137
      else:
2138
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
2139

    
2140
      test = not (node_files and isinstance(node_files, dict))
2141
      errorif(test, cls.ENODEFILECHECK, node.name,
2142
              "Node did not return file checksum data")
2143
      if test:
2144
        continue
2145

    
2146
      for (filename, checksum) in node_files.items():
2147
        # Check if the file should be considered for a node
2148
        fn = file2nodefn[filename]
2149
        if fn is None or fn(node):
2150
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
2151

    
2152
    for (filename, checksums) in fileinfo.items():
2153
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
2154

    
2155
      # Nodes having the file
2156
      with_file = frozenset(node_name
2157
                            for nodes in fileinfo[filename].values()
2158
                            for node_name in nodes)
2159

    
2160
      # Nodes missing file
2161
      missing_file = node_names - with_file
2162

    
2163
      if filename in files_all_opt:
2164
        # All or no nodes
2165
        errorif(missing_file and missing_file != node_names,
2166
                cls.ECLUSTERFILECHECK, None,
2167
                "File %s is optional, but it must exist on all or no"
2168
                " nodes (not found on %s)",
2169
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
2170
      else:
2171
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
2172
                "File %s is missing from node(s) %s", filename,
2173
                utils.CommaJoin(utils.NiceSort(missing_file)))
2174

    
2175
      # See if there are multiple versions of the file
2176
      test = len(checksums) > 1
2177
      if test:
2178
        variants = ["variant %s on %s" %
2179
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
2180
                    for (idx, (checksum, nodes)) in
2181
                      enumerate(sorted(checksums.items()))]
2182
      else:
2183
        variants = []
2184

    
2185
      errorif(test, cls.ECLUSTERFILECHECK, None,
2186
              "File %s found with %s different checksums (%s)",
2187
              filename, len(checksums), "; ".join(variants))
2188

    
2189
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
2190
                      drbd_map):
2191
    """Verifies and the node DRBD status.
2192

2193
    @type ninfo: L{objects.Node}
2194
    @param ninfo: the node to check
2195
    @param nresult: the remote results for the node
2196
    @param instanceinfo: the dict of instances
2197
    @param drbd_helper: the configured DRBD usermode helper
2198
    @param drbd_map: the DRBD map as returned by
2199
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
2200

2201
    """
2202
    node = ninfo.name
2203
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2204

    
2205
    if drbd_helper:
2206
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
2207
      test = (helper_result == None)
2208
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
2209
               "no drbd usermode helper returned")
2210
      if helper_result:
2211
        status, payload = helper_result
2212
        test = not status
2213
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2214
                 "drbd usermode helper check unsuccessful: %s", payload)
2215
        test = status and (payload != drbd_helper)
2216
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2217
                 "wrong drbd usermode helper: %s", payload)
2218

    
2219
    # compute the DRBD minors
2220
    node_drbd = {}
2221
    for minor, instance in drbd_map[node].items():
2222
      test = instance not in instanceinfo
2223
      _ErrorIf(test, self.ECLUSTERCFG, None,
2224
               "ghost instance '%s' in temporary DRBD map", instance)
2225
        # ghost instance should not be running, but otherwise we
2226
        # don't give double warnings (both ghost instance and
2227
        # unallocated minor in use)
2228
      if test:
2229
        node_drbd[minor] = (instance, False)
2230
      else:
2231
        instance = instanceinfo[instance]
2232
        node_drbd[minor] = (instance.name, instance.admin_up)
2233

    
2234
    # and now check them
2235
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
2236
    test = not isinstance(used_minors, (tuple, list))
2237
    _ErrorIf(test, self.ENODEDRBD, node,
2238
             "cannot parse drbd status file: %s", str(used_minors))
2239
    if test:
2240
      # we cannot check drbd status
2241
      return
2242

    
2243
    for minor, (iname, must_exist) in node_drbd.items():
2244
      test = minor not in used_minors and must_exist
2245
      _ErrorIf(test, self.ENODEDRBD, node,
2246
               "drbd minor %d of instance %s is not active", minor, iname)
2247
    for minor in used_minors:
2248
      test = minor not in node_drbd
2249
      _ErrorIf(test, self.ENODEDRBD, node,
2250
               "unallocated drbd minor %d is in use", minor)
2251

    
2252
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
2253
    """Builds the node OS structures.
2254

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

2260
    """
2261
    node = ninfo.name
2262
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2263

    
2264
    remote_os = nresult.get(constants.NV_OSLIST, None)
2265
    test = (not isinstance(remote_os, list) or
2266
            not compat.all(isinstance(v, list) and len(v) == 7
2267
                           for v in remote_os))
2268

    
2269
    _ErrorIf(test, self.ENODEOS, node,
2270
             "node hasn't returned valid OS data")
2271

    
2272
    nimg.os_fail = test
2273

    
2274
    if test:
2275
      return
2276

    
2277
    os_dict = {}
2278

    
2279
    for (name, os_path, status, diagnose,
2280
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2281

    
2282
      if name not in os_dict:
2283
        os_dict[name] = []
2284

    
2285
      # parameters is a list of lists instead of list of tuples due to
2286
      # JSON lacking a real tuple type, fix it:
2287
      parameters = [tuple(v) for v in parameters]
2288
      os_dict[name].append((os_path, status, diagnose,
2289
                            set(variants), set(parameters), set(api_ver)))
2290

    
2291
    nimg.oslist = os_dict
2292

    
2293
  def _VerifyNodeOS(self, ninfo, nimg, base):
2294
    """Verifies the node OS list.
2295

2296
    @type ninfo: L{objects.Node}
2297
    @param ninfo: the node to check
2298
    @param nimg: the node image object
2299
    @param base: the 'template' node we match against (e.g. from the master)
2300

2301
    """
2302
    node = ninfo.name
2303
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2304

    
2305
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2306

    
2307
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
2308
    for os_name, os_data in nimg.oslist.items():
2309
      assert os_data, "Empty OS status for OS %s?!" % os_name
2310
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
2311
      _ErrorIf(not f_status, self.ENODEOS, node,
2312
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
2313
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
2314
               "OS '%s' has multiple entries (first one shadows the rest): %s",
2315
               os_name, utils.CommaJoin([v[0] for v in os_data]))
2316
      # comparisons with the 'base' image
2317
      test = os_name not in base.oslist
2318
      _ErrorIf(test, self.ENODEOS, node,
2319
               "Extra OS %s not present on reference node (%s)",
2320
               os_name, base.name)
2321
      if test:
2322
        continue
2323
      assert base.oslist[os_name], "Base node has empty OS status?"
2324
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
2325
      if not b_status:
2326
        # base OS is invalid, skipping
2327
        continue
2328
      for kind, a, b in [("API version", f_api, b_api),
2329
                         ("variants list", f_var, b_var),
2330
                         ("parameters", beautify_params(f_param),
2331
                          beautify_params(b_param))]:
2332
        _ErrorIf(a != b, self.ENODEOS, node,
2333
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2334
                 kind, os_name, base.name,
2335
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2336

    
2337
    # check any missing OSes
2338
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2339
    _ErrorIf(missing, self.ENODEOS, node,
2340
             "OSes present on reference node %s but missing on this node: %s",
2341
             base.name, utils.CommaJoin(missing))
2342

    
2343
  def _VerifyOob(self, ninfo, nresult):
2344
    """Verifies out of band functionality of a node.
2345

2346
    @type ninfo: L{objects.Node}
2347
    @param ninfo: the node to check
2348
    @param nresult: the remote results for the node
2349

2350
    """
2351
    node = ninfo.name
2352
    # We just have to verify the paths on master and/or master candidates
2353
    # as the oob helper is invoked on the master
2354
    if ((ninfo.master_candidate or ninfo.master_capable) and
2355
        constants.NV_OOB_PATHS in nresult):
2356
      for path_result in nresult[constants.NV_OOB_PATHS]:
2357
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2358

    
2359
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2360
    """Verifies and updates the node volume data.
2361

2362
    This function will update a L{NodeImage}'s internal structures
2363
    with data from the remote call.
2364

2365
    @type ninfo: L{objects.Node}
2366
    @param ninfo: the node to check
2367
    @param nresult: the remote results for the node
2368
    @param nimg: the node image object
2369
    @param vg_name: the configured VG name
2370

2371
    """
2372
    node = ninfo.name
2373
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2374

    
2375
    nimg.lvm_fail = True
2376
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2377
    if vg_name is None:
2378
      pass
2379
    elif isinstance(lvdata, basestring):
2380
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2381
               utils.SafeEncode(lvdata))
2382
    elif not isinstance(lvdata, dict):
2383
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2384
    else:
2385
      nimg.volumes = lvdata
2386
      nimg.lvm_fail = False
2387

    
2388
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2389
    """Verifies and updates the node instance list.
2390

2391
    If the listing was successful, then updates this node's instance
2392
    list. Otherwise, it marks the RPC call as failed for the instance
2393
    list key.
2394

2395
    @type ninfo: L{objects.Node}
2396
    @param ninfo: the node to check
2397
    @param nresult: the remote results for the node
2398
    @param nimg: the node image object
2399

2400
    """
2401
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2402
    test = not isinstance(idata, list)
2403
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2404
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2405
    if test:
2406
      nimg.hyp_fail = True
2407
    else:
2408
      nimg.instances = idata
2409

    
2410
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2411
    """Verifies and computes a node information map
2412

2413
    @type ninfo: L{objects.Node}
2414
    @param ninfo: the node to check
2415
    @param nresult: the remote results for the node
2416
    @param nimg: the node image object
2417
    @param vg_name: the configured VG name
2418

2419
    """
2420
    node = ninfo.name
2421
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2422

    
2423
    # try to read free memory (from the hypervisor)
2424
    hv_info = nresult.get(constants.NV_HVINFO, None)
2425
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2426
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2427
    if not test:
2428
      try:
2429
        nimg.mfree = int(hv_info["memory_free"])
2430
      except (ValueError, TypeError):
2431
        _ErrorIf(True, self.ENODERPC, node,
2432
                 "node returned invalid nodeinfo, check hypervisor")
2433

    
2434
    # FIXME: devise a free space model for file based instances as well
2435
    if vg_name is not None:
2436
      test = (constants.NV_VGLIST not in nresult or
2437
              vg_name not in nresult[constants.NV_VGLIST])
2438
      _ErrorIf(test, self.ENODELVM, node,
2439
               "node didn't return data for the volume group '%s'"
2440
               " - it is either missing or broken", vg_name)
2441
      if not test:
2442
        try:
2443
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2444
        except (ValueError, TypeError):
2445
          _ErrorIf(True, self.ENODERPC, node,
2446
                   "node returned invalid LVM info, check LVM status")
2447

    
2448
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2449
    """Gets per-disk status information for all instances.
2450

2451
    @type nodelist: list of strings
2452
    @param nodelist: Node names
2453
    @type node_image: dict of (name, L{objects.Node})
2454
    @param node_image: Node objects
2455
    @type instanceinfo: dict of (name, L{objects.Instance})
2456
    @param instanceinfo: Instance objects
2457
    @rtype: {instance: {node: [(succes, payload)]}}
2458
    @return: a dictionary of per-instance dictionaries with nodes as
2459
        keys and disk information as values; the disk information is a
2460
        list of tuples (success, payload)
2461

2462
    """
2463
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2464

    
2465
    node_disks = {}
2466
    node_disks_devonly = {}
2467
    diskless_instances = set()
2468
    diskless = constants.DT_DISKLESS
2469

    
2470
    for nname in nodelist:
2471
      node_instances = list(itertools.chain(node_image[nname].pinst,
2472
                                            node_image[nname].sinst))
2473
      diskless_instances.update(inst for inst in node_instances
2474
                                if instanceinfo[inst].disk_template == diskless)
2475
      disks = [(inst, disk)
2476
               for inst in node_instances
2477
               for disk in instanceinfo[inst].disks]
2478

    
2479
      if not disks:
2480
        # No need to collect data
2481
        continue
2482

    
2483
      node_disks[nname] = disks
2484

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

    
2489
      for dev in devonly:
2490
        self.cfg.SetDiskID(dev, nname)
2491

    
2492
      node_disks_devonly[nname] = devonly
2493

    
2494
    assert len(node_disks) == len(node_disks_devonly)
2495

    
2496
    # Collect data from all nodes with disks
2497
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2498
                                                          node_disks_devonly)
2499

    
2500
    assert len(result) == len(node_disks)
2501

    
2502
    instdisk = {}
2503

    
2504
    for (nname, nres) in result.items():
2505
      disks = node_disks[nname]
2506

    
2507
      if nres.offline:
2508
        # No data from this node
2509
        data = len(disks) * [(False, "node offline")]
2510
      else:
2511
        msg = nres.fail_msg
2512
        _ErrorIf(msg, self.ENODERPC, nname,
2513
                 "while getting disk information: %s", msg)
2514
        if msg:
2515
          # No data from this node
2516
          data = len(disks) * [(False, msg)]
2517
        else:
2518
          data = []
2519
          for idx, i in enumerate(nres.payload):
2520
            if isinstance(i, (tuple, list)) and len(i) == 2:
2521
              data.append(i)
2522
            else:
2523
              logging.warning("Invalid result from node %s, entry %d: %s",
2524
                              nname, idx, i)
2525
              data.append((False, "Invalid result from the remote node"))
2526

    
2527
      for ((inst, _), status) in zip(disks, data):
2528
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2529

    
2530
    # Add empty entries for diskless instances.
2531
    for inst in diskless_instances:
2532
      assert inst not in instdisk
2533
      instdisk[inst] = {}
2534

    
2535
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2536
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2537
                      compat.all(isinstance(s, (tuple, list)) and
2538
                                 len(s) == 2 for s in statuses)
2539
                      for inst, nnames in instdisk.items()
2540
                      for nname, statuses in nnames.items())
2541
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2542

    
2543
    return instdisk
2544

    
2545
  def BuildHooksEnv(self):
2546
    """Build hooks env.
2547

2548
    Cluster-Verify hooks just ran in the post phase and their failure makes
2549
    the output be logged in the verify output and the verification to fail.
2550

2551
    """
2552
    env = {
2553
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2554
      }
2555

    
2556
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2557
               for node in self.my_node_info.values())
2558

    
2559
    return env
2560

    
2561
  def BuildHooksNodes(self):
2562
    """Build hooks nodes.
2563

2564
    """
2565
    return ([], self.my_node_names)
2566

    
2567
  def Exec(self, feedback_fn):
2568
    """Verify integrity of the node group, performing various test on nodes.
2569

2570
    """
2571
    # This method has too many local variables. pylint: disable=R0914
2572
    feedback_fn("* Verifying group '%s'" % self.group_info.name)
2573

    
2574
    if not self.my_node_names:
2575
      # empty node group
2576
      feedback_fn("* Empty node group, skipping verification")
2577
      return True
2578

    
2579
    self.bad = False
2580
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2581
    verbose = self.op.verbose
2582
    self._feedback_fn = feedback_fn
2583

    
2584
    vg_name = self.cfg.GetVGName()
2585
    drbd_helper = self.cfg.GetDRBDHelper()
2586
    cluster = self.cfg.GetClusterInfo()
2587
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2588
    hypervisors = cluster.enabled_hypervisors
2589
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2590

    
2591
    i_non_redundant = [] # Non redundant instances
2592
    i_non_a_balanced = [] # Non auto-balanced instances
2593
    n_offline = 0 # Count of offline nodes
2594
    n_drained = 0 # Count of nodes being drained
2595
    node_vol_should = {}
2596

    
2597
    # FIXME: verify OS list
2598

    
2599
    # File verification
2600
    filemap = _ComputeAncillaryFiles(cluster, False)
2601

    
2602
    # do local checksums
2603
    master_node = self.master_node = self.cfg.GetMasterNode()
2604
    master_ip = self.cfg.GetMasterIP()
2605

    
2606
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2607

    
2608
    # We will make nodes contact all nodes in their group, and one node from
2609
    # every other group.
2610
    # TODO: should it be a *random* node, different every time?
2611
    online_nodes = [node.name for node in node_data_list if not node.offline]
2612
    other_group_nodes = {}
2613

    
2614
    for name in sorted(self.all_node_info):
2615
      node = self.all_node_info[name]
2616
      if (node.group not in other_group_nodes
2617
          and node.group != self.group_uuid
2618
          and not node.offline):
2619
        other_group_nodes[node.group] = node.name
2620

    
2621
    node_verify_param = {
2622
      constants.NV_FILELIST:
2623
        utils.UniqueSequence(filename
2624
                             for files in filemap
2625
                             for filename in files),
2626
      constants.NV_NODELIST: online_nodes + other_group_nodes.values(),
2627
      constants.NV_HYPERVISOR: hypervisors,
2628
      constants.NV_HVPARAMS:
2629
        _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2630
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2631
                                 for node in node_data_list
2632
                                 if not node.offline],
2633
      constants.NV_INSTANCELIST: hypervisors,
2634
      constants.NV_VERSION: None,
2635
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2636
      constants.NV_NODESETUP: None,
2637
      constants.NV_TIME: None,
2638
      constants.NV_MASTERIP: (master_node, master_ip),
2639
      constants.NV_OSLIST: None,
2640
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2641
      }
2642

    
2643
    if vg_name is not None:
2644
      node_verify_param[constants.NV_VGLIST] = None
2645
      node_verify_param[constants.NV_LVLIST] = vg_name
2646
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2647
      node_verify_param[constants.NV_DRBDLIST] = None
2648

    
2649
    if drbd_helper:
2650
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2651

    
2652
    # bridge checks
2653
    # FIXME: this needs to be changed per node-group, not cluster-wide
2654
    bridges = set()
2655
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2656
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2657
      bridges.add(default_nicpp[constants.NIC_LINK])
2658
    for instance in self.my_inst_info.values():
2659
      for nic in instance.nics:
2660
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2661
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2662
          bridges.add(full_nic[constants.NIC_LINK])
2663

    
2664
    if bridges:
2665
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2666

    
2667
    # Build our expected cluster state
2668
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2669
                                                 name=node.name,
2670
                                                 vm_capable=node.vm_capable))
2671
                      for node in node_data_list)
2672

    
2673
    # Gather OOB paths
2674
    oob_paths = []
2675
    for node in self.all_node_info.values():
2676
      path = _SupportsOob(self.cfg, node)
2677
      if path and path not in oob_paths:
2678
        oob_paths.append(path)
2679

    
2680
    if oob_paths:
2681
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2682

    
2683
    for instance in self.my_inst_names:
2684
      inst_config = self.my_inst_info[instance]
2685

    
2686
      for nname in inst_config.all_nodes:
2687
        if nname not in node_image:
2688
          gnode = self.NodeImage(name=nname)
2689
          gnode.ghost = (nname not in self.all_node_info)
2690
          node_image[nname] = gnode
2691

    
2692
      inst_config.MapLVsByNode(node_vol_should)
2693

    
2694
      pnode = inst_config.primary_node
2695
      node_image[pnode].pinst.append(instance)
2696

    
2697
      for snode in inst_config.secondary_nodes:
2698
        nimg = node_image[snode]
2699
        nimg.sinst.append(instance)
2700
        if pnode not in nimg.sbp:
2701
          nimg.sbp[pnode] = []
2702
        nimg.sbp[pnode].append(instance)
2703

    
2704
    # At this point, we have the in-memory data structures complete,
2705
    # except for the runtime information, which we'll gather next
2706

    
2707
    # Due to the way our RPC system works, exact response times cannot be
2708
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2709
    # time before and after executing the request, we can at least have a time
2710
    # window.
2711
    nvinfo_starttime = time.time()
2712
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2713
                                           node_verify_param,
2714
                                           self.cfg.GetClusterName())
2715
    nvinfo_endtime = time.time()
2716

    
2717
    if self.extra_lv_nodes and vg_name is not None:
2718
      extra_lv_nvinfo = \
2719
          self.rpc.call_node_verify(self.extra_lv_nodes,
2720
                                    {constants.NV_LVLIST: vg_name},
2721
                                    self.cfg.GetClusterName())
2722
    else:
2723
      extra_lv_nvinfo = {}
2724

    
2725
    all_drbd_map = self.cfg.ComputeDRBDMap()
2726

    
2727
    feedback_fn("* Gathering disk information (%s nodes)" %
2728
                len(self.my_node_names))
2729
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2730
                                     self.my_inst_info)
2731

    
2732
    feedback_fn("* Verifying configuration file consistency")
2733

    
2734
    # If not all nodes are being checked, we need to make sure the master node
2735
    # and a non-checked vm_capable node are in the list.
2736
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2737
    if absent_nodes:
2738
      vf_nvinfo = all_nvinfo.copy()
2739
      vf_node_info = list(self.my_node_info.values())
2740
      additional_nodes = []
2741
      if master_node not in self.my_node_info:
2742
        additional_nodes.append(master_node)
2743
        vf_node_info.append(self.all_node_info[master_node])
2744
      # Add the first vm_capable node we find which is not included
2745
      for node in absent_nodes:
2746
        nodeinfo = self.all_node_info[node]
2747
        if nodeinfo.vm_capable and not nodeinfo.offline:
2748
          additional_nodes.append(node)
2749
          vf_node_info.append(self.all_node_info[node])
2750
          break
2751
      key = constants.NV_FILELIST
2752
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2753
                                                 {key: node_verify_param[key]},
2754
                                                 self.cfg.GetClusterName()))
2755
    else:
2756
      vf_nvinfo = all_nvinfo
2757
      vf_node_info = self.my_node_info.values()
2758

    
2759
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2760

    
2761
    feedback_fn("* Verifying node status")
2762

    
2763
    refos_img = None
2764

    
2765
    for node_i in node_data_list:
2766
      node = node_i.name
2767
      nimg = node_image[node]
2768

    
2769
      if node_i.offline:
2770
        if verbose:
2771
          feedback_fn("* Skipping offline node %s" % (node,))
2772
        n_offline += 1
2773
        continue
2774

    
2775
      if node == master_node:
2776
        ntype = "master"
2777
      elif node_i.master_candidate:
2778
        ntype = "master candidate"
2779
      elif node_i.drained:
2780
        ntype = "drained"
2781
        n_drained += 1
2782
      else:
2783
        ntype = "regular"
2784
      if verbose:
2785
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2786

    
2787
      msg = all_nvinfo[node].fail_msg
2788
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2789
      if msg:
2790
        nimg.rpc_fail = True
2791
        continue
2792

    
2793
      nresult = all_nvinfo[node].payload
2794

    
2795
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2796
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2797
      self._VerifyNodeNetwork(node_i, nresult)
2798
      self._VerifyOob(node_i, nresult)
2799

    
2800
      if nimg.vm_capable:
2801
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2802
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2803
                             all_drbd_map)
2804

    
2805
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2806
        self._UpdateNodeInstances(node_i, nresult, nimg)
2807
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2808
        self._UpdateNodeOS(node_i, nresult, nimg)
2809

    
2810
        if not nimg.os_fail:
2811
          if refos_img is None:
2812
            refos_img = nimg
2813
          self._VerifyNodeOS(node_i, nimg, refos_img)
2814
        self._VerifyNodeBridges(node_i, nresult, bridges)
2815

    
2816
        # Check whether all running instancies are primary for the node. (This
2817
        # can no longer be done from _VerifyInstance below, since some of the
2818
        # wrong instances could be from other node groups.)
2819
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2820

    
2821
        for inst in non_primary_inst:
2822
          test = inst in self.all_inst_info
2823
          _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2824
                   "instance should not run on node %s", node_i.name)
2825
          _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2826
                   "node is running unknown instance %s", inst)
2827

    
2828
    for node, result in extra_lv_nvinfo.items():
2829
      self._UpdateNodeVolumes(self.all_node_info[node], result.payload,
2830
                              node_image[node], vg_name)
2831

    
2832
    feedback_fn("* Verifying instance status")
2833
    for instance in self.my_inst_names:
2834
      if verbose:
2835
        feedback_fn("* Verifying instance %s" % instance)
2836
      inst_config = self.my_inst_info[instance]
2837
      self._VerifyInstance(instance, inst_config, node_image,
2838
                           instdisk[instance])
2839
      inst_nodes_offline = []
2840

    
2841
      pnode = inst_config.primary_node
2842
      pnode_img = node_image[pnode]
2843
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2844
               self.ENODERPC, pnode, "instance %s, connection to"
2845
               " primary node failed", instance)
2846

    
2847
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2848
               self.EINSTANCEBADNODE, instance,
2849
               "instance is marked as running and lives on offline node %s",
2850
               inst_config.primary_node)
2851

    
2852
      # If the instance is non-redundant we cannot survive losing its primary
2853
      # node, so we are not N+1 compliant. On the other hand we have no disk
2854
      # templates with more than one secondary so that situation is not well
2855
      # supported either.
2856
      # FIXME: does not support file-backed instances
2857
      if not inst_config.secondary_nodes:
2858
        i_non_redundant.append(instance)
2859

    
2860
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2861
               instance, "instance has multiple secondary nodes: %s",
2862
               utils.CommaJoin(inst_config.secondary_nodes),
2863
               code=self.ETYPE_WARNING)
2864

    
2865
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2866
        pnode = inst_config.primary_node
2867
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2868
        instance_groups = {}
2869

    
2870
        for node in instance_nodes:
2871
          instance_groups.setdefault(self.all_node_info[node].group,
2872
                                     []).append(node)
2873

    
2874
        pretty_list = [
2875
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2876
          # Sort so that we always list the primary node first.
2877
          for group, nodes in sorted(instance_groups.items(),
2878
                                     key=lambda (_, nodes): pnode in nodes,
2879
                                     reverse=True)]
2880

    
2881
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2882
                      instance, "instance has primary and secondary nodes in"
2883
                      " different groups: %s", utils.CommaJoin(pretty_list),
2884
                      code=self.ETYPE_WARNING)
2885

    
2886
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2887
        i_non_a_balanced.append(instance)
2888

    
2889
      for snode in inst_config.secondary_nodes:
2890
        s_img = node_image[snode]
2891
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2892
                 "instance %s, connection to secondary node failed", instance)
2893

    
2894
        if s_img.offline:
2895
          inst_nodes_offline.append(snode)
2896

    
2897
      # warn that the instance lives on offline nodes
2898
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2899
               "instance has offline secondary node(s) %s",
2900
               utils.CommaJoin(inst_nodes_offline))
2901
      # ... or ghost/non-vm_capable nodes
2902
      for node in inst_config.all_nodes:
2903
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2904
                 "instance lives on ghost node %s", node)
2905
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2906
                 instance, "instance lives on non-vm_capable node %s", node)
2907

    
2908
    feedback_fn("* Verifying orphan volumes")
2909
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2910

    
2911
    # We will get spurious "unknown volume" warnings if any node of this group
2912
    # is secondary for an instance whose primary is in another group. To avoid
2913
    # them, we find these instances and add their volumes to node_vol_should.
2914
    for inst in self.all_inst_info.values():
2915
      for secondary in inst.secondary_nodes:
2916
        if (secondary in self.my_node_info
2917
            and inst.name not in self.my_inst_info):
2918
          inst.MapLVsByNode(node_vol_should)
2919
          break
2920

    
2921
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2922

    
2923
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2924
      feedback_fn("* Verifying N+1 Memory redundancy")
2925
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2926

    
2927
    feedback_fn("* Other Notes")
2928
    if i_non_redundant:
2929
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2930
                  % len(i_non_redundant))
2931

    
2932
    if i_non_a_balanced:
2933
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2934
                  % len(i_non_a_balanced))
2935

    
2936
    if n_offline:
2937
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2938

    
2939
    if n_drained:
2940
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2941

    
2942
    return not self.bad
2943

    
2944
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2945
    """Analyze the post-hooks' result
2946

2947
    This method analyses the hook result, handles it, and sends some
2948
    nicely-formatted feedback back to the user.
2949

2950
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2951
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2952
    @param hooks_results: the results of the multi-node hooks rpc call
2953
    @param feedback_fn: function used send feedback back to the caller
2954
    @param lu_result: previous Exec result
2955
    @return: the new Exec result, based on the previous result
2956
        and hook results
2957

2958
    """
2959
    # We only really run POST phase hooks, only for non-empty groups,
2960
    # and are only interested in their results
2961
    if not self.my_node_names:
2962
      # empty node group
2963
      pass
2964
    elif phase == constants.HOOKS_PHASE_POST:
2965
      # Used to change hooks' output to proper indentation
2966
      feedback_fn("* Hooks Results")
2967
      assert hooks_results, "invalid result from hooks"
2968

    
2969
      for node_name in hooks_results:
2970
        res = hooks_results[node_name]
2971
        msg = res.fail_msg
2972
        test = msg and not res.offline
2973
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2974
                      "Communication failure in hooks execution: %s", msg)
2975
        if res.offline or msg:
2976
          # No need to investigate payload if node is offline or gave an error.
2977
          # override manually lu_result here as _ErrorIf only
2978
          # overrides self.bad
2979
          lu_result = 1
2980
          continue
2981
        for script, hkr, output in res.payload:
2982
          test = hkr == constants.HKR_FAIL
2983
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2984
                        "Script %s failed, output:", script)
2985
          if test:
2986
            output = self._HOOKS_INDENT_RE.sub("      ", output)
2987
            feedback_fn("%s" % output)
2988
            lu_result = 0
2989

    
2990
    return lu_result
2991

    
2992

    
2993
class LUClusterVerifyDisks(NoHooksLU):
2994
  """Verifies the cluster disks status.
2995

2996
  """
2997
  REQ_BGL = False
2998

    
2999
  def ExpandNames(self):
3000
    self.share_locks = _ShareAll()
3001
    self.needed_locks = {
3002
      locking.LEVEL_NODEGROUP: locking.ALL_SET,
3003
      }
3004

    
3005
  def Exec(self, feedback_fn):
3006
    group_names = self.owned_locks(locking.LEVEL_NODEGROUP)
3007

    
3008
    # Submit one instance of L{opcodes.OpGroupVerifyDisks} per node group
3009
    return ResultWithJobs([[opcodes.OpGroupVerifyDisks(group_name=group)]
3010
                           for group in group_names])
3011

    
3012

    
3013
class LUGroupVerifyDisks(NoHooksLU):
3014
  """Verifies the status of all disks in a node group.
3015

3016
  """
3017
  REQ_BGL = False
3018

    
3019
  def ExpandNames(self):
3020
    # Raises errors.OpPrereqError on its own if group can't be found
3021
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
3022

    
3023
    self.share_locks = _ShareAll()
3024
    self.needed_locks = {
3025
      locking.LEVEL_INSTANCE: [],
3026
      locking.LEVEL_NODEGROUP: [],
3027
      locking.LEVEL_NODE: [],
3028
      }
3029

    
3030
  def DeclareLocks(self, level):
3031
    if level == locking.LEVEL_INSTANCE:
3032
      assert not self.needed_locks[locking.LEVEL_INSTANCE]
3033

    
3034
      # Lock instances optimistically, needs verification once node and group
3035
      # locks have been acquired
3036
      self.needed_locks[locking.LEVEL_INSTANCE] = \
3037
        self.cfg.GetNodeGroupInstances(self.group_uuid)
3038

    
3039
    elif level == locking.LEVEL_NODEGROUP:
3040
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
3041

    
3042
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
3043
        set([self.group_uuid] +
3044
            # Lock all groups used by instances optimistically; this requires
3045
            # going via the node before it's locked, requiring verification
3046
            # later on
3047
            [group_uuid
3048
             for instance_name in self.owned_locks(locking.LEVEL_INSTANCE)
3049
             for group_uuid in self.cfg.GetInstanceNodeGroups(instance_name)])
3050

    
3051
    elif level == locking.LEVEL_NODE:
3052
      # This will only lock the nodes in the group to be verified which contain
3053
      # actual instances
3054
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
3055
      self._LockInstancesNodes()
3056

    
3057
      # Lock all nodes in group to be verified
3058
      assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
3059
      member_nodes = self.cfg.GetNodeGroup(self.group_uuid).members
3060
      self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
3061

    
3062
  def CheckPrereq(self):
3063
    owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
3064
    owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
3065
    owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
3066

    
3067
    assert self.group_uuid in owned_groups
3068

    
3069
    # Check if locked instances are still correct
3070
    _CheckNodeGroupInstances(self.cfg, self.group_uuid, owned_instances)
3071

    
3072
    # Get instance information
3073
    self.instances = dict(self.cfg.GetMultiInstanceInfo(owned_instances))
3074

    
3075
    # Check if node groups for locked instances are still correct
3076
    for (instance_name, inst) in self.instances.items():
3077
      assert owned_nodes.issuperset(inst.all_nodes), \
3078
        "Instance %s's nodes changed while we kept the lock" % instance_name
3079

    
3080
      inst_groups = _CheckInstanceNodeGroups(self.cfg, instance_name,
3081
                                             owned_groups)
3082

    
3083
      assert self.group_uuid in inst_groups, \
3084
        "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
3085

    
3086
  def Exec(self, feedback_fn):
3087
    """Verify integrity of cluster disks.
3088

3089
    @rtype: tuple of three items
3090
    @return: a tuple of (dict of node-to-node_error, list of instances
3091
        which need activate-disks, dict of instance: (node, volume) for
3092
        missing volumes
3093

3094
    """
3095
    res_nodes = {}
3096
    res_instances = set()
3097
    res_missing = {}
3098

    
3099
    nv_dict = _MapInstanceDisksToNodes([inst
3100
                                        for inst in self.instances.values()
3101
                                        if inst.admin_up])
3102

    
3103
    if nv_dict:
3104
      nodes = utils.NiceSort(set(self.owned_locks(locking.LEVEL_NODE)) &
3105
                             set(self.cfg.GetVmCapableNodeList()))
3106

    
3107
      node_lvs = self.rpc.call_lv_list(nodes, [])
3108

    
3109
      for (node, node_res) in node_lvs.items():
3110
        if node_res.offline:
3111
          continue
3112

    
3113
        msg = node_res.fail_msg
3114
        if msg:
3115
          logging.warning("Error enumerating LVs on node %s: %s", node, msg)
3116
          res_nodes[node] = msg
3117
          continue
3118

    
3119
        for lv_name, (_, _, lv_online) in node_res.payload.items():
3120
          inst = nv_dict.pop((node, lv_name), None)
3121
          if not (lv_online or inst is None):
3122
            res_instances.add(inst)
3123

    
3124
      # any leftover items in nv_dict are missing LVs, let's arrange the data
3125
      # better
3126
      for key, inst in nv_dict.iteritems():
3127
        res_missing.setdefault(inst, []).append(key)
3128

    
3129
    return (res_nodes, list(res_instances), res_missing)
3130

    
3131

    
3132
class LUClusterRepairDiskSizes(NoHooksLU):
3133
  """Verifies the cluster disks sizes.
3134

3135
  """
3136
  REQ_BGL = False
3137

    
3138
  def ExpandNames(self):
3139
    if self.op.instances:
3140
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
3141
      self.needed_locks = {
3142
        locking.LEVEL_NODE: [],
3143
        locking.LEVEL_INSTANCE: self.wanted_names,
3144
        }
3145
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3146
    else:
3147
      self.wanted_names = None
3148
      self.needed_locks = {
3149
        locking.LEVEL_NODE: locking.ALL_SET,
3150
        locking.LEVEL_INSTANCE: locking.ALL_SET,
3151
        }
3152
    self.share_locks = _ShareAll()
3153

    
3154
  def DeclareLocks(self, level):
3155
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
3156
      self._LockInstancesNodes(primary_only=True)
3157

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

3161
    This only checks the optional instance list against the existing names.
3162

3163
    """
3164
    if self.wanted_names is None:
3165
      self.wanted_names = self.owned_locks(locking.LEVEL_INSTANCE)
3166

    
3167
    self.wanted_instances = \
3168
        map(compat.snd, self.cfg.GetMultiInstanceInfo(self.wanted_names))
3169

    
3170
  def _EnsureChildSizes(self, disk):
3171
    """Ensure children of the disk have the needed disk size.
3172

3173
    This is valid mainly for DRBD8 and fixes an issue where the
3174
    children have smaller disk size.
3175

3176
    @param disk: an L{ganeti.objects.Disk} object
3177

3178
    """
3179
    if disk.dev_type == constants.LD_DRBD8:
3180
      assert disk.children, "Empty children for DRBD8?"
3181
      fchild = disk.children[0]
3182
      mismatch = fchild.size < disk.size
3183
      if mismatch:
3184
        self.LogInfo("Child disk has size %d, parent %d, fixing",
3185
                     fchild.size, disk.size)
3186
        fchild.size = disk.size
3187

    
3188
      # and we recurse on this child only, not on the metadev
3189
      return self._EnsureChildSizes(fchild) or mismatch
3190
    else:
3191
      return False
3192

    
3193
  def Exec(self, feedback_fn):
3194
    """Verify the size of cluster disks.
3195

3196
    """
3197
    # TODO: check child disks too
3198
    # TODO: check differences in size between primary/secondary nodes
3199
    per_node_disks = {}
3200
    for instance in self.wanted_instances:
3201
      pnode = instance.primary_node
3202
      if pnode not in per_node_disks:
3203
        per_node_disks[pnode] = []
3204
      for idx, disk in enumerate(instance.disks):
3205
        per_node_disks[pnode].append((instance, idx, disk))
3206

    
3207
    changed = []
3208
    for node, dskl in per_node_disks.items():
3209
      newl = [v[2].Copy() for v in dskl]
3210
      for dsk in newl:
3211
        self.cfg.SetDiskID(dsk, node)
3212
      result = self.rpc.call_blockdev_getsize(node, newl)
3213
      if result.fail_msg:
3214
        self.LogWarning("Failure in blockdev_getsize call to node"
3215
                        " %s, ignoring", node)
3216
        continue
3217
      if len(result.payload) != len(dskl):
3218
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
3219
                        " result.payload=%s", node, len(dskl), result.payload)
3220
        self.LogWarning("Invalid result from node %s, ignoring node results",
3221
                        node)
3222
        continue
3223
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
3224
        if size is None:
3225
          self.LogWarning("Disk %d of instance %s did not return size"
3226
                          " information, ignoring", idx, instance.name)
3227
          continue
3228
        if not isinstance(size, (int, long)):
3229
          self.LogWarning("Disk %d of instance %s did not return valid"
3230
                          " size information, ignoring", idx, instance.name)
3231
          continue
3232
        size = size >> 20
3233
        if size != disk.size:
3234
          self.LogInfo("Disk %d of instance %s has mismatched size,"
3235
                       " correcting: recorded %d, actual %d", idx,
3236
                       instance.name, disk.size, size)
3237
          disk.size = size
3238
          self.cfg.Update(instance, feedback_fn)
3239
          changed.append((instance.name, idx, size))
3240
        if self._EnsureChildSizes(disk):
3241
          self.cfg.Update(instance, feedback_fn)
3242
          changed.append((instance.name, idx, disk.size))
3243
    return changed
3244

    
3245

    
3246
class LUClusterRename(LogicalUnit):
3247
  """Rename the cluster.
3248

3249
  """
3250
  HPATH = "cluster-rename"
3251
  HTYPE = constants.HTYPE_CLUSTER
3252

    
3253
  def BuildHooksEnv(self):
3254
    """Build hooks env.
3255

3256
    """
3257
    return {
3258
      "OP_TARGET": self.cfg.GetClusterName(),
3259
      "NEW_NAME": self.op.name,
3260
      }
3261

    
3262
  def BuildHooksNodes(self):
3263
    """Build hooks nodes.
3264

3265
    """
3266
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
3267

    
3268
  def CheckPrereq(self):
3269
    """Verify that the passed name is a valid one.
3270

3271
    """
3272
    hostname = netutils.GetHostname(name=self.op.name,
3273
                                    family=self.cfg.GetPrimaryIPFamily())
3274

    
3275
    new_name = hostname.name
3276
    self.ip = new_ip = hostname.ip
3277
    old_name = self.cfg.GetClusterName()
3278
    old_ip = self.cfg.GetMasterIP()
3279
    if new_name == old_name and new_ip == old_ip:
3280
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
3281
                                 " cluster has changed",
3282
                                 errors.ECODE_INVAL)
3283
    if new_ip != old_ip:
3284
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
3285
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
3286
                                   " reachable on the network" %
3287
                                   new_ip, errors.ECODE_NOTUNIQUE)
3288

    
3289
    self.op.name = new_name
3290

    
3291
  def Exec(self, feedback_fn):
3292
    """Rename the cluster.
3293

3294
    """
3295
    clustername = self.op.name
3296
    ip = self.ip
3297

    
3298
    # shutdown the master IP
3299
    master = self.cfg.GetMasterNode()
3300
    result = self.rpc.call_node_deactivate_master_ip(master)
3301
    result.Raise("Could not disable the master role")
3302

    
3303
    try:
3304
      cluster = self.cfg.GetClusterInfo()
3305
      cluster.cluster_name = clustername
3306
      cluster.master_ip = ip
3307
      self.cfg.Update(cluster, feedback_fn)
3308

    
3309
      # update the known hosts file
3310
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
3311
      node_list = self.cfg.GetOnlineNodeList()
3312
      try:
3313
        node_list.remove(master)
3314
      except ValueError:
3315
        pass
3316
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3317
    finally:
3318
      result = self.rpc.call_node_activate_master_ip(master)
3319
      msg = result.fail_msg
3320
      if msg:
3321
        self.LogWarning("Could not re-enable the master role on"
3322
                        " the master, please restart manually: %s", msg)
3323

    
3324
    return clustername
3325

    
3326

    
3327
class LUClusterSetParams(LogicalUnit):
3328
  """Change the parameters of the cluster.
3329

3330
  """
3331
  HPATH = "cluster-modify"
3332
  HTYPE = constants.HTYPE_CLUSTER
3333
  REQ_BGL = False
3334

    
3335
  def CheckArguments(self):
3336
    """Check parameters
3337

3338
    """
3339
    if self.op.uid_pool:
3340
      uidpool.CheckUidPool(self.op.uid_pool)
3341

    
3342
    if self.op.add_uids:
3343
      uidpool.CheckUidPool(self.op.add_uids)
3344

    
3345
    if self.op.remove_uids:
3346
      uidpool.CheckUidPool(self.op.remove_uids)
3347

    
3348
  def ExpandNames(self):
3349
    # FIXME: in the future maybe other cluster params won't require checking on
3350
    # all nodes to be modified.
3351
    self.needed_locks = {
3352
      locking.LEVEL_NODE: locking.ALL_SET,
3353
    }
3354
    self.share_locks[locking.LEVEL_NODE] = 1
3355

    
3356
  def BuildHooksEnv(self):
3357
    """Build hooks env.
3358

3359
    """
3360
    return {
3361
      "OP_TARGET": self.cfg.GetClusterName(),
3362
      "NEW_VG_NAME": self.op.vg_name,
3363
      }
3364

    
3365
  def BuildHooksNodes(self):
3366
    """Build hooks nodes.
3367

3368
    """
3369
    mn = self.cfg.GetMasterNode()
3370
    return ([mn], [mn])
3371

    
3372
  def CheckPrereq(self):
3373
    """Check prerequisites.
3374

3375
    This checks whether the given params don't conflict and
3376
    if the given volume group is valid.
3377

3378
    """
3379
    if self.op.vg_name is not None and not self.op.vg_name:
3380
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3381
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3382
                                   " instances exist", errors.ECODE_INVAL)
3383

    
3384
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
3385
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3386
        raise errors.OpPrereqError("Cannot disable drbd helper while"
3387
                                   " drbd-based instances exist",
3388
                                   errors.ECODE_INVAL)
3389

    
3390
    node_list = self.owned_locks(locking.LEVEL_NODE)
3391

    
3392
    # if vg_name not None, checks given volume group on all nodes
3393
    if self.op.vg_name:
3394
      vglist = self.rpc.call_vg_list(node_list)
3395
      for node in node_list:
3396
        msg = vglist[node].fail_msg
3397
        if msg:
3398
          # ignoring down node
3399
          self.LogWarning("Error while gathering data on node %s"
3400
                          " (ignoring node): %s", node, msg)
3401
          continue
3402
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3403
                                              self.op.vg_name,
3404
                                              constants.MIN_VG_SIZE)
3405
        if vgstatus:
3406
          raise errors.OpPrereqError("Error on node '%s': %s" %
3407
                                     (node, vgstatus), errors.ECODE_ENVIRON)
3408

    
3409
    if self.op.drbd_helper:
3410
      # checks given drbd helper on all nodes
3411
      helpers = self.rpc.call_drbd_helper(node_list)
3412
      for (node, ninfo) in self.cfg.GetMultiNodeInfo(node_list):
3413
        if ninfo.offline:
3414
          self.LogInfo("Not checking drbd helper on offline node %s", node)
3415
          continue
3416
        msg = helpers[node].fail_msg
3417
        if msg:
3418
          raise errors.OpPrereqError("Error checking drbd helper on node"
3419
                                     " '%s': %s" % (node, msg),
3420
                                     errors.ECODE_ENVIRON)
3421
        node_helper = helpers[node].payload
3422
        if node_helper != self.op.drbd_helper:
3423
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3424
                                     (node, node_helper), errors.ECODE_ENVIRON)
3425

    
3426
    self.cluster = cluster = self.cfg.GetClusterInfo()
3427
    # validate params changes
3428
    if self.op.beparams:
3429
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3430
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3431

    
3432
    if self.op.ndparams:
3433
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3434
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3435

    
3436
      # TODO: we need a more general way to handle resetting
3437
      # cluster-level parameters to default values
3438
      if self.new_ndparams["oob_program"] == "":
3439
        self.new_ndparams["oob_program"] = \
3440
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3441

    
3442
    if self.op.nicparams:
3443
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3444
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3445
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3446
      nic_errors = []
3447

    
3448
      # check all instances for consistency
3449
      for instance in self.cfg.GetAllInstancesInfo().values():
3450
        for nic_idx, nic in enumerate(instance.nics):
3451
          params_copy = copy.deepcopy(nic.nicparams)
3452
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3453

    
3454
          # check parameter syntax
3455
          try:
3456
            objects.NIC.CheckParameterSyntax(params_filled)
3457
          except errors.ConfigurationError, err:
3458
            nic_errors.append("Instance %s, nic/%d: %s" %
3459
                              (instance.name, nic_idx, err))
3460

    
3461
          # if we're moving instances to routed, check that they have an ip
3462
          target_mode = params_filled[constants.NIC_MODE]
3463
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3464
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3465
                              " address" % (instance.name, nic_idx))
3466
      if nic_errors:
3467
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3468
                                   "\n".join(nic_errors))
3469

    
3470
    # hypervisor list/parameters
3471
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3472
    if self.op.hvparams:
3473
      for hv_name, hv_dict in self.op.hvparams.items():
3474
        if hv_name not in self.new_hvparams:
3475
          self.new_hvparams[hv_name] = hv_dict
3476
        else:
3477
          self.new_hvparams[hv_name].update(hv_dict)
3478

    
3479
    # os hypervisor parameters
3480
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3481
    if self.op.os_hvp:
3482
      for os_name, hvs in self.op.os_hvp.items():
3483
        if os_name not in self.new_os_hvp:
3484
          self.new_os_hvp[os_name] = hvs
3485
        else:
3486
          for hv_name, hv_dict in hvs.items():
3487
            if hv_name not in self.new_os_hvp[os_name]:
3488
              self.new_os_hvp[os_name][hv_name] = hv_dict
3489
            else:
3490
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3491

    
3492
    # os parameters
3493
    self.new_osp = objects.FillDict(cluster.osparams, {})
3494
    if self.op.osparams:
3495
      for os_name, osp in self.op.osparams.items():
3496
        if os_name not in self.new_osp:
3497
          self.new_osp[os_name] = {}
3498

    
3499
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3500
                                                  use_none=True)
3501

    
3502
        if not self.new_osp[os_name]:
3503
          # we removed all parameters
3504
          del self.new_osp[os_name]
3505
        else:
3506
          # check the parameter validity (remote check)
3507
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3508
                         os_name, self.new_osp[os_name])
3509

    
3510
    # changes to the hypervisor list
3511
    if self.op.enabled_hypervisors is not None:
3512
      self.hv_list = self.op.enabled_hypervisors
3513
      for hv in self.hv_list:
3514
        # if the hypervisor doesn't already exist in the cluster
3515
        # hvparams, we initialize it to empty, and then (in both
3516
        # cases) we make sure to fill the defaults, as we might not
3517
        # have a complete defaults list if the hypervisor wasn't
3518
        # enabled before
3519
        if hv not in new_hvp:
3520
          new_hvp[hv] = {}
3521
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3522
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3523
    else:
3524
      self.hv_list = cluster.enabled_hypervisors
3525

    
3526
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3527
      # either the enabled list has changed, or the parameters have, validate
3528
      for hv_name, hv_params in self.new_hvparams.items():
3529
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3530
            (self.op.enabled_hypervisors and
3531
             hv_name in self.op.enabled_hypervisors)):
3532
          # either this is a new hypervisor, or its parameters have changed
3533
          hv_class = hypervisor.GetHypervisor(hv_name)
3534
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3535
          hv_class.CheckParameterSyntax(hv_params)
3536
          _CheckHVParams(self, node_list, hv_name, hv_params)
3537

    
3538
    if self.op.os_hvp:
3539
      # no need to check any newly-enabled hypervisors, since the
3540
      # defaults have already been checked in the above code-block
3541
      for os_name, os_hvp in self.new_os_hvp.items():
3542
        for hv_name, hv_params in os_hvp.items():
3543
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3544
          # we need to fill in the new os_hvp on top of the actual hv_p
3545
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3546
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3547
          hv_class = hypervisor.GetHypervisor(hv_name)
3548
          hv_class.CheckParameterSyntax(new_osp)
3549
          _CheckHVParams(self, node_list, hv_name, new_osp)
3550

    
3551
    if self.op.default_iallocator:
3552
      alloc_script = utils.FindFile(self.op.default_iallocator,
3553
                                    constants.IALLOCATOR_SEARCH_PATH,
3554
                                    os.path.isfile)
3555
      if alloc_script is None:
3556
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3557
                                   " specified" % self.op.default_iallocator,
3558
                                   errors.ECODE_INVAL)
3559

    
3560
  def Exec(self, feedback_fn):
3561
    """Change the parameters of the cluster.
3562

3563
    """
3564
    if self.op.vg_name is not None:
3565
      new_volume = self.op.vg_name
3566
      if not new_volume:
3567
        new_volume = None
3568
      if new_volume != self.cfg.GetVGName():
3569
        self.cfg.SetVGName(new_volume)
3570
      else:
3571
        feedback_fn("Cluster LVM configuration already in desired"
3572
                    " state, not changing")
3573
    if self.op.drbd_helper is not None:
3574
      new_helper = self.op.drbd_helper
3575
      if not new_helper:
3576
        new_helper = None
3577
      if new_helper != self.cfg.GetDRBDHelper():
3578
        self.cfg.SetDRBDHelper(new_helper)
3579
      else:
3580
        feedback_fn("Cluster DRBD helper already in desired state,"
3581
                    " not changing")
3582
    if self.op.hvparams:
3583
      self.cluster.hvparams = self.new_hvparams
3584
    if self.op.os_hvp:
3585
      self.cluster.os_hvp = self.new_os_hvp
3586
    if self.op.enabled_hypervisors is not None:
3587
      self.cluster.hvparams = self.new_hvparams
3588
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3589
    if self.op.beparams:
3590
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3591
    if self.op.nicparams:
3592
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3593
    if self.op.osparams:
3594
      self.cluster.osparams = self.new_osp
3595
    if self.op.ndparams:
3596
      self.cluster.ndparams = self.new_ndparams
3597

    
3598
    if self.op.candidate_pool_size is not None:
3599
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3600
      # we need to update the pool size here, otherwise the save will fail
3601
      _AdjustCandidatePool(self, [])
3602

    
3603
    if self.op.maintain_node_health is not None:
3604
      self.cluster.maintain_node_health = self.op.maintain_node_health
3605

    
3606
    if self.op.prealloc_wipe_disks is not None:
3607
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3608

    
3609
    if self.op.add_uids is not None:
3610
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3611

    
3612
    if self.op.remove_uids is not None:
3613
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3614

    
3615
    if self.op.uid_pool is not None:
3616
      self.cluster.uid_pool = self.op.uid_pool
3617

    
3618
    if self.op.default_iallocator is not None:
3619
      self.cluster.default_iallocator = self.op.default_iallocator
3620

    
3621
    if self.op.reserved_lvs is not None:
3622
      self.cluster.reserved_lvs = self.op.reserved_lvs
3623

    
3624
    def helper_os(aname, mods, desc):
3625
      desc += " OS list"
3626
      lst = getattr(self.cluster, aname)
3627
      for key, val in mods:
3628
        if key == constants.DDM_ADD:
3629
          if val in lst:
3630
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3631
          else:
3632
            lst.append(val)
3633
        elif key == constants.DDM_REMOVE:
3634
          if val in lst:
3635
            lst.remove(val)
3636
          else:
3637
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3638
        else:
3639
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3640

    
3641
    if self.op.hidden_os:
3642
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3643

    
3644
    if self.op.blacklisted_os:
3645
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3646

    
3647
    if self.op.master_netdev:
3648
      master = self.cfg.GetMasterNode()
3649
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3650
                  self.cluster.master_netdev)
3651
      result = self.rpc.call_node_deactivate_master_ip(master)
3652
      result.Raise("Could not disable the master ip")
3653
      feedback_fn("Changing master_netdev from %s to %s" %
3654
                  (self.cluster.master_netdev, self.op.master_netdev))
3655
      self.cluster.master_netdev = self.op.master_netdev
3656

    
3657
    self.cfg.Update(self.cluster, feedback_fn)
3658

    
3659
    if self.op.master_netdev:
3660
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3661
                  self.op.master_netdev)
3662
      result = self.rpc.call_node_activate_master_ip(master)
3663
      if result.fail_msg:
3664
        self.LogWarning("Could not re-enable the master ip on"
3665
                        " the master, please restart manually: %s",
3666
                        result.fail_msg)
3667

    
3668

    
3669
def _UploadHelper(lu, nodes, fname):
3670
  """Helper for uploading a file and showing warnings.
3671

3672
  """
3673
  if os.path.exists(fname):
3674
    result = lu.rpc.call_upload_file(nodes, fname)
3675
    for to_node, to_result in result.items():
3676
      msg = to_result.fail_msg
3677
      if msg:
3678
        msg = ("Copy of file %s to node %s failed: %s" %
3679
               (fname, to_node, msg))
3680
        lu.proc.LogWarning(msg)
3681

    
3682

    
3683
def _ComputeAncillaryFiles(cluster, redist):
3684
  """Compute files external to Ganeti which need to be consistent.
3685

3686
  @type redist: boolean
3687
  @param redist: Whether to include files which need to be redistributed
3688

3689
  """
3690
  # Compute files for all nodes
3691
  files_all = set([
3692
    constants.SSH_KNOWN_HOSTS_FILE,
3693
    constants.CONFD_HMAC_KEY,
3694
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3695
    ])
3696

    
3697
  if not redist:
3698
    files_all.update(constants.ALL_CERT_FILES)
3699
    files_all.update(ssconf.SimpleStore().GetFileList())
3700

    
3701
  if cluster.modify_etc_hosts:
3702
    files_all.add(constants.ETC_HOSTS)
3703

    
3704
  # Files which must either exist on all nodes or on none
3705
  files_all_opt = set([
3706
    constants.RAPI_USERS_FILE,
3707
    ])
3708

    
3709
  # Files which should only be on master candidates
3710
  files_mc = set()
3711
  if not redist:
3712
    files_mc.add(constants.CLUSTER_CONF_FILE)
3713

    
3714
  # Files which should only be on VM-capable nodes
3715
  files_vm = set(filename
3716
    for hv_name in cluster.enabled_hypervisors
3717
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3718

    
3719
  # Filenames must be unique
3720
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3721
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3722
         "Found file listed in more than one file list"
3723

    
3724
  return (files_all, files_all_opt, files_mc, files_vm)
3725

    
3726

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

3730
  ConfigWriter takes care of distributing the config and ssconf files, but
3731
  there are more files which should be distributed to all nodes. This function
3732
  makes sure those are copied.
3733

3734
  @param lu: calling logical unit
3735
  @param additional_nodes: list of nodes not in the config to distribute to
3736
  @type additional_vm: boolean
3737
  @param additional_vm: whether the additional nodes are vm-capable or not
3738

3739
  """
3740
  # Gather target nodes
3741
  cluster = lu.cfg.GetClusterInfo()
3742
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3743

    
3744
  online_nodes = lu.cfg.GetOnlineNodeList()
3745
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3746

    
3747
  if additional_nodes is not None:
3748
    online_nodes.extend(additional_nodes)
3749
    if additional_vm:
3750
      vm_nodes.extend(additional_nodes)
3751

    
3752
  # Never distribute to master node
3753
  for nodelist in [online_nodes, vm_nodes]:
3754
    if master_info.name in nodelist:
3755
      nodelist.remove(master_info.name)
3756

    
3757
  # Gather file lists
3758
  (files_all, files_all_opt, files_mc, files_vm) = \
3759
    _ComputeAncillaryFiles(cluster, True)
3760

    
3761
  # Never re-distribute configuration file from here
3762
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3763
              constants.CLUSTER_CONF_FILE in files_vm)
3764
  assert not files_mc, "Master candidates not handled in this function"
3765

    
3766
  filemap = [
3767
    (online_nodes, files_all),
3768
    (online_nodes, files_all_opt),
3769
    (vm_nodes, files_vm),
3770
    ]
3771

    
3772
  # Upload the files
3773
  for (node_list, files) in filemap:
3774
    for fname in files:
3775
      _UploadHelper(lu, node_list, fname)
3776

    
3777

    
3778
class LUClusterRedistConf(NoHooksLU):
3779
  """Force the redistribution of cluster configuration.
3780

3781
  This is a very simple LU.
3782

3783
  """
3784
  REQ_BGL = False
3785

    
3786
  def ExpandNames(self):
3787
    self.needed_locks = {
3788
      locking.LEVEL_NODE: locking.ALL_SET,
3789
    }
3790
    self.share_locks[locking.LEVEL_NODE] = 1
3791

    
3792
  def Exec(self, feedback_fn):
3793
    """Redistribute the configuration.
3794

3795
    """
3796
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3797
    _RedistributeAncillaryFiles(self)
3798

    
3799

    
3800
class LUClusterActivateMasterIp(NoHooksLU):
3801
  """Activate the master IP on the master node.
3802

3803
  """
3804
  def Exec(self, feedback_fn):
3805
    """Activate the master IP.
3806

3807
    """
3808
    master = self.cfg.GetMasterNode()
3809
    self.rpc.call_node_activate_master_ip(master)
3810

    
3811

    
3812
class LUClusterDeactivateMasterIp(NoHooksLU):
3813
  """Deactivate the master IP on the master node.
3814

3815
  """
3816
  def Exec(self, feedback_fn):
3817
    """Deactivate the master IP.
3818

3819
    """
3820
    master = self.cfg.GetMasterNode()
3821
    self.rpc.call_node_deactivate_master_ip(master)
3822

    
3823

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

3827
  """
3828
  if not instance.disks or disks is not None and not disks:
3829
    return True
3830

    
3831
  disks = _ExpandCheckDisks(instance, disks)
3832

    
3833
  if not oneshot:
3834
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3835

    
3836
  node = instance.primary_node
3837

    
3838
  for dev in disks:
3839
    lu.cfg.SetDiskID(dev, node)
3840

    
3841
  # TODO: Convert to utils.Retry
3842

    
3843
  retries = 0
3844
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3845
  while True:
3846
    max_time = 0
3847
    done = True
3848
    cumul_degraded = False
3849
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3850
    msg = rstats.fail_msg
3851
    if msg:
3852
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3853
      retries += 1
3854
      if retries >= 10:
3855
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3856
                                 " aborting." % node)
3857
      time.sleep(6)
3858
      continue
3859
    rstats = rstats.payload
3860
    retries = 0
3861
    for i, mstat in enumerate(rstats):
3862
      if mstat is None:
3863
        lu.LogWarning("Can't compute data for node %s/%s",
3864
                           node, disks[i].iv_name)
3865
        continue
3866

    
3867
      cumul_degraded = (cumul_degraded or
3868
                        (mstat.is_degraded and mstat.sync_percent is None))
3869
      if mstat.sync_percent is not None:
3870
        done = False
3871
        if mstat.estimated_time is not None:
3872
          rem_time = ("%s remaining (estimated)" %
3873
                      utils.FormatSeconds(mstat.estimated_time))
3874
          max_time = mstat.estimated_time
3875
        else:
3876
          rem_time = "no time estimate"
3877
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3878
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3879

    
3880
    # if we're done but degraded, let's do a few small retries, to
3881
    # make sure we see a stable and not transient situation; therefore
3882
    # we force restart of the loop
3883
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3884
      logging.info("Degraded disks found, %d retries left", degr_retries)
3885
      degr_retries -= 1
3886
      time.sleep(1)
3887
      continue
3888

    
3889
    if done or oneshot:
3890
      break
3891

    
3892
    time.sleep(min(60, max_time))
3893

    
3894
  if done:
3895
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3896
  return not cumul_degraded
3897

    
3898

    
3899
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3900
  """Check that mirrors are not degraded.
3901

3902
  The ldisk parameter, if True, will change the test from the
3903
  is_degraded attribute (which represents overall non-ok status for
3904
  the device(s)) to the ldisk (representing the local storage status).
3905

3906
  """
3907
  lu.cfg.SetDiskID(dev, node)
3908

    
3909
  result = True
3910

    
3911
  if on_primary or dev.AssembleOnSecondary():
3912
    rstats = lu.rpc.call_blockdev_find(node, dev)
3913
    msg = rstats.fail_msg
3914
    if msg:
3915
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3916
      result = False
3917
    elif not rstats.payload:
3918
      lu.LogWarning("Can't find disk on node %s", node)
3919
      result = False
3920
    else:
3921
      if ldisk:
3922
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3923
      else:
3924
        result = result and not rstats.payload.is_degraded
3925

    
3926
  if dev.children:
3927
    for child in dev.children:
3928
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3929

    
3930
  return result
3931

    
3932

    
3933
class LUOobCommand(NoHooksLU):
3934
  """Logical unit for OOB handling.
3935

3936
  """
3937
  REG_BGL = False
3938
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3939

    
3940
  def ExpandNames(self):
3941
    """Gather locks we need.
3942

3943
    """
3944
    if self.op.node_names:
3945
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3946
      lock_names = self.op.node_names
3947
    else:
3948
      lock_names = locking.ALL_SET
3949

    
3950
    self.needed_locks = {
3951
      locking.LEVEL_NODE: lock_names,
3952
      }
3953

    
3954
  def CheckPrereq(self):
3955
    """Check prerequisites.
3956

3957
    This checks:
3958
     - the node exists in the configuration
3959
     - OOB is supported
3960

3961
    Any errors are signaled by raising errors.OpPrereqError.
3962

3963
    """
3964
    self.nodes = []
3965
    self.master_node = self.cfg.GetMasterNode()
3966

    
3967
    assert self.op.power_delay >= 0.0
3968

    
3969
    if self.op.node_names:
3970
      if (self.op.command in self._SKIP_MASTER and
3971
          self.master_node in self.op.node_names):
3972
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3973
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3974

    
3975
        if master_oob_handler:
3976
          additional_text = ("run '%s %s %s' if you want to operate on the"
3977
                             " master regardless") % (master_oob_handler,
3978
                                                      self.op.command,
3979
                                                      self.master_node)
3980
        else:
3981
          additional_text = "it does not support out-of-band operations"
3982

    
3983
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3984
                                    " allowed for %s; %s") %
3985
                                   (self.master_node, self.op.command,
3986
                                    additional_text), errors.ECODE_INVAL)
3987
    else:
3988
      self.op.node_names = self.cfg.GetNodeList()
3989
      if self.op.command in self._SKIP_MASTER:
3990
        self.op.node_names.remove(self.master_node)
3991

    
3992
    if self.op.command in self._SKIP_MASTER:
3993
      assert self.master_node not in self.op.node_names
3994

    
3995
    for (node_name, node) in self.cfg.GetMultiNodeInfo(self.op.node_names):
3996
      if node is None:
3997
        raise errors.OpPrereqError("Node %s not found" % node_name,
3998
                                   errors.ECODE_NOENT)
3999
      else:
4000
        self.nodes.append(node)
4001

    
4002
      if (not self.op.ignore_status and
4003
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
4004
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
4005
                                    " not marked offline") % node_name,
4006
                                   errors.ECODE_STATE)
4007

    
4008
  def Exec(self, feedback_fn):
4009
    """Execute OOB and return result if we expect any.
4010

4011
    """
4012
    master_node = self.master_node
4013
    ret = []
4014

    
4015
    for idx, node in enumerate(utils.NiceSort(self.nodes,
4016
                                              key=lambda node: node.name)):
4017
      node_entry = [(constants.RS_NORMAL, node.name)]
4018
      ret.append(node_entry)
4019

    
4020
      oob_program = _SupportsOob(self.cfg, node)
4021

    
4022
      if not oob_program:
4023
        node_entry.append((constants.RS_UNAVAIL, None))
4024
        continue
4025

    
4026
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
4027
                   self.op.command, oob_program, node.name)
4028
      result = self.rpc.call_run_oob(master_node, oob_program,
4029
                                     self.op.command, node.name,
4030
                                     self.op.timeout)
4031

    
4032
      if result.fail_msg:
4033
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
4034
                        node.name, result.fail_msg)
4035
        node_entry.append((constants.RS_NODATA, None))
4036
      else:
4037
        try:
4038
          self._CheckPayload(result)
4039
        except errors.OpExecError, err:
4040
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
4041
                          node.name, err)
4042
          node_entry.append((constants.RS_NODATA, None))
4043
        else:
4044
          if self.op.command == constants.OOB_HEALTH:
4045
            # For health we should log important events
4046
            for item, status in result.payload:
4047
              if status in [constants.OOB_STATUS_WARNING,
4048
                            constants.OOB_STATUS_CRITICAL]:
4049
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
4050
                                item, node.name, status)
4051

    
4052
          if self.op.command == constants.OOB_POWER_ON:
4053
            node.powered = True
4054
          elif self.op.command == constants.OOB_POWER_OFF:
4055
            node.powered = False
4056
          elif self.op.command == constants.OOB_POWER_STATUS:
4057
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
4058
            if powered != node.powered:
4059
              logging.warning(("Recorded power state (%s) of node '%s' does not"
4060
                               " match actual power state (%s)"), node.powered,
4061
                              node.name, powered)
4062

    
4063
          # For configuration changing commands we should update the node
4064
          if self.op.command in (constants.OOB_POWER_ON,
4065
                                 constants.OOB_POWER_OFF):
4066
            self.cfg.Update(node, feedback_fn)
4067

    
4068
          node_entry.append((constants.RS_NORMAL, result.payload))
4069

    
4070
          if (self.op.command == constants.OOB_POWER_ON and
4071
              idx < len(self.nodes) - 1):
4072
            time.sleep(self.op.power_delay)
4073

    
4074
    return ret
4075

    
4076
  def _CheckPayload(self, result):
4077
    """Checks if the payload is valid.
4078

4079
    @param result: RPC result
4080
    @raises errors.OpExecError: If payload is not valid
4081

4082
    """
4083
    errs = []
4084
    if self.op.command == constants.OOB_HEALTH:
4085
      if not isinstance(result.payload, list):
4086
        errs.append("command 'health' is expected to return a list but got %s" %
4087
                    type(result.payload))
4088
      else:
4089
        for item, status in result.payload:
4090
          if status not in constants.OOB_STATUSES:
4091
            errs.append("health item '%s' has invalid status '%s'" %
4092
                        (item, status))
4093

    
4094
    if self.op.command == constants.OOB_POWER_STATUS:
4095
      if not isinstance(result.payload, dict):
4096
        errs.append("power-status is expected to return a dict but got %s" %
4097
                    type(result.payload))
4098

    
4099
    if self.op.command in [
4100
        constants.OOB_POWER_ON,
4101
        constants.OOB_POWER_OFF,
4102
        constants.OOB_POWER_CYCLE,
4103
        ]:
4104
      if result.payload is not None:
4105
        errs.append("%s is expected to not return payload but got '%s'" %
4106
                    (self.op.command, result.payload))
4107

    
4108
    if errs:
4109
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
4110
                               utils.CommaJoin(errs))
4111

    
4112

    
4113
class _OsQuery(_QueryBase):
4114
  FIELDS = query.OS_FIELDS
4115

    
4116
  def ExpandNames(self, lu):
4117
    # Lock all nodes in shared mode
4118
    # Temporary removal of locks, should be reverted later
4119
    # TODO: reintroduce locks when they are lighter-weight
4120
    lu.needed_locks = {}
4121
    #self.share_locks[locking.LEVEL_NODE] = 1
4122
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4123

    
4124
    # The following variables interact with _QueryBase._GetNames
4125
    if self.names:
4126
      self.wanted = self.names
4127
    else:
4128
      self.wanted = locking.ALL_SET
4129

    
4130
    self.do_locking = self.use_locking
4131

    
4132
  def DeclareLocks(self, lu, level):
4133
    pass
4134

    
4135
  @staticmethod
4136
  def _DiagnoseByOS(rlist):
4137
    """Remaps a per-node return list into an a per-os per-node dictionary
4138

4139
    @param rlist: a map with node names as keys and OS objects as values
4140

4141
    @rtype: dict
4142
    @return: a dictionary with osnames as keys and as value another
4143
        map, with nodes as keys and tuples of (path, status, diagnose,
4144
        variants, parameters, api_versions) as values, eg::
4145

4146
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
4147
                                     (/srv/..., False, "invalid api")],
4148
                           "node2": [(/srv/..., True, "", [], [])]}
4149
          }
4150

4151
    """
4152
    all_os = {}
4153
    # we build here the list of nodes that didn't fail the RPC (at RPC
4154
    # level), so that nodes with a non-responding node daemon don't
4155
    # make all OSes invalid
4156
    good_nodes = [node_name for node_name in rlist
4157
                  if not rlist[node_name].fail_msg]
4158
    for node_name, nr in rlist.items():
4159
      if nr.fail_msg or not nr.payload:
4160
        continue
4161
      for (name, path, status, diagnose, variants,
4162
           params, api_versions) in nr.payload:
4163
        if name not in all_os:
4164
          # build a list of nodes for this os containing empty lists
4165
          # for each node in node_list
4166
          all_os[name] = {}
4167
          for nname in good_nodes:
4168
            all_os[name][nname] = []
4169
        # convert params from [name, help] to (name, help)
4170
        params = [tuple(v) for v in params]
4171
        all_os[name][node_name].append((path, status, diagnose,
4172
                                        variants, params, api_versions))
4173
    return all_os
4174

    
4175
  def _GetQueryData(self, lu):
4176
    """Computes the list of nodes and their attributes.
4177

4178
    """
4179
    # Locking is not used
4180
    assert not (compat.any(lu.glm.is_owned(level)
4181
                           for level in locking.LEVELS
4182
                           if level != locking.LEVEL_CLUSTER) or
4183
                self.do_locking or self.use_locking)
4184

    
4185
    valid_nodes = [node.name
4186
                   for node in lu.cfg.GetAllNodesInfo().values()
4187
                   if not node.offline and node.vm_capable]
4188
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
4189
    cluster = lu.cfg.GetClusterInfo()
4190

    
4191
    data = {}
4192

    
4193
    for (os_name, os_data) in pol.items():
4194
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
4195
                          hidden=(os_name in cluster.hidden_os),
4196
                          blacklisted=(os_name in cluster.blacklisted_os))
4197

    
4198
      variants = set()
4199
      parameters = set()
4200
      api_versions = set()
4201

    
4202
      for idx, osl in enumerate(os_data.values()):
4203
        info.valid = bool(info.valid and osl and osl[0][1])
4204
        if not info.valid:
4205
          break
4206

    
4207
        (node_variants, node_params, node_api) = osl[0][3:6]
4208
        if idx == 0:
4209
          # First entry
4210
          variants.update(node_variants)
4211
          parameters.update(node_params)
4212
          api_versions.update(node_api)
4213
        else:
4214
          # Filter out inconsistent values
4215
          variants.intersection_update(node_variants)
4216
          parameters.intersection_update(node_params)
4217
          api_versions.intersection_update(node_api)
4218

    
4219
      info.variants = list(variants)
4220
      info.parameters = list(parameters)
4221
      info.api_versions = list(api_versions)
4222

    
4223
      data[os_name] = info
4224

    
4225
    # Prepare data in requested order
4226
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
4227
            if name in data]
4228

    
4229

    
4230
class LUOsDiagnose(NoHooksLU):
4231
  """Logical unit for OS diagnose/query.
4232

4233
  """
4234
  REQ_BGL = False
4235

    
4236
  @staticmethod
4237
  def _BuildFilter(fields, names):
4238
    """Builds a filter for querying OSes.
4239

4240
    """
4241
    name_filter = qlang.MakeSimpleFilter("name", names)
4242

    
4243
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
4244
    # respective field is not requested
4245
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
4246
                     for fname in ["hidden", "blacklisted"]
4247
                     if fname not in fields]
4248
    if "valid" not in fields:
4249
      status_filter.append([qlang.OP_TRUE, "valid"])
4250

    
4251
    if status_filter:
4252
      status_filter.insert(0, qlang.OP_AND)
4253
    else:
4254
      status_filter = None
4255

    
4256
    if name_filter and status_filter:
4257
      return [qlang.OP_AND, name_filter, status_filter]
4258
    elif name_filter:
4259
      return name_filter
4260
    else:
4261
      return status_filter
4262

    
4263
  def CheckArguments(self):
4264
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
4265
                       self.op.output_fields, False)
4266

    
4267
  def ExpandNames(self):
4268
    self.oq.ExpandNames(self)
4269

    
4270
  def Exec(self, feedback_fn):
4271
    return self.oq.OldStyleQuery(self)
4272

    
4273

    
4274
class LUNodeRemove(LogicalUnit):
4275
  """Logical unit for removing a node.
4276

4277
  """
4278
  HPATH = "node-remove"
4279
  HTYPE = constants.HTYPE_NODE
4280

    
4281
  def BuildHooksEnv(self):
4282
    """Build hooks env.
4283

4284
    This doesn't run on the target node in the pre phase as a failed
4285
    node would then be impossible to remove.
4286

4287
    """
4288
    return {
4289
      "OP_TARGET": self.op.node_name,
4290
      "NODE_NAME": self.op.node_name,
4291
      }
4292

    
4293
  def BuildHooksNodes(self):
4294
    """Build hooks nodes.
4295

4296
    """
4297
    all_nodes = self.cfg.GetNodeList()
4298
    try:
4299
      all_nodes.remove(self.op.node_name)
4300
    except ValueError:
4301
      logging.warning("Node '%s', which is about to be removed, was not found"
4302
                      " in the list of all nodes", self.op.node_name)
4303
    return (all_nodes, all_nodes)
4304

    
4305
  def CheckPrereq(self):
4306
    """Check prerequisites.
4307

4308
    This checks:
4309
     - the node exists in the configuration
4310
     - it does not have primary or secondary instances
4311
     - it's not the master
4312

4313
    Any errors are signaled by raising errors.OpPrereqError.
4314

4315
    """
4316
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4317
    node = self.cfg.GetNodeInfo(self.op.node_name)
4318
    assert node is not None
4319

    
4320
    masternode = self.cfg.GetMasterNode()
4321
    if node.name == masternode:
4322
      raise errors.OpPrereqError("Node is the master node, failover to another"
4323
                                 " node is required", errors.ECODE_INVAL)
4324

    
4325
    for instance_name, instance in self.cfg.GetAllInstancesInfo():
4326
      if node.name in instance.all_nodes:
4327
        raise errors.OpPrereqError("Instance %s is still running on the node,"
4328
                                   " please remove first" % instance_name,
4329
                                   errors.ECODE_INVAL)
4330
    self.op.node_name = node.name
4331
    self.node = node
4332

    
4333
  def Exec(self, feedback_fn):
4334
    """Removes the node from the cluster.
4335

4336
    """
4337
    node = self.node
4338
    logging.info("Stopping the node daemon and removing configs from node %s",
4339
                 node.name)
4340

    
4341
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
4342

    
4343
    # Promote nodes to master candidate as needed
4344
    _AdjustCandidatePool(self, exceptions=[node.name])
4345
    self.context.RemoveNode(node.name)
4346

    
4347
    # Run post hooks on the node before it's removed
4348
    _RunPostHook(self, node.name)
4349

    
4350
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
4351
    msg = result.fail_msg
4352
    if msg:
4353
      self.LogWarning("Errors encountered on the remote node while leaving"
4354
                      " the cluster: %s", msg)
4355

    
4356
    # Remove node from our /etc/hosts
4357
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4358
      master_node = self.cfg.GetMasterNode()
4359
      result = self.rpc.call_etc_hosts_modify(master_node,
4360
                                              constants.ETC_HOSTS_REMOVE,
4361
                                              node.name, None)
4362
      result.Raise("Can't update hosts file with new host data")
4363
      _RedistributeAncillaryFiles(self)
4364

    
4365

    
4366
class _NodeQuery(_QueryBase):
4367
  FIELDS = query.NODE_FIELDS
4368

    
4369
  def ExpandNames(self, lu):
4370
    lu.needed_locks = {}
4371
    lu.share_locks = _ShareAll()
4372

    
4373
    if self.names:
4374
      self.wanted = _GetWantedNodes(lu, self.names)
4375
    else:
4376
      self.wanted = locking.ALL_SET
4377

    
4378
    self.do_locking = (self.use_locking and
4379
                       query.NQ_LIVE in self.requested_data)
4380

    
4381
    if self.do_locking:
4382
      # If any non-static field is requested we need to lock the nodes
4383
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
4384

    
4385
  def DeclareLocks(self, lu, level):
4386
    pass
4387

    
4388
  def _GetQueryData(self, lu):
4389
    """Computes the list of nodes and their attributes.
4390

4391
    """
4392
    all_info = lu.cfg.GetAllNodesInfo()
4393

    
4394
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
4395

    
4396
    # Gather data as requested
4397
    if query.NQ_LIVE in self.requested_data:
4398
      # filter out non-vm_capable nodes
4399
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
4400

    
4401
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
4402
                                        lu.cfg.GetHypervisorType())
4403
      live_data = dict((name, nresult.payload)
4404
                       for (name, nresult) in node_data.items()
4405
                       if not nresult.fail_msg and nresult.payload)
4406
    else:
4407
      live_data = None
4408

    
4409
    if query.NQ_INST in self.requested_data:
4410
      node_to_primary = dict([(name, set()) for name in nodenames])
4411
      node_to_secondary = dict([(name, set()) for name in nodenames])
4412

    
4413
      inst_data = lu.cfg.GetAllInstancesInfo()
4414

    
4415
      for inst in inst_data.values():
4416
        if inst.primary_node in node_to_primary:
4417
          node_to_primary[inst.primary_node].add(inst.name)
4418
        for secnode in inst.secondary_nodes:
4419
          if secnode in node_to_secondary:
4420
            node_to_secondary[secnode].add(inst.name)
4421
    else:
4422
      node_to_primary = None
4423
      node_to_secondary = None
4424

    
4425
    if query.NQ_OOB in self.requested_data:
4426
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
4427
                         for name, node in all_info.iteritems())
4428
    else:
4429
      oob_support = None
4430

    
4431
    if query.NQ_GROUP in self.requested_data:
4432
      groups = lu.cfg.GetAllNodeGroupsInfo()
4433
    else:
4434
      groups = {}
4435

    
4436
    return query.NodeQueryData([all_info[name] for name in nodenames],
4437
                               live_data, lu.cfg.GetMasterNode(),
4438
                               node_to_primary, node_to_secondary, groups,
4439
                               oob_support, lu.cfg.GetClusterInfo())
4440

    
4441

    
4442
class LUNodeQuery(NoHooksLU):
4443
  """Logical unit for querying nodes.
4444

4445
  """
4446
  # pylint: disable=W0142
4447
  REQ_BGL = False
4448

    
4449
  def CheckArguments(self):
4450
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4451
                         self.op.output_fields, self.op.use_locking)
4452

    
4453
  def ExpandNames(self):
4454
    self.nq.ExpandNames(self)
4455

    
4456
  def Exec(self, feedback_fn):
4457
    return self.nq.OldStyleQuery(self)
4458

    
4459

    
4460
class LUNodeQueryvols(NoHooksLU):
4461
  """Logical unit for getting volumes on node(s).
4462

4463
  """
4464
  REQ_BGL = False
4465
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4466
  _FIELDS_STATIC = utils.FieldSet("node")
4467

    
4468
  def CheckArguments(self):
4469
    _CheckOutputFields(static=self._FIELDS_STATIC,
4470
                       dynamic=self._FIELDS_DYNAMIC,
4471
                       selected=self.op.output_fields)
4472

    
4473
  def ExpandNames(self):
4474
    self.needed_locks = {}
4475
    self.share_locks[locking.LEVEL_NODE] = 1
4476
    if not self.op.nodes:
4477
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4478
    else:
4479
      self.needed_locks[locking.LEVEL_NODE] = \
4480
        _GetWantedNodes(self, self.op.nodes)
4481

    
4482
  def Exec(self, feedback_fn):
4483
    """Computes the list of nodes and their attributes.
4484

4485
    """
4486
    nodenames = self.owned_locks(locking.LEVEL_NODE)
4487
    volumes = self.rpc.call_node_volumes(nodenames)
4488

    
4489
    ilist = self.cfg.GetAllInstancesInfo()
4490
    vol2inst = _MapInstanceDisksToNodes(ilist.values())
4491

    
4492
    output = []
4493
    for node in nodenames:
4494
      nresult = volumes[node]
4495
      if nresult.offline:
4496
        continue
4497
      msg = nresult.fail_msg
4498
      if msg:
4499
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4500
        continue
4501

    
4502
      node_vols = sorted(nresult.payload,
4503
                         key=operator.itemgetter("dev"))
4504

    
4505
      for vol in node_vols:
4506
        node_output = []
4507
        for field in self.op.output_fields:
4508
          if field == "node":
4509
            val = node
4510
          elif field == "phys":
4511
            val = vol["dev"]
4512
          elif field == "vg":
4513
            val = vol["vg"]
4514
          elif field == "name":
4515
            val = vol["name"]
4516
          elif field == "size":
4517
            val = int(float(vol["size"]))
4518
          elif field == "instance":
4519
            val = vol2inst.get((node, vol["vg"] + "/" + vol["name"]), "-")
4520
          else:
4521
            raise errors.ParameterError(field)
4522
          node_output.append(str(val))
4523

    
4524
        output.append(node_output)
4525

    
4526
    return output
4527

    
4528

    
4529
class LUNodeQueryStorage(NoHooksLU):
4530
  """Logical unit for getting information on storage units on node(s).
4531

4532
  """
4533
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4534
  REQ_BGL = False
4535

    
4536
  def CheckArguments(self):
4537
    _CheckOutputFields(static=self._FIELDS_STATIC,
4538
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4539
                       selected=self.op.output_fields)
4540

    
4541
  def ExpandNames(self):
4542
    self.needed_locks = {}
4543
    self.share_locks[locking.LEVEL_NODE] = 1
4544

    
4545
    if self.op.nodes:
4546
      self.needed_locks[locking.LEVEL_NODE] = \
4547
        _GetWantedNodes(self, self.op.nodes)
4548
    else:
4549
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4550

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

4554
    """
4555
    self.nodes = self.owned_locks(locking.LEVEL_NODE)
4556

    
4557
    # Always get name to sort by
4558
    if constants.SF_NAME in self.op.output_fields:
4559
      fields = self.op.output_fields[:]
4560
    else:
4561
      fields = [constants.SF_NAME] + self.op.output_fields
4562

    
4563
    # Never ask for node or type as it's only known to the LU
4564
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4565
      while extra in fields:
4566
        fields.remove(extra)
4567

    
4568
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4569
    name_idx = field_idx[constants.SF_NAME]
4570

    
4571
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4572
    data = self.rpc.call_storage_list(self.nodes,
4573
                                      self.op.storage_type, st_args,
4574
                                      self.op.name, fields)
4575

    
4576
    result = []
4577

    
4578
    for node in utils.NiceSort(self.nodes):
4579
      nresult = data[node]
4580
      if nresult.offline:
4581
        continue
4582

    
4583
      msg = nresult.fail_msg
4584
      if msg:
4585
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4586
        continue
4587

    
4588
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4589

    
4590
      for name in utils.NiceSort(rows.keys()):
4591
        row = rows[name]
4592

    
4593
        out = []
4594

    
4595
        for field in self.op.output_fields:
4596
          if field == constants.SF_NODE:
4597
            val = node
4598
          elif field == constants.SF_TYPE:
4599
            val = self.op.storage_type
4600
          elif field in field_idx:
4601
            val = row[field_idx[field]]
4602
          else:
4603
            raise errors.ParameterError(field)
4604

    
4605
          out.append(val)
4606

    
4607
        result.append(out)
4608

    
4609
    return result
4610

    
4611

    
4612
class _InstanceQuery(_QueryBase):
4613
  FIELDS = query.INSTANCE_FIELDS
4614

    
4615
  def ExpandNames(self, lu):
4616
    lu.needed_locks = {}
4617
    lu.share_locks = _ShareAll()
4618

    
4619
    if self.names:
4620
      self.wanted = _GetWantedInstances(lu, self.names)
4621
    else:
4622
      self.wanted = locking.ALL_SET
4623

    
4624
    self.do_locking = (self.use_locking and
4625
                       query.IQ_LIVE in self.requested_data)
4626
    if self.do_locking:
4627
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4628
      lu.needed_locks[locking.LEVEL_NODEGROUP] = []
4629
      lu.needed_locks[locking.LEVEL_NODE] = []
4630
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4631

    
4632
    self.do_grouplocks = (self.do_locking and
4633
                          query.IQ_NODES in self.requested_data)
4634

    
4635
  def DeclareLocks(self, lu, level):
4636
    if self.do_locking:
4637
      if level == locking.LEVEL_NODEGROUP and self.do_grouplocks:
4638
        assert not lu.needed_locks[locking.LEVEL_NODEGROUP]
4639

    
4640
        # Lock all groups used by instances optimistically; this requires going
4641
        # via the node before it's locked, requiring verification later on
4642
        lu.needed_locks[locking.LEVEL_NODEGROUP] = \
4643
          set(group_uuid
4644
              for instance_name in lu.owned_locks(locking.LEVEL_INSTANCE)
4645
              for group_uuid in lu.cfg.GetInstanceNodeGroups(instance_name))
4646
      elif level == locking.LEVEL_NODE:
4647
        lu._LockInstancesNodes() # pylint: disable=W0212
4648

    
4649
  @staticmethod
4650
  def _CheckGroupLocks(lu):
4651
    owned_instances = frozenset(lu.owned_locks(locking.LEVEL_INSTANCE))
4652
    owned_groups = frozenset(lu.owned_locks(locking.LEVEL_NODEGROUP))
4653

    
4654
    # Check if node groups for locked instances are still correct
4655
    for instance_name in owned_instances:
4656
      _CheckInstanceNodeGroups(lu.cfg, instance_name, owned_groups)
4657

    
4658
  def _GetQueryData(self, lu):
4659
    """Computes the list of instances and their attributes.
4660

4661
    """
4662
    if self.do_grouplocks:
4663
      self._CheckGroupLocks(lu)
4664

    
4665
    cluster = lu.cfg.GetClusterInfo()
4666
    all_info = lu.cfg.GetAllInstancesInfo()
4667

    
4668
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4669

    
4670
    instance_list = [all_info[name] for name in instance_names]
4671
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4672
                                        for inst in instance_list)))
4673
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4674
    bad_nodes = []
4675
    offline_nodes = []
4676
    wrongnode_inst = set()
4677

    
4678
    # Gather data as requested
4679
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4680
      live_data = {}
4681
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4682
      for name in nodes:
4683
        result = node_data[name]
4684
        if result.offline:
4685
          # offline nodes will be in both lists
4686
          assert result.fail_msg
4687
          offline_nodes.append(name)
4688
        if result.fail_msg:
4689
          bad_nodes.append(name)
4690
        elif result.payload:
4691
          for inst in result.payload:
4692
            if inst in all_info:
4693
              if all_info[inst].primary_node == name:
4694
                live_data.update(result.payload)
4695
              else:
4696
                wrongnode_inst.add(inst)
4697
            else:
4698
              # orphan instance; we don't list it here as we don't
4699
              # handle this case yet in the output of instance listing
4700
              logging.warning("Orphan instance '%s' found on node %s",
4701
                              inst, name)
4702
        # else no instance is alive
4703
    else:
4704
      live_data = {}
4705

    
4706
    if query.IQ_DISKUSAGE in self.requested_data:
4707
      disk_usage = dict((inst.name,
4708
                         _ComputeDiskSize(inst.disk_template,
4709
                                          [{constants.IDISK_SIZE: disk.size}
4710
                                           for disk in inst.disks]))
4711
                        for inst in instance_list)
4712
    else:
4713
      disk_usage = None
4714

    
4715
    if query.IQ_CONSOLE in self.requested_data:
4716
      consinfo = {}
4717
      for inst in instance_list:
4718
        if inst.name in live_data:
4719
          # Instance is running
4720
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4721
        else:
4722
          consinfo[inst.name] = None
4723
      assert set(consinfo.keys()) == set(instance_names)
4724
    else:
4725
      consinfo = None
4726

    
4727
    if query.IQ_NODES in self.requested_data:
4728
      node_names = set(itertools.chain(*map(operator.attrgetter("all_nodes"),
4729
                                            instance_list)))
4730
      nodes = dict(lu.cfg.GetMultiNodeInfo(node_names))
4731
      groups = dict((uuid, lu.cfg.GetNodeGroup(uuid))
4732
                    for uuid in set(map(operator.attrgetter("group"),
4733
                                        nodes.values())))
4734
    else:
4735
      nodes = None
4736
      groups = None
4737

    
4738
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4739
                                   disk_usage, offline_nodes, bad_nodes,
4740
                                   live_data, wrongnode_inst, consinfo,
4741
                                   nodes, groups)
4742

    
4743

    
4744
class LUQuery(NoHooksLU):
4745
  """Query for resources/items of a certain kind.
4746

4747
  """
4748
  # pylint: disable=W0142
4749
  REQ_BGL = False
4750

    
4751
  def CheckArguments(self):
4752
    qcls = _GetQueryImplementation(self.op.what)
4753

    
4754
    self.impl = qcls(self.op.filter, self.op.fields, self.op.use_locking)
4755

    
4756
  def ExpandNames(self):
4757
    self.impl.ExpandNames(self)
4758

    
4759
  def DeclareLocks(self, level):
4760
    self.impl.DeclareLocks(self, level)
4761

    
4762
  def Exec(self, feedback_fn):
4763
    return self.impl.NewStyleQuery(self)
4764

    
4765

    
4766
class LUQueryFields(NoHooksLU):
4767
  """Query for resources/items of a certain kind.
4768

4769
  """
4770
  # pylint: disable=W0142
4771
  REQ_BGL = False
4772

    
4773
  def CheckArguments(self):
4774
    self.qcls = _GetQueryImplementation(self.op.what)
4775

    
4776
  def ExpandNames(self):
4777
    self.needed_locks = {}
4778

    
4779
  def Exec(self, feedback_fn):
4780
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4781

    
4782

    
4783
class LUNodeModifyStorage(NoHooksLU):
4784
  """Logical unit for modifying a storage volume on a node.
4785

4786
  """
4787
  REQ_BGL = False
4788

    
4789
  def CheckArguments(self):
4790
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4791

    
4792
    storage_type = self.op.storage_type
4793

    
4794
    try:
4795
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4796
    except KeyError:
4797
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4798
                                 " modified" % storage_type,
4799
                                 errors.ECODE_INVAL)
4800

    
4801
    diff = set(self.op.changes.keys()) - modifiable
4802
    if diff:
4803
      raise errors.OpPrereqError("The following fields can not be modified for"
4804
                                 " storage units of type '%s': %r" %
4805
                                 (storage_type, list(diff)),
4806
                                 errors.ECODE_INVAL)
4807

    
4808
  def ExpandNames(self):
4809
    self.needed_locks = {
4810
      locking.LEVEL_NODE: self.op.node_name,
4811
      }
4812

    
4813
  def Exec(self, feedback_fn):
4814
    """Computes the list of nodes and their attributes.
4815

4816
    """
4817
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4818
    result = self.rpc.call_storage_modify(self.op.node_name,
4819
                                          self.op.storage_type, st_args,
4820
                                          self.op.name, self.op.changes)
4821
    result.Raise("Failed to modify storage unit '%s' on %s" %
4822
                 (self.op.name, self.op.node_name))
4823

    
4824

    
4825
class LUNodeAdd(LogicalUnit):
4826
  """Logical unit for adding node to the cluster.
4827

4828
  """
4829
  HPATH = "node-add"
4830
  HTYPE = constants.HTYPE_NODE
4831
  _NFLAGS = ["master_capable", "vm_capable"]
4832

    
4833
  def CheckArguments(self):
4834
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4835
    # validate/normalize the node name
4836
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4837
                                         family=self.primary_ip_family)
4838
    self.op.node_name = self.hostname.name
4839

    
4840
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4841
      raise errors.OpPrereqError("Cannot readd the master node",
4842
                                 errors.ECODE_STATE)
4843

    
4844
    if self.op.readd and self.op.group:
4845
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4846
                                 " being readded", errors.ECODE_INVAL)
4847

    
4848
  def BuildHooksEnv(self):
4849
    """Build hooks env.
4850

4851
    This will run on all nodes before, and on all nodes + the new node after.
4852

4853
    """
4854
    return {
4855
      "OP_TARGET": self.op.node_name,
4856
      "NODE_NAME": self.op.node_name,
4857
      "NODE_PIP": self.op.primary_ip,
4858
      "NODE_SIP": self.op.secondary_ip,
4859
      "MASTER_CAPABLE": str(self.op.master_capable),
4860
      "VM_CAPABLE": str(self.op.vm_capable),
4861
      }
4862

    
4863
  def BuildHooksNodes(self):
4864
    """Build hooks nodes.
4865

4866
    """
4867
    # Exclude added node
4868
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4869
    post_nodes = pre_nodes + [self.op.node_name, ]
4870

    
4871
    return (pre_nodes, post_nodes)
4872

    
4873
  def CheckPrereq(self):
4874
    """Check prerequisites.
4875

4876
    This checks:
4877
     - the new node is not already in the config
4878
     - it is resolvable
4879
     - its parameters (single/dual homed) matches the cluster
4880

4881
    Any errors are signaled by raising errors.OpPrereqError.
4882

4883
    """
4884
    cfg = self.cfg
4885
    hostname = self.hostname
4886
    node = hostname.name
4887
    primary_ip = self.op.primary_ip = hostname.ip
4888
    if self.op.secondary_ip is None:
4889
      if self.primary_ip_family == netutils.IP6Address.family:
4890
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4891
                                   " IPv4 address must be given as secondary",
4892
                                   errors.ECODE_INVAL)
4893
      self.op.secondary_ip = primary_ip
4894

    
4895
    secondary_ip = self.op.secondary_ip
4896
    if not netutils.IP4Address.IsValid(secondary_ip):
4897
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4898
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4899

    
4900
    node_list = cfg.GetNodeList()
4901
    if not self.op.readd and node in node_list:
4902
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4903
                                 node, errors.ECODE_EXISTS)
4904
    elif self.op.readd and node not in node_list:
4905
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4906
                                 errors.ECODE_NOENT)
4907

    
4908
    self.changed_primary_ip = False
4909

    
4910
    for existing_node_name, existing_node in cfg.GetMultiNodeInfo(node_list):
4911
      if self.op.readd and node == existing_node_name:
4912
        if existing_node.secondary_ip != secondary_ip:
4913
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4914
                                     " address configuration as before",
4915
                                     errors.ECODE_INVAL)
4916
        if existing_node.primary_ip != primary_ip:
4917
          self.changed_primary_ip = True
4918

    
4919
        continue
4920

    
4921
      if (existing_node.primary_ip == primary_ip or
4922
          existing_node.secondary_ip == primary_ip or
4923
          existing_node.primary_ip == secondary_ip or
4924
          existing_node.secondary_ip == secondary_ip):
4925
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4926
                                   " existing node %s" % existing_node.name,
4927
                                   errors.ECODE_NOTUNIQUE)
4928

    
4929
    # After this 'if' block, None is no longer a valid value for the
4930
    # _capable op attributes
4931
    if self.op.readd:
4932
      old_node = self.cfg.GetNodeInfo(node)
4933
      assert old_node is not None, "Can't retrieve locked node %s" % node
4934
      for attr in self._NFLAGS:
4935
        if getattr(self.op, attr) is None:
4936
          setattr(self.op, attr, getattr(old_node, attr))
4937
    else:
4938
      for attr in self._NFLAGS:
4939
        if getattr(self.op, attr) is None:
4940
          setattr(self.op, attr, True)
4941

    
4942
    if self.op.readd and not self.op.vm_capable:
4943
      pri, sec = cfg.GetNodeInstances(node)
4944
      if pri or sec:
4945
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4946
                                   " flag set to false, but it already holds"
4947
                                   " instances" % node,
4948
                                   errors.ECODE_STATE)
4949

    
4950
    # check that the type of the node (single versus dual homed) is the
4951
    # same as for the master
4952
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4953
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4954
    newbie_singlehomed = secondary_ip == primary_ip
4955
    if master_singlehomed != newbie_singlehomed:
4956
      if master_singlehomed:
4957
        raise errors.OpPrereqError("The master has no secondary ip but the"
4958
                                   " new node has one",
4959
                                   errors.ECODE_INVAL)
4960
      else:
4961
        raise errors.OpPrereqError("The master has a secondary ip but the"
4962
                                   " new node doesn't have one",
4963
                                   errors.ECODE_INVAL)
4964

    
4965
    # checks reachability
4966
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4967
      raise errors.OpPrereqError("Node not reachable by ping",
4968
                                 errors.ECODE_ENVIRON)
4969

    
4970
    if not newbie_singlehomed:
4971
      # check reachability from my secondary ip to newbie's secondary ip
4972
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4973
                           source=myself.secondary_ip):
4974
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4975
                                   " based ping to node daemon port",
4976
                                   errors.ECODE_ENVIRON)
4977

    
4978
    if self.op.readd:
4979
      exceptions = [node]
4980
    else:
4981
      exceptions = []
4982

    
4983
    if self.op.master_capable:
4984
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4985
    else:
4986
      self.master_candidate = False
4987

    
4988
    if self.op.readd:
4989
      self.new_node = old_node
4990
    else:
4991
      node_group = cfg.LookupNodeGroup(self.op.group)
4992
      self.new_node = objects.Node(name=node,
4993
                                   primary_ip=primary_ip,
4994
                                   secondary_ip=secondary_ip,
4995
                                   master_candidate=self.master_candidate,
4996
                                   offline=False, drained=False,
4997
                                   group=node_group)
4998

    
4999
    if self.op.ndparams:
5000
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
5001

    
5002
  def Exec(self, feedback_fn):
5003
    """Adds the new node to the cluster.
5004

5005
    """
5006
    new_node = self.new_node
5007
    node = new_node.name
5008

    
5009
    # We adding a new node so we assume it's powered
5010
    new_node.powered = True
5011

    
5012
    # for re-adds, reset the offline/drained/master-candidate flags;
5013
    # we need to reset here, otherwise offline would prevent RPC calls
5014
    # later in the procedure; this also means that if the re-add
5015
    # fails, we are left with a non-offlined, broken node
5016
    if self.op.readd:
5017
      new_node.drained = new_node.offline = False # pylint: disable=W0201
5018
      self.LogInfo("Readding a node, the offline/drained flags were reset")
5019
      # if we demote the node, we do cleanup later in the procedure
5020
      new_node.master_candidate = self.master_candidate
5021
      if self.changed_primary_ip:
5022
        new_node.primary_ip = self.op.primary_ip
5023

    
5024
    # copy the master/vm_capable flags
5025
    for attr in self._NFLAGS:
5026
      setattr(new_node, attr, getattr(self.op, attr))
5027

    
5028
    # notify the user about any possible mc promotion
5029
    if new_node.master_candidate:
5030
      self.LogInfo("Node will be a master candidate")
5031

    
5032
    if self.op.ndparams:
5033
      new_node.ndparams = self.op.ndparams
5034
    else:
5035
      new_node.ndparams = {}
5036

    
5037
    # check connectivity
5038
    result = self.rpc.call_version([node])[node]
5039
    result.Raise("Can't get version information from node %s" % node)
5040
    if constants.PROTOCOL_VERSION == result.payload:
5041
      logging.info("Communication to node %s fine, sw version %s match",
5042
                   node, result.payload)
5043
    else:
5044
      raise errors.OpExecError("Version mismatch master version %s,"
5045
                               " node version %s" %
5046
                               (constants.PROTOCOL_VERSION, result.payload))
5047

    
5048
    # Add node to our /etc/hosts, and add key to known_hosts
5049
    if self.cfg.GetClusterInfo().modify_etc_hosts:
5050
      master_node = self.cfg.GetMasterNode()
5051
      result = self.rpc.call_etc_hosts_modify(master_node,
5052
                                              constants.ETC_HOSTS_ADD,
5053
                                              self.hostname.name,
5054
                                              self.hostname.ip)
5055
      result.Raise("Can't update hosts file with new host data")
5056

    
5057
    if new_node.secondary_ip != new_node.primary_ip:
5058
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
5059
                               False)
5060

    
5061
    node_verify_list = [self.cfg.GetMasterNode()]
5062
    node_verify_param = {
5063
      constants.NV_NODELIST: [node],
5064
      # TODO: do a node-net-test as well?
5065
    }
5066

    
5067
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
5068
                                       self.cfg.GetClusterName())
5069
    for verifier in node_verify_list:
5070
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
5071
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
5072
      if nl_payload:
5073
        for failed in nl_payload:
5074
          feedback_fn("ssh/hostname verification failed"
5075
                      " (checking from %s): %s" %
5076
                      (verifier, nl_payload[failed]))
5077
        raise errors.OpExecError("ssh/hostname verification failed")
5078

    
5079
    if self.op.readd:
5080
      _RedistributeAncillaryFiles(self)
5081
      self.context.ReaddNode(new_node)
5082
      # make sure we redistribute the config
5083
      self.cfg.Update(new_node, feedback_fn)
5084
      # and make sure the new node will not have old files around
5085
      if not new_node.master_candidate:
5086
        result = self.rpc.call_node_demote_from_mc(new_node.name)
5087
        msg = result.fail_msg
5088
        if msg:
5089
          self.LogWarning("Node failed to demote itself from master"
5090
                          " candidate status: %s" % msg)
5091
    else:
5092
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
5093
                                  additional_vm=self.op.vm_capable)
5094
      self.context.AddNode(new_node, self.proc.GetECId())
5095

    
5096

    
5097
class LUNodeSetParams(LogicalUnit):
5098
  """Modifies the parameters of a node.
5099

5100
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
5101
      to the node role (as _ROLE_*)
5102
  @cvar _R2F: a dictionary from node role to tuples of flags
5103
  @cvar _FLAGS: a list of attribute names corresponding to the flags
5104

5105
  """
5106
  HPATH = "node-modify"
5107
  HTYPE = constants.HTYPE_NODE
5108
  REQ_BGL = False
5109
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
5110
  _F2R = {
5111
    (True, False, False): _ROLE_CANDIDATE,
5112
    (False, True, False): _ROLE_DRAINED,
5113
    (False, False, True): _ROLE_OFFLINE,
5114
    (False, False, False): _ROLE_REGULAR,
5115
    }
5116
  _R2F = dict((v, k) for k, v in _F2R.items())
5117
  _FLAGS = ["master_candidate", "drained", "offline"]
5118

    
5119
  def CheckArguments(self):
5120
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5121
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
5122
                self.op.master_capable, self.op.vm_capable,
5123
                self.op.secondary_ip, self.op.ndparams]
5124
    if all_mods.count(None) == len(all_mods):
5125
      raise errors.OpPrereqError("Please pass at least one modification",
5126
                                 errors.ECODE_INVAL)
5127
    if all_mods.count(True) > 1:
5128
      raise errors.OpPrereqError("Can't set the node into more than one"
5129
                                 " state at the same time",
5130
                                 errors.ECODE_INVAL)
5131

    
5132
    # Boolean value that tells us whether we might be demoting from MC
5133
    self.might_demote = (self.op.master_candidate == False or
5134
                         self.op.offline == True or
5135
                         self.op.drained == True or
5136
                         self.op.master_capable == False)
5137

    
5138
    if self.op.secondary_ip:
5139
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
5140
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
5141
                                   " address" % self.op.secondary_ip,
5142
                                   errors.ECODE_INVAL)
5143

    
5144
    self.lock_all = self.op.auto_promote and self.might_demote
5145
    self.lock_instances = self.op.secondary_ip is not None
5146

    
5147
  def ExpandNames(self):
5148
    if self.lock_all:
5149
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
5150
    else:
5151
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
5152

    
5153
    if self.lock_instances:
5154
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
5155

    
5156
  def DeclareLocks(self, level):
5157
    # If we have locked all instances, before waiting to lock nodes, release
5158
    # all the ones living on nodes unrelated to the current operation.
5159
    if level == locking.LEVEL_NODE and self.lock_instances:
5160
      self.affected_instances = []
5161
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
5162
        instances_keep = []
5163

    
5164
        # Build list of instances to release
5165
        locked_i = self.owned_locks(locking.LEVEL_INSTANCE)
5166
        for instance_name, instance in self.cfg.GetMultiInstanceInfo(locked_i):
5167
          if (instance.disk_template in constants.DTS_INT_MIRROR and
5168
              self.op.node_name in instance.all_nodes):
5169
            instances_keep.append(instance_name)
5170
            self.affected_instances.append(instance)
5171

    
5172
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
5173

    
5174
        assert (set(self.owned_locks(locking.LEVEL_INSTANCE)) ==
5175
                set(instances_keep))
5176

    
5177
  def BuildHooksEnv(self):
5178
    """Build hooks env.
5179

5180
    This runs on the master node.
5181

5182
    """
5183
    return {
5184
      "OP_TARGET": self.op.node_name,
5185
      "MASTER_CANDIDATE": str(self.op.master_candidate),
5186
      "OFFLINE": str(self.op.offline),
5187
      "DRAINED": str(self.op.drained),
5188
      "MASTER_CAPABLE": str(self.op.master_capable),
5189
      "VM_CAPABLE": str(self.op.vm_capable),
5190
      }
5191

    
5192
  def BuildHooksNodes(self):
5193
    """Build hooks nodes.
5194

5195
    """
5196
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
5197
    return (nl, nl)
5198

    
5199
  def CheckPrereq(self):
5200
    """Check prerequisites.
5201

5202
    This only checks the instance list against the existing names.
5203

5204
    """
5205
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
5206

    
5207
    if (self.op.master_candidate is not None or
5208
        self.op.drained is not None or
5209
        self.op.offline is not None):
5210
      # we can't change the master's node flags
5211
      if self.op.node_name == self.cfg.GetMasterNode():
5212
        raise errors.OpPrereqError("The master role can be changed"
5213
                                   " only via master-failover",
5214
                                   errors.ECODE_INVAL)
5215

    
5216
    if self.op.master_candidate and not node.master_capable:
5217
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
5218
                                 " it a master candidate" % node.name,
5219
                                 errors.ECODE_STATE)
5220

    
5221
    if self.op.vm_capable == False:
5222
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
5223
      if ipri or isec:
5224
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
5225
                                   " the vm_capable flag" % node.name,
5226
                                   errors.ECODE_STATE)
5227

    
5228
    if node.master_candidate and self.might_demote and not self.lock_all:
5229
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
5230
      # check if after removing the current node, we're missing master
5231
      # candidates
5232
      (mc_remaining, mc_should, _) = \
5233
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
5234
      if mc_remaining < mc_should:
5235
        raise errors.OpPrereqError("Not enough master candidates, please"
5236
                                   " pass auto promote option to allow"
5237
                                   " promotion", errors.ECODE_STATE)
5238

    
5239
    self.old_flags = old_flags = (node.master_candidate,
5240
                                  node.drained, node.offline)
5241
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
5242
    self.old_role = old_role = self._F2R[old_flags]
5243

    
5244
    # Check for ineffective changes
5245
    for attr in self._FLAGS:
5246
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
5247
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
5248
        setattr(self.op, attr, None)
5249

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

    
5253
    # TODO: We might query the real power state if it supports OOB
5254
    if _SupportsOob(self.cfg, node):
5255
      if self.op.offline is False and not (node.powered or
5256
                                           self.op.powered == True):
5257
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
5258
                                    " offline status can be reset") %
5259
                                   self.op.node_name)
5260
    elif self.op.powered is not None:
5261
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
5262
                                  " as it does not support out-of-band"
5263
                                  " handling") % self.op.node_name)
5264

    
5265
    # If we're being deofflined/drained, we'll MC ourself if needed
5266
    if (self.op.drained == False or self.op.offline == False or
5267
        (self.op.master_capable and not node.master_capable)):
5268
      if _DecideSelfPromotion(self):
5269
        self.op.master_candidate = True
5270
        self.LogInfo("Auto-promoting node to master candidate")
5271

    
5272
    # If we're no longer master capable, we'll demote ourselves from MC
5273
    if self.op.master_capable == False and node.master_candidate:
5274
      self.LogInfo("Demoting from master candidate")
5275
      self.op.master_candidate = False
5276

    
5277
    # Compute new role
5278
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
5279
    if self.op.master_candidate:
5280
      new_role = self._ROLE_CANDIDATE
5281
    elif self.op.drained:
5282
      new_role = self._ROLE_DRAINED
5283
    elif self.op.offline:
5284
      new_role = self._ROLE_OFFLINE
5285
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
5286
      # False is still in new flags, which means we're un-setting (the
5287
      # only) True flag
5288
      new_role = self._ROLE_REGULAR
5289
    else: # no new flags, nothing, keep old role
5290
      new_role = old_role
5291

    
5292
    self.new_role = new_role
5293

    
5294
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
5295
      # Trying to transition out of offline status
5296
      result = self.rpc.call_version([node.name])[node.name]
5297
      if result.fail_msg:
5298
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
5299
                                   " to report its version: %s" %
5300
                                   (node.name, result.fail_msg),
5301
                                   errors.ECODE_STATE)
5302
      else:
5303
        self.LogWarning("Transitioning node from offline to online state"
5304
                        " without using re-add. Please make sure the node"
5305
                        " is healthy!")
5306

    
5307
    if self.op.secondary_ip:
5308
      # Ok even without locking, because this can't be changed by any LU
5309
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
5310
      master_singlehomed = master.secondary_ip == master.primary_ip
5311
      if master_singlehomed and self.op.secondary_ip:
5312
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
5313
                                   " homed cluster", errors.ECODE_INVAL)
5314

    
5315
      if node.offline:
5316
        if self.affected_instances:
5317
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
5318
                                     " node has instances (%s) configured"
5319
                                     " to use it" % self.affected_instances)
5320
      else:
5321
        # On online nodes, check that no instances are running, and that
5322
        # the node has the new ip and we can reach it.
5323
        for instance in self.affected_instances:
5324
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
5325

    
5326
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
5327
        if master.name != node.name:
5328
          # check reachability from master secondary ip to new secondary ip
5329
          if not netutils.TcpPing(self.op.secondary_ip,
5330
                                  constants.DEFAULT_NODED_PORT,
5331
                                  source=master.secondary_ip):
5332
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5333
                                       " based ping to node daemon port",
5334
                                       errors.ECODE_ENVIRON)
5335

    
5336
    if self.op.ndparams:
5337
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
5338
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
5339
      self.new_ndparams = new_ndparams
5340

    
5341
  def Exec(self, feedback_fn):
5342
    """Modifies a node.
5343

5344
    """
5345
    node = self.node
5346
    old_role = self.old_role
5347
    new_role = self.new_role
5348

    
5349
    result = []
5350

    
5351
    if self.op.ndparams:
5352
      node.ndparams = self.new_ndparams
5353

    
5354
    if self.op.powered is not None:
5355
      node.powered = self.op.powered
5356

    
5357
    for attr in ["master_capable", "vm_capable"]:
5358
      val = getattr(self.op, attr)
5359
      if val is not None:
5360
        setattr(node, attr, val)
5361
        result.append((attr, str(val)))
5362

    
5363
    if new_role != old_role:
5364
      # Tell the node to demote itself, if no longer MC and not offline
5365
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5366
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5367
        if msg:
5368
          self.LogWarning("Node failed to demote itself: %s", msg)
5369

    
5370
      new_flags = self._R2F[new_role]
5371
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5372
        if of != nf:
5373
          result.append((desc, str(nf)))
5374
      (node.master_candidate, node.drained, node.offline) = new_flags
5375

    
5376
      # we locked all nodes, we adjust the CP before updating this node
5377
      if self.lock_all:
5378
        _AdjustCandidatePool(self, [node.name])
5379

    
5380
    if self.op.secondary_ip:
5381
      node.secondary_ip = self.op.secondary_ip
5382
      result.append(("secondary_ip", self.op.secondary_ip))
5383

    
5384
    # this will trigger configuration file update, if needed
5385
    self.cfg.Update(node, feedback_fn)
5386

    
5387
    # this will trigger job queue propagation or cleanup if the mc
5388
    # flag changed
5389
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5390
      self.context.ReaddNode(node)
5391

    
5392
    return result
5393

    
5394

    
5395
class LUNodePowercycle(NoHooksLU):
5396
  """Powercycles a node.
5397

5398
  """
5399
  REQ_BGL = False
5400

    
5401
  def CheckArguments(self):
5402
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5403
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5404
      raise errors.OpPrereqError("The node is the master and the force"
5405
                                 " parameter was not set",
5406
                                 errors.ECODE_INVAL)
5407

    
5408
  def ExpandNames(self):
5409
    """Locking for PowercycleNode.
5410

5411
    This is a last-resort option and shouldn't block on other
5412
    jobs. Therefore, we grab no locks.
5413

5414
    """
5415
    self.needed_locks = {}
5416

    
5417
  def Exec(self, feedback_fn):
5418
    """Reboots a node.
5419

5420
    """
5421
    result = self.rpc.call_node_powercycle(self.op.node_name,
5422
                                           self.cfg.GetHypervisorType())
5423
    result.Raise("Failed to schedule the reboot")
5424
    return result.payload
5425

    
5426

    
5427
class LUClusterQuery(NoHooksLU):
5428
  """Query cluster configuration.
5429

5430
  """
5431
  REQ_BGL = False
5432

    
5433
  def ExpandNames(self):
5434
    self.needed_locks = {}
5435

    
5436
  def Exec(self, feedback_fn):
5437
    """Return cluster config.
5438

5439
    """
5440
    cluster = self.cfg.GetClusterInfo()
5441
    os_hvp = {}
5442

    
5443
    # Filter just for enabled hypervisors
5444
    for os_name, hv_dict in cluster.os_hvp.items():
5445
      os_hvp[os_name] = {}
5446
      for hv_name, hv_params in hv_dict.items():
5447
        if hv_name in cluster.enabled_hypervisors:
5448
          os_hvp[os_name][hv_name] = hv_params
5449

    
5450
    # Convert ip_family to ip_version
5451
    primary_ip_version = constants.IP4_VERSION
5452
    if cluster.primary_ip_family == netutils.IP6Address.family:
5453
      primary_ip_version = constants.IP6_VERSION
5454

    
5455
    result = {
5456
      "software_version": constants.RELEASE_VERSION,
5457
      "protocol_version": constants.PROTOCOL_VERSION,
5458
      "config_version": constants.CONFIG_VERSION,
5459
      "os_api_version": max(constants.OS_API_VERSIONS),
5460
      "export_version": constants.EXPORT_VERSION,
5461
      "architecture": (platform.architecture()[0], platform.machine()),
5462
      "name": cluster.cluster_name,
5463
      "master": cluster.master_node,
5464
      "default_hypervisor": cluster.enabled_hypervisors[0],
5465
      "enabled_hypervisors": cluster.enabled_hypervisors,
5466
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5467
                        for hypervisor_name in cluster.enabled_hypervisors]),
5468
      "os_hvp": os_hvp,
5469
      "beparams": cluster.beparams,
5470
      "osparams": cluster.osparams,
5471
      "nicparams": cluster.nicparams,
5472
      "ndparams": cluster.ndparams,
5473
      "candidate_pool_size": cluster.candidate_pool_size,
5474
      "master_netdev": cluster.master_netdev,
5475
      "volume_group_name": cluster.volume_group_name,
5476
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5477
      "file_storage_dir": cluster.file_storage_dir,
5478
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5479
      "maintain_node_health": cluster.maintain_node_health,
5480
      "ctime": cluster.ctime,
5481
      "mtime": cluster.mtime,
5482
      "uuid": cluster.uuid,
5483
      "tags": list(cluster.GetTags()),
5484
      "uid_pool": cluster.uid_pool,
5485
      "default_iallocator": cluster.default_iallocator,
5486
      "reserved_lvs": cluster.reserved_lvs,
5487
      "primary_ip_version": primary_ip_version,
5488
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5489
      "hidden_os": cluster.hidden_os,
5490
      "blacklisted_os": cluster.blacklisted_os,
5491
      }
5492

    
5493
    return result
5494

    
5495

    
5496
class LUClusterConfigQuery(NoHooksLU):
5497
  """Return configuration values.
5498

5499
  """
5500
  REQ_BGL = False
5501
  _FIELDS_DYNAMIC = utils.FieldSet()
5502
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5503
                                  "watcher_pause", "volume_group_name")
5504

    
5505
  def CheckArguments(self):
5506
    _CheckOutputFields(static=self._FIELDS_STATIC,
5507
                       dynamic=self._FIELDS_DYNAMIC,
5508
                       selected=self.op.output_fields)
5509

    
5510
  def ExpandNames(self):
5511
    self.needed_locks = {}
5512

    
5513
  def Exec(self, feedback_fn):
5514
    """Dump a representation of the cluster config to the standard output.
5515

5516
    """
5517
    values = []
5518
    for field in self.op.output_fields:
5519
      if field == "cluster_name":
5520
        entry = self.cfg.GetClusterName()
5521
      elif field == "master_node":
5522
        entry = self.cfg.GetMasterNode()
5523
      elif field == "drain_flag":
5524
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5525
      elif field == "watcher_pause":
5526
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5527
      elif field == "volume_group_name":
5528
        entry = self.cfg.GetVGName()
5529
      else:
5530
        raise errors.ParameterError(field)
5531
      values.append(entry)
5532
    return values
5533

    
5534

    
5535
class LUInstanceActivateDisks(NoHooksLU):
5536
  """Bring up an instance's disks.
5537

5538
  """
5539
  REQ_BGL = False
5540

    
5541
  def ExpandNames(self):
5542
    self._ExpandAndLockInstance()
5543
    self.needed_locks[locking.LEVEL_NODE] = []
5544
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5545

    
5546
  def DeclareLocks(self, level):
5547
    if level == locking.LEVEL_NODE:
5548
      self._LockInstancesNodes()
5549

    
5550
  def CheckPrereq(self):
5551
    """Check prerequisites.
5552

5553
    This checks that the instance is in the cluster.
5554

5555
    """
5556
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5557
    assert self.instance is not None, \
5558
      "Cannot retrieve locked instance %s" % self.op.instance_name
5559
    _CheckNodeOnline(self, self.instance.primary_node)
5560

    
5561
  def Exec(self, feedback_fn):
5562
    """Activate the disks.
5563

5564
    """
5565
    disks_ok, disks_info = \
5566
              _AssembleInstanceDisks(self, self.instance,
5567
                                     ignore_size=self.op.ignore_size)
5568
    if not disks_ok:
5569
      raise errors.OpExecError("Cannot activate block devices")
5570

    
5571
    return disks_info
5572

    
5573

    
5574
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5575
                           ignore_size=False):
5576
  """Prepare the block devices for an instance.
5577

5578
  This sets up the block devices on all nodes.
5579

5580
  @type lu: L{LogicalUnit}
5581
  @param lu: the logical unit on whose behalf we execute
5582
  @type instance: L{objects.Instance}
5583
  @param instance: the instance for whose disks we assemble
5584
  @type disks: list of L{objects.Disk} or None
5585
  @param disks: which disks to assemble (or all, if None)
5586
  @type ignore_secondaries: boolean
5587
  @param ignore_secondaries: if true, errors on secondary nodes
5588
      won't result in an error return from the function
5589
  @type ignore_size: boolean
5590
  @param ignore_size: if true, the current known size of the disk
5591
      will not be used during the disk activation, useful for cases
5592
      when the size is wrong
5593
  @return: False if the operation failed, otherwise a list of
5594
      (host, instance_visible_name, node_visible_name)
5595
      with the mapping from node devices to instance devices
5596

5597
  """
5598
  device_info = []
5599
  disks_ok = True
5600
  iname = instance.name
5601
  disks = _ExpandCheckDisks(instance, disks)
5602

    
5603
  # With the two passes mechanism we try to reduce the window of
5604
  # opportunity for the race condition of switching DRBD to primary
5605
  # before handshaking occured, but we do not eliminate it
5606

    
5607
  # The proper fix would be to wait (with some limits) until the
5608
  # connection has been made and drbd transitions from WFConnection
5609
  # into any other network-connected state (Connected, SyncTarget,
5610
  # SyncSource, etc.)
5611

    
5612
  # 1st pass, assemble on all nodes in secondary mode
5613
  for idx, inst_disk in enumerate(disks):
5614
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5615
      if ignore_size:
5616
        node_disk = node_disk.Copy()
5617
        node_disk.UnsetSize()
5618
      lu.cfg.SetDiskID(node_disk, node)
5619
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5620
      msg = result.fail_msg
5621
      if msg:
5622
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5623
                           " (is_primary=False, pass=1): %s",
5624
                           inst_disk.iv_name, node, msg)
5625
        if not ignore_secondaries:
5626
          disks_ok = False
5627

    
5628
  # FIXME: race condition on drbd migration to primary
5629

    
5630
  # 2nd pass, do only the primary node
5631
  for idx, inst_disk in enumerate(disks):
5632
    dev_path = None
5633

    
5634
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5635
      if node != instance.primary_node:
5636
        continue
5637
      if ignore_size:
5638
        node_disk = node_disk.Copy()
5639
        node_disk.UnsetSize()
5640
      lu.cfg.SetDiskID(node_disk, node)
5641
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5642
      msg = result.fail_msg
5643
      if msg:
5644
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5645
                           " (is_primary=True, pass=2): %s",
5646
                           inst_disk.iv_name, node, msg)
5647
        disks_ok = False
5648
      else:
5649
        dev_path = result.payload
5650

    
5651
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5652

    
5653
  # leave the disks configured for the primary node
5654
  # this is a workaround that would be fixed better by
5655
  # improving the logical/physical id handling
5656
  for disk in disks:
5657
    lu.cfg.SetDiskID(disk, instance.primary_node)
5658

    
5659
  return disks_ok, device_info
5660

    
5661

    
5662
def _StartInstanceDisks(lu, instance, force):
5663
  """Start the disks of an instance.
5664

5665
  """
5666
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5667
                                           ignore_secondaries=force)
5668
  if not disks_ok:
5669
    _ShutdownInstanceDisks(lu, instance)
5670
    if force is not None and not force:
5671
      lu.proc.LogWarning("", hint="If the message above refers to a"
5672
                         " secondary node,"
5673
                         " you can retry the operation using '--force'.")
5674
    raise errors.OpExecError("Disk consistency error")
5675

    
5676

    
5677
class LUInstanceDeactivateDisks(NoHooksLU):
5678
  """Shutdown an instance's disks.
5679

5680
  """
5681
  REQ_BGL = False
5682

    
5683
  def ExpandNames(self):
5684
    self._ExpandAndLockInstance()
5685
    self.needed_locks[locking.LEVEL_NODE] = []
5686
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5687

    
5688
  def DeclareLocks(self, level):
5689
    if level == locking.LEVEL_NODE:
5690
      self._LockInstancesNodes()
5691

    
5692
  def CheckPrereq(self):
5693
    """Check prerequisites.
5694

5695
    This checks that the instance is in the cluster.
5696

5697
    """
5698
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5699
    assert self.instance is not None, \
5700
      "Cannot retrieve locked instance %s" % self.op.instance_name
5701

    
5702
  def Exec(self, feedback_fn):
5703
    """Deactivate the disks
5704

5705
    """
5706
    instance = self.instance
5707
    if self.op.force:
5708
      _ShutdownInstanceDisks(self, instance)
5709
    else:
5710
      _SafeShutdownInstanceDisks(self, instance)
5711

    
5712

    
5713
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5714
  """Shutdown block devices of an instance.
5715

5716
  This function checks if an instance is running, before calling
5717
  _ShutdownInstanceDisks.
5718

5719
  """
5720
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5721
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5722

    
5723

    
5724
def _ExpandCheckDisks(instance, disks):
5725
  """Return the instance disks selected by the disks list
5726

5727
  @type disks: list of L{objects.Disk} or None
5728
  @param disks: selected disks
5729
  @rtype: list of L{objects.Disk}
5730
  @return: selected instance disks to act on
5731

5732
  """
5733
  if disks is None:
5734
    return instance.disks
5735
  else:
5736
    if not set(disks).issubset(instance.disks):
5737
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5738
                                   " target instance")
5739
    return disks
5740

    
5741

    
5742
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5743
  """Shutdown block devices of an instance.
5744

5745
  This does the shutdown on all nodes of the instance.
5746

5747
  If the ignore_primary is false, errors on the primary node are
5748
  ignored.
5749

5750
  """
5751
  all_result = True
5752
  disks = _ExpandCheckDisks(instance, disks)
5753

    
5754
  for disk in disks:
5755
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5756
      lu.cfg.SetDiskID(top_disk, node)
5757
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5758
      msg = result.fail_msg
5759
      if msg:
5760
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5761
                      disk.iv_name, node, msg)
5762
        if ((node == instance.primary_node and not ignore_primary) or
5763
            (node != instance.primary_node and not result.offline)):
5764
          all_result = False
5765
  return all_result
5766

    
5767

    
5768
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5769
  """Checks if a node has enough free memory.
5770

5771
  This function check if a given node has the needed amount of free
5772
  memory. In case the node has less memory or we cannot get the
5773
  information from the node, this function raise an OpPrereqError
5774
  exception.
5775

5776
  @type lu: C{LogicalUnit}
5777
  @param lu: a logical unit from which we get configuration data
5778
  @type node: C{str}
5779
  @param node: the node to check
5780
  @type reason: C{str}
5781
  @param reason: string to use in the error message
5782
  @type requested: C{int}
5783
  @param requested: the amount of memory in MiB to check for
5784
  @type hypervisor_name: C{str}
5785
  @param hypervisor_name: the hypervisor to ask for memory stats
5786
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5787
      we cannot check the node
5788

5789
  """
5790
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5791
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5792
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5793
  free_mem = nodeinfo[node].payload.get("memory_free", None)
5794
  if not isinstance(free_mem, int):
5795
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5796
                               " was '%s'" % (node, free_mem),
5797
                               errors.ECODE_ENVIRON)
5798
  if requested > free_mem:
5799
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5800
                               " needed %s MiB, available %s MiB" %
5801
                               (node, reason, requested, free_mem),
5802
                               errors.ECODE_NORES)
5803

    
5804

    
5805
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5806
  """Checks if nodes have enough free disk space in the all VGs.
5807

5808
  This function check if all given nodes have the needed amount of
5809
  free disk. In case any node has less disk or we cannot get the
5810
  information from the node, this function raise an OpPrereqError
5811
  exception.
5812

5813
  @type lu: C{LogicalUnit}
5814
  @param lu: a logical unit from which we get configuration data
5815
  @type nodenames: C{list}
5816
  @param nodenames: the list of node names to check
5817
  @type req_sizes: C{dict}
5818
  @param req_sizes: the hash of vg and corresponding amount of disk in
5819
      MiB to check for
5820
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5821
      or we cannot check the node
5822

5823
  """
5824
  for vg, req_size in req_sizes.items():
5825
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5826

    
5827

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

5831
  This function check if all given nodes have the needed amount of
5832
  free disk. In case any node has less disk or we cannot get the
5833
  information from the node, this function raise an OpPrereqError
5834
  exception.
5835

5836
  @type lu: C{LogicalUnit}
5837
  @param lu: a logical unit from which we get configuration data
5838
  @type nodenames: C{list}
5839
  @param nodenames: the list of node names to check
5840
  @type vg: C{str}
5841
  @param vg: the volume group to check
5842
  @type requested: C{int}
5843
  @param requested: the amount of disk in MiB to check for
5844
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5845
      or we cannot check the node
5846

5847
  """
5848
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5849
  for node in nodenames:
5850
    info = nodeinfo[node]
5851
    info.Raise("Cannot get current information from node %s" % node,
5852
               prereq=True, ecode=errors.ECODE_ENVIRON)
5853
    vg_free = info.payload.get("vg_free", None)
5854
    if not isinstance(vg_free, int):
5855
      raise errors.OpPrereqError("Can't compute free disk space on node"
5856
                                 " %s for vg %s, result was '%s'" %
5857
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5858
    if requested > vg_free:
5859
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5860
                                 " vg %s: required %d MiB, available %d MiB" %
5861
                                 (node, vg, requested, vg_free),
5862
                                 errors.ECODE_NORES)
5863

    
5864

    
5865
class LUInstanceStartup(LogicalUnit):
5866
  """Starts an instance.
5867

5868
  """
5869
  HPATH = "instance-start"
5870
  HTYPE = constants.HTYPE_INSTANCE
5871
  REQ_BGL = False
5872

    
5873
  def CheckArguments(self):
5874
    # extra beparams
5875
    if self.op.beparams:
5876
      # fill the beparams dict
5877
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5878

    
5879
  def ExpandNames(self):
5880
    self._ExpandAndLockInstance()
5881

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

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

5887
    """
5888
    env = {
5889
      "FORCE": self.op.force,
5890
      }
5891

    
5892
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5893

    
5894
    return env
5895

    
5896
  def BuildHooksNodes(self):
5897
    """Build hooks nodes.
5898

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

    
5903
  def CheckPrereq(self):
5904
    """Check prerequisites.
5905

5906
    This checks that the instance is in the cluster.
5907

5908
    """
5909
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5910
    assert self.instance is not None, \
5911
      "Cannot retrieve locked instance %s" % self.op.instance_name
5912

    
5913
    # extra hvparams
5914
    if self.op.hvparams:
5915
      # check hypervisor parameter syntax (locally)
5916
      cluster = self.cfg.GetClusterInfo()
5917
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5918
      filled_hvp = cluster.FillHV(instance)
5919
      filled_hvp.update(self.op.hvparams)
5920
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5921
      hv_type.CheckParameterSyntax(filled_hvp)
5922
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5923

    
5924
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5925

    
5926
    if self.primary_offline and self.op.ignore_offline_nodes:
5927
      self.proc.LogWarning("Ignoring offline primary node")
5928

    
5929
      if self.op.hvparams or self.op.beparams:
5930
        self.proc.LogWarning("Overridden parameters are ignored")
5931
    else:
5932
      _CheckNodeOnline(self, instance.primary_node)
5933

    
5934
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5935

    
5936
      # check bridges existence
5937
      _CheckInstanceBridgesExist(self, instance)
5938

    
5939
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5940
                                                instance.name,
5941
                                                instance.hypervisor)
5942
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5943
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5944
      if not remote_info.payload: # not running already
5945
        _CheckNodeFreeMemory(self, instance.primary_node,
5946
                             "starting instance %s" % instance.name,
5947
                             bep[constants.BE_MEMORY], instance.hypervisor)
5948

    
5949
  def Exec(self, feedback_fn):
5950
    """Start the instance.
5951

5952
    """
5953
    instance = self.instance
5954
    force = self.op.force
5955

    
5956
    if not self.op.no_remember:
5957
      self.cfg.MarkInstanceUp(instance.name)
5958

    
5959
    if self.primary_offline:
5960
      assert self.op.ignore_offline_nodes
5961
      self.proc.LogInfo("Primary node offline, marked instance as started")
5962
    else:
5963
      node_current = instance.primary_node
5964

    
5965
      _StartInstanceDisks(self, instance, force)
5966

    
5967
      result = self.rpc.call_instance_start(node_current, instance,
5968
                                            self.op.hvparams, self.op.beparams,
5969
                                            self.op.startup_paused)
5970
      msg = result.fail_msg
5971
      if msg:
5972
        _ShutdownInstanceDisks(self, instance)
5973
        raise errors.OpExecError("Could not start instance: %s" % msg)
5974

    
5975

    
5976
class LUInstanceReboot(LogicalUnit):
5977
  """Reboot an instance.
5978

5979
  """
5980
  HPATH = "instance-reboot"
5981
  HTYPE = constants.HTYPE_INSTANCE
5982
  REQ_BGL = False
5983

    
5984
  def ExpandNames(self):
5985
    self._ExpandAndLockInstance()
5986

    
5987
  def BuildHooksEnv(self):
5988
    """Build hooks env.
5989

5990
    This runs on master, primary and secondary nodes of the instance.
5991

5992
    """
5993
    env = {
5994
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5995
      "REBOOT_TYPE": self.op.reboot_type,
5996
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5997
      }
5998

    
5999
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6000

    
6001
    return env
6002

    
6003
  def BuildHooksNodes(self):
6004
    """Build hooks nodes.
6005

6006
    """
6007
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6008
    return (nl, nl)
6009

    
6010
  def CheckPrereq(self):
6011
    """Check prerequisites.
6012

6013
    This checks that the instance is in the cluster.
6014

6015
    """
6016
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6017
    assert self.instance is not None, \
6018
      "Cannot retrieve locked instance %s" % self.op.instance_name
6019

    
6020
    _CheckNodeOnline(self, instance.primary_node)
6021

    
6022
    # check bridges existence
6023
    _CheckInstanceBridgesExist(self, instance)
6024

    
6025
  def Exec(self, feedback_fn):
6026
    """Reboot the instance.
6027

6028
    """
6029
    instance = self.instance
6030
    ignore_secondaries = self.op.ignore_secondaries
6031
    reboot_type = self.op.reboot_type
6032

    
6033
    remote_info = self.rpc.call_instance_info(instance.primary_node,
6034
                                              instance.name,
6035
                                              instance.hypervisor)
6036
    remote_info.Raise("Error checking node %s" % instance.primary_node)
6037
    instance_running = bool(remote_info.payload)
6038

    
6039
    node_current = instance.primary_node
6040

    
6041
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
6042
                                            constants.INSTANCE_REBOOT_HARD]:
6043
      for disk in instance.disks:
6044
        self.cfg.SetDiskID(disk, node_current)
6045
      result = self.rpc.call_instance_reboot(node_current, instance,
6046
                                             reboot_type,
6047
                                             self.op.shutdown_timeout)
6048
      result.Raise("Could not reboot instance")
6049
    else:
6050
      if instance_running:
6051
        result = self.rpc.call_instance_shutdown(node_current, instance,
6052
                                                 self.op.shutdown_timeout)
6053
        result.Raise("Could not shutdown instance for full reboot")
6054
        _ShutdownInstanceDisks(self, instance)
6055
      else:
6056
        self.LogInfo("Instance %s was already stopped, starting now",
6057
                     instance.name)
6058
      _StartInstanceDisks(self, instance, ignore_secondaries)
6059
      result = self.rpc.call_instance_start(node_current, instance,
6060
                                            None, None, False)
6061
      msg = result.fail_msg
6062
      if msg:
6063
        _ShutdownInstanceDisks(self, instance)
6064
        raise errors.OpExecError("Could not start instance for"
6065
                                 " full reboot: %s" % msg)
6066

    
6067
    self.cfg.MarkInstanceUp(instance.name)
6068

    
6069

    
6070
class LUInstanceShutdown(LogicalUnit):
6071
  """Shutdown an instance.
6072

6073
  """
6074
  HPATH = "instance-stop"
6075
  HTYPE = constants.HTYPE_INSTANCE
6076
  REQ_BGL = False
6077

    
6078
  def ExpandNames(self):
6079
    self._ExpandAndLockInstance()
6080

    
6081
  def BuildHooksEnv(self):
6082
    """Build hooks env.
6083

6084
    This runs on master, primary and secondary nodes of the instance.
6085

6086
    """
6087
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6088
    env["TIMEOUT"] = self.op.timeout
6089
    return env
6090

    
6091
  def BuildHooksNodes(self):
6092
    """Build hooks nodes.
6093

6094
    """
6095
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6096
    return (nl, nl)
6097

    
6098
  def CheckPrereq(self):
6099
    """Check prerequisites.
6100

6101
    This checks that the instance is in the cluster.
6102

6103
    """
6104
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6105
    assert self.instance is not None, \
6106
      "Cannot retrieve locked instance %s" % self.op.instance_name
6107

    
6108
    self.primary_offline = \
6109
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
6110

    
6111
    if self.primary_offline and self.op.ignore_offline_nodes:
6112
      self.proc.LogWarning("Ignoring offline primary node")
6113
    else:
6114
      _CheckNodeOnline(self, self.instance.primary_node)
6115

    
6116
  def Exec(self, feedback_fn):
6117
    """Shutdown the instance.
6118

6119
    """
6120
    instance = self.instance
6121
    node_current = instance.primary_node
6122
    timeout = self.op.timeout
6123

    
6124
    if not self.op.no_remember:
6125
      self.cfg.MarkInstanceDown(instance.name)
6126

    
6127
    if self.primary_offline:
6128
      assert self.op.ignore_offline_nodes
6129
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
6130
    else:
6131
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
6132
      msg = result.fail_msg
6133
      if msg:
6134
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
6135

    
6136
      _ShutdownInstanceDisks(self, instance)
6137

    
6138

    
6139
class LUInstanceReinstall(LogicalUnit):
6140
  """Reinstall an instance.
6141

6142
  """
6143
  HPATH = "instance-reinstall"
6144
  HTYPE = constants.HTYPE_INSTANCE
6145
  REQ_BGL = False
6146

    
6147
  def ExpandNames(self):
6148
    self._ExpandAndLockInstance()
6149

    
6150
  def BuildHooksEnv(self):
6151
    """Build hooks env.
6152

6153
    This runs on master, primary and secondary nodes of the instance.
6154

6155
    """
6156
    return _BuildInstanceHookEnvByObject(self, self.instance)
6157

    
6158
  def BuildHooksNodes(self):
6159
    """Build hooks nodes.
6160

6161
    """
6162
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6163
    return (nl, nl)
6164

    
6165
  def CheckPrereq(self):
6166
    """Check prerequisites.
6167

6168
    This checks that the instance is in the cluster and is not running.
6169

6170
    """
6171
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6172
    assert instance is not None, \
6173
      "Cannot retrieve locked instance %s" % self.op.instance_name
6174
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
6175
                     " offline, cannot reinstall")
6176
    for node in instance.secondary_nodes:
6177
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
6178
                       " cannot reinstall")
6179

    
6180
    if instance.disk_template == constants.DT_DISKLESS:
6181
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6182
                                 self.op.instance_name,
6183
                                 errors.ECODE_INVAL)
6184
    _CheckInstanceDown(self, instance, "cannot reinstall")
6185

    
6186
    if self.op.os_type is not None:
6187
      # OS verification
6188
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
6189
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
6190
      instance_os = self.op.os_type
6191
    else:
6192
      instance_os = instance.os
6193

    
6194
    nodelist = list(instance.all_nodes)
6195

    
6196
    if self.op.osparams:
6197
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
6198
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
6199
      self.os_inst = i_osdict # the new dict (without defaults)
6200
    else:
6201
      self.os_inst = None
6202

    
6203
    self.instance = instance
6204

    
6205
  def Exec(self, feedback_fn):
6206
    """Reinstall the instance.
6207

6208
    """
6209
    inst = self.instance
6210

    
6211
    if self.op.os_type is not None:
6212
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
6213
      inst.os = self.op.os_type
6214
      # Write to configuration
6215
      self.cfg.Update(inst, feedback_fn)
6216

    
6217
    _StartInstanceDisks(self, inst, None)
6218
    try:
6219
      feedback_fn("Running the instance OS create scripts...")
6220
      # FIXME: pass debug option from opcode to backend
6221
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
6222
                                             self.op.debug_level,
6223
                                             osparams=self.os_inst)
6224
      result.Raise("Could not install OS for instance %s on node %s" %
6225
                   (inst.name, inst.primary_node))
6226
    finally:
6227
      _ShutdownInstanceDisks(self, inst)
6228

    
6229

    
6230
class LUInstanceRecreateDisks(LogicalUnit):
6231
  """Recreate an instance's missing disks.
6232

6233
  """
6234
  HPATH = "instance-recreate-disks"
6235
  HTYPE = constants.HTYPE_INSTANCE
6236
  REQ_BGL = False
6237

    
6238
  def CheckArguments(self):
6239
    # normalise the disk list
6240
    self.op.disks = sorted(frozenset(self.op.disks))
6241

    
6242
  def ExpandNames(self):
6243
    self._ExpandAndLockInstance()
6244
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6245
    if self.op.nodes:
6246
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
6247
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
6248
    else:
6249
      self.needed_locks[locking.LEVEL_NODE] = []
6250

    
6251
  def DeclareLocks(self, level):
6252
    if level == locking.LEVEL_NODE:
6253
      # if we replace the nodes, we only need to lock the old primary,
6254
      # otherwise we need to lock all nodes for disk re-creation
6255
      primary_only = bool(self.op.nodes)
6256
      self._LockInstancesNodes(primary_only=primary_only)
6257

    
6258
  def BuildHooksEnv(self):
6259
    """Build hooks env.
6260

6261
    This runs on master, primary and secondary nodes of the instance.
6262

6263
    """
6264
    return _BuildInstanceHookEnvByObject(self, self.instance)
6265

    
6266
  def BuildHooksNodes(self):
6267
    """Build hooks nodes.
6268

6269
    """
6270
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6271
    return (nl, nl)
6272

    
6273
  def CheckPrereq(self):
6274
    """Check prerequisites.
6275

6276
    This checks that the instance is in the cluster and is not running.
6277

6278
    """
6279
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6280
    assert instance is not None, \
6281
      "Cannot retrieve locked instance %s" % self.op.instance_name
6282
    if self.op.nodes:
6283
      if len(self.op.nodes) != len(instance.all_nodes):
6284
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6285
                                   " %d replacement nodes were specified" %
6286
                                   (instance.name, len(instance.all_nodes),
6287
                                    len(self.op.nodes)),
6288
                                   errors.ECODE_INVAL)
6289
      assert instance.disk_template != constants.DT_DRBD8 or \
6290
          len(self.op.nodes) == 2
6291
      assert instance.disk_template != constants.DT_PLAIN or \
6292
          len(self.op.nodes) == 1
6293
      primary_node = self.op.nodes[0]
6294
    else:
6295
      primary_node = instance.primary_node
6296
    _CheckNodeOnline(self, primary_node)
6297

    
6298
    if instance.disk_template == constants.DT_DISKLESS:
6299
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6300
                                 self.op.instance_name, errors.ECODE_INVAL)
6301
    # if we replace nodes *and* the old primary is offline, we don't
6302
    # check
6303
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
6304
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6305
    if not (self.op.nodes and old_pnode.offline):
6306
      _CheckInstanceDown(self, instance, "cannot recreate disks")
6307

    
6308
    if not self.op.disks:
6309
      self.op.disks = range(len(instance.disks))
6310
    else:
6311
      for idx in self.op.disks:
6312
        if idx >= len(instance.disks):
6313
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6314
                                     errors.ECODE_INVAL)
6315
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6316
      raise errors.OpPrereqError("Can't recreate disks partially and"
6317
                                 " change the nodes at the same time",
6318
                                 errors.ECODE_INVAL)
6319
    self.instance = instance
6320

    
6321
  def Exec(self, feedback_fn):
6322
    """Recreate the disks.
6323

6324
    """
6325
    instance = self.instance
6326

    
6327
    to_skip = []
6328
    mods = [] # keeps track of needed logical_id changes
6329

    
6330
    for idx, disk in enumerate(instance.disks):
6331
      if idx not in self.op.disks: # disk idx has not been passed in
6332
        to_skip.append(idx)
6333
        continue
6334
      # update secondaries for disks, if needed
6335
      if self.op.nodes:
6336
        if disk.dev_type == constants.LD_DRBD8:
6337
          # need to update the nodes and minors
6338
          assert len(self.op.nodes) == 2
6339
          assert len(disk.logical_id) == 6 # otherwise disk internals
6340
                                           # have changed
6341
          (_, _, old_port, _, _, old_secret) = disk.logical_id
6342
          new_minors = self.cfg.AllocateDRBDMinor(self.op.nodes, instance.name)
6343
          new_id = (self.op.nodes[0], self.op.nodes[1], old_port,
6344
                    new_minors[0], new_minors[1], old_secret)
6345
          assert len(disk.logical_id) == len(new_id)
6346
          mods.append((idx, new_id))
6347

    
6348
    # now that we have passed all asserts above, we can apply the mods
6349
    # in a single run (to avoid partial changes)
6350
    for idx, new_id in mods:
6351
      instance.disks[idx].logical_id = new_id
6352

    
6353
    # change primary node, if needed
6354
    if self.op.nodes:
6355
      instance.primary_node = self.op.nodes[0]
6356
      self.LogWarning("Changing the instance's nodes, you will have to"
6357
                      " remove any disks left on the older nodes manually")
6358

    
6359
    if self.op.nodes:
6360
      self.cfg.Update(instance, feedback_fn)
6361

    
6362
    _CreateDisks(self, instance, to_skip=to_skip)
6363

    
6364

    
6365
class LUInstanceRename(LogicalUnit):
6366
  """Rename an instance.
6367

6368
  """
6369
  HPATH = "instance-rename"
6370
  HTYPE = constants.HTYPE_INSTANCE
6371

    
6372
  def CheckArguments(self):
6373
    """Check arguments.
6374

6375
    """
6376
    if self.op.ip_check and not self.op.name_check:
6377
      # TODO: make the ip check more flexible and not depend on the name check
6378
      raise errors.OpPrereqError("IP address check requires a name check",
6379
                                 errors.ECODE_INVAL)
6380

    
6381
  def BuildHooksEnv(self):
6382
    """Build hooks env.
6383

6384
    This runs on master, primary and secondary nodes of the instance.
6385

6386
    """
6387
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6388
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6389
    return env
6390

    
6391
  def BuildHooksNodes(self):
6392
    """Build hooks nodes.
6393

6394
    """
6395
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6396
    return (nl, nl)
6397

    
6398
  def CheckPrereq(self):
6399
    """Check prerequisites.
6400

6401
    This checks that the instance is in the cluster and is not running.
6402

6403
    """
6404
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6405
                                                self.op.instance_name)
6406
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6407
    assert instance is not None
6408
    _CheckNodeOnline(self, instance.primary_node)
6409
    _CheckInstanceDown(self, instance, "cannot rename")
6410
    self.instance = instance
6411

    
6412
    new_name = self.op.new_name
6413
    if self.op.name_check:
6414
      hostname = netutils.GetHostname(name=new_name)
6415
      if hostname != new_name:
6416
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6417
                     hostname.name)
6418
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6419
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6420
                                    " same as given hostname '%s'") %
6421
                                    (hostname.name, self.op.new_name),
6422
                                    errors.ECODE_INVAL)
6423
      new_name = self.op.new_name = hostname.name
6424
      if (self.op.ip_check and
6425
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6426
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6427
                                   (hostname.ip, new_name),
6428
                                   errors.ECODE_NOTUNIQUE)
6429

    
6430
    instance_list = self.cfg.GetInstanceList()
6431
    if new_name in instance_list and new_name != instance.name:
6432
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6433
                                 new_name, errors.ECODE_EXISTS)
6434

    
6435
  def Exec(self, feedback_fn):
6436
    """Rename the instance.
6437

6438
    """
6439
    inst = self.instance
6440
    old_name = inst.name
6441

    
6442
    rename_file_storage = False
6443
    if (inst.disk_template in constants.DTS_FILEBASED and
6444
        self.op.new_name != inst.name):
6445
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6446
      rename_file_storage = True
6447

    
6448
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6449
    # Change the instance lock. This is definitely safe while we hold the BGL.
6450
    # Otherwise the new lock would have to be added in acquired mode.
6451
    assert self.REQ_BGL
6452
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6453
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6454

    
6455
    # re-read the instance from the configuration after rename
6456
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6457

    
6458
    if rename_file_storage:
6459
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6460
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6461
                                                     old_file_storage_dir,
6462
                                                     new_file_storage_dir)
6463
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6464
                   " (but the instance has been renamed in Ganeti)" %
6465
                   (inst.primary_node, old_file_storage_dir,
6466
                    new_file_storage_dir))
6467

    
6468
    _StartInstanceDisks(self, inst, None)
6469
    try:
6470
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6471
                                                 old_name, self.op.debug_level)
6472
      msg = result.fail_msg
6473
      if msg:
6474
        msg = ("Could not run OS rename script for instance %s on node %s"
6475
               " (but the instance has been renamed in Ganeti): %s" %
6476
               (inst.name, inst.primary_node, msg))
6477
        self.proc.LogWarning(msg)
6478
    finally:
6479
      _ShutdownInstanceDisks(self, inst)
6480

    
6481
    return inst.name
6482

    
6483

    
6484
class LUInstanceRemove(LogicalUnit):
6485
  """Remove an instance.
6486

6487
  """
6488
  HPATH = "instance-remove"
6489
  HTYPE = constants.HTYPE_INSTANCE
6490
  REQ_BGL = False
6491

    
6492
  def ExpandNames(self):
6493
    self._ExpandAndLockInstance()
6494
    self.needed_locks[locking.LEVEL_NODE] = []
6495
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6496

    
6497
  def DeclareLocks(self, level):
6498
    if level == locking.LEVEL_NODE:
6499
      self._LockInstancesNodes()
6500

    
6501
  def BuildHooksEnv(self):
6502
    """Build hooks env.
6503

6504
    This runs on master, primary and secondary nodes of the instance.
6505

6506
    """
6507
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6508
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6509
    return env
6510

    
6511
  def BuildHooksNodes(self):
6512
    """Build hooks nodes.
6513

6514
    """
6515
    nl = [self.cfg.GetMasterNode()]
6516
    nl_post = list(self.instance.all_nodes) + nl
6517
    return (nl, nl_post)
6518

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

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

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

    
6529
  def Exec(self, feedback_fn):
6530
    """Remove the instance.
6531

6532
    """
6533
    instance = self.instance
6534
    logging.info("Shutting down instance %s on node %s",
6535
                 instance.name, instance.primary_node)
6536

    
6537
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6538
                                             self.op.shutdown_timeout)
6539
    msg = result.fail_msg
6540
    if msg:
6541
      if self.op.ignore_failures:
6542
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6543
      else:
6544
        raise errors.OpExecError("Could not shutdown instance %s on"
6545
                                 " node %s: %s" %
6546
                                 (instance.name, instance.primary_node, msg))
6547

    
6548
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6549

    
6550

    
6551
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6552
  """Utility function to remove an instance.
6553

6554
  """
6555
  logging.info("Removing block devices for instance %s", instance.name)
6556

    
6557
  if not _RemoveDisks(lu, instance):
6558
    if not ignore_failures:
6559
      raise errors.OpExecError("Can't remove instance's disks")
6560
    feedback_fn("Warning: can't remove instance's disks")
6561

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

    
6564
  lu.cfg.RemoveInstance(instance.name)
6565

    
6566
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6567
    "Instance lock removal conflict"
6568

    
6569
  # Remove lock for the instance
6570
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6571

    
6572

    
6573
class LUInstanceQuery(NoHooksLU):
6574
  """Logical unit for querying instances.
6575

6576
  """
6577
  # pylint: disable=W0142
6578
  REQ_BGL = False
6579

    
6580
  def CheckArguments(self):
6581
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6582
                             self.op.output_fields, self.op.use_locking)
6583

    
6584
  def ExpandNames(self):
6585
    self.iq.ExpandNames(self)
6586

    
6587
  def DeclareLocks(self, level):
6588
    self.iq.DeclareLocks(self, level)
6589

    
6590
  def Exec(self, feedback_fn):
6591
    return self.iq.OldStyleQuery(self)
6592

    
6593

    
6594
class LUInstanceFailover(LogicalUnit):
6595
  """Failover an instance.
6596

6597
  """
6598
  HPATH = "instance-failover"
6599
  HTYPE = constants.HTYPE_INSTANCE
6600
  REQ_BGL = False
6601

    
6602
  def CheckArguments(self):
6603
    """Check the arguments.
6604

6605
    """
6606
    self.iallocator = getattr(self.op, "iallocator", None)
6607
    self.target_node = getattr(self.op, "target_node", None)
6608

    
6609
  def ExpandNames(self):
6610
    self._ExpandAndLockInstance()
6611

    
6612
    if self.op.target_node is not None:
6613
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6614

    
6615
    self.needed_locks[locking.LEVEL_NODE] = []
6616
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6617

    
6618
    ignore_consistency = self.op.ignore_consistency
6619
    shutdown_timeout = self.op.shutdown_timeout
6620
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6621
                                       cleanup=False,
6622
                                       failover=True,
6623
                                       ignore_consistency=ignore_consistency,
6624
                                       shutdown_timeout=shutdown_timeout)
6625
    self.tasklets = [self._migrater]
6626

    
6627
  def DeclareLocks(self, level):
6628
    if level == locking.LEVEL_NODE:
6629
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6630
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6631
        if self.op.target_node is None:
6632
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6633
        else:
6634
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6635
                                                   self.op.target_node]
6636
        del self.recalculate_locks[locking.LEVEL_NODE]
6637
      else:
6638
        self._LockInstancesNodes()
6639

    
6640
  def BuildHooksEnv(self):
6641
    """Build hooks env.
6642

6643
    This runs on master, primary and secondary nodes of the instance.
6644

6645
    """
6646
    instance = self._migrater.instance
6647
    source_node = instance.primary_node
6648
    target_node = self.op.target_node
6649
    env = {
6650
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6651
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6652
      "OLD_PRIMARY": source_node,
6653
      "NEW_PRIMARY": target_node,
6654
      }
6655

    
6656
    if instance.disk_template in constants.DTS_INT_MIRROR:
6657
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6658
      env["NEW_SECONDARY"] = source_node
6659
    else:
6660
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6661

    
6662
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6663

    
6664
    return env
6665

    
6666
  def BuildHooksNodes(self):
6667
    """Build hooks nodes.
6668

6669
    """
6670
    instance = self._migrater.instance
6671
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6672
    return (nl, nl + [instance.primary_node])
6673

    
6674

    
6675
class LUInstanceMigrate(LogicalUnit):
6676
  """Migrate an instance.
6677

6678
  This is migration without shutting down, compared to the failover,
6679
  which is done with shutdown.
6680

6681
  """
6682
  HPATH = "instance-migrate"
6683
  HTYPE = constants.HTYPE_INSTANCE
6684
  REQ_BGL = False
6685

    
6686
  def ExpandNames(self):
6687
    self._ExpandAndLockInstance()
6688

    
6689
    if self.op.target_node is not None:
6690
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6691

    
6692
    self.needed_locks[locking.LEVEL_NODE] = []
6693
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6694

    
6695
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6696
                                       cleanup=self.op.cleanup,
6697
                                       failover=False,
6698
                                       fallback=self.op.allow_failover)
6699
    self.tasklets = [self._migrater]
6700

    
6701
  def DeclareLocks(self, level):
6702
    if level == locking.LEVEL_NODE:
6703
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6704
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6705
        if self.op.target_node is None:
6706
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6707
        else:
6708
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6709
                                                   self.op.target_node]
6710
        del self.recalculate_locks[locking.LEVEL_NODE]
6711
      else:
6712
        self._LockInstancesNodes()
6713

    
6714
  def BuildHooksEnv(self):
6715
    """Build hooks env.
6716

6717
    This runs on master, primary and secondary nodes of the instance.
6718

6719
    """
6720
    instance = self._migrater.instance
6721
    source_node = instance.primary_node
6722
    target_node = self.op.target_node
6723
    env = _BuildInstanceHookEnvByObject(self, instance)
6724
    env.update({
6725
      "MIGRATE_LIVE": self._migrater.live,
6726
      "MIGRATE_CLEANUP": self.op.cleanup,
6727
      "OLD_PRIMARY": source_node,
6728
      "NEW_PRIMARY": target_node,
6729
      })
6730

    
6731
    if instance.disk_template in constants.DTS_INT_MIRROR:
6732
      env["OLD_SECONDARY"] = target_node
6733
      env["NEW_SECONDARY"] = source_node
6734
    else:
6735
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6736

    
6737
    return env
6738

    
6739
  def BuildHooksNodes(self):
6740
    """Build hooks nodes.
6741

6742
    """
6743
    instance = self._migrater.instance
6744
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6745
    return (nl, nl + [instance.primary_node])
6746

    
6747

    
6748
class LUInstanceMove(LogicalUnit):
6749
  """Move an instance by data-copying.
6750

6751
  """
6752
  HPATH = "instance-move"
6753
  HTYPE = constants.HTYPE_INSTANCE
6754
  REQ_BGL = False
6755

    
6756
  def ExpandNames(self):
6757
    self._ExpandAndLockInstance()
6758
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6759
    self.op.target_node = target_node
6760
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6761
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6762

    
6763
  def DeclareLocks(self, level):
6764
    if level == locking.LEVEL_NODE:
6765
      self._LockInstancesNodes(primary_only=True)
6766

    
6767
  def BuildHooksEnv(self):
6768
    """Build hooks env.
6769

6770
    This runs on master, primary and secondary nodes of the instance.
6771

6772
    """
6773
    env = {
6774
      "TARGET_NODE": self.op.target_node,
6775
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6776
      }
6777
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6778
    return env
6779

    
6780
  def BuildHooksNodes(self):
6781
    """Build hooks nodes.
6782

6783
    """
6784
    nl = [
6785
      self.cfg.GetMasterNode(),
6786
      self.instance.primary_node,
6787
      self.op.target_node,
6788
      ]
6789
    return (nl, nl)
6790

    
6791
  def CheckPrereq(self):
6792
    """Check prerequisites.
6793

6794
    This checks that the instance is in the cluster.
6795

6796
    """
6797
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6798
    assert self.instance is not None, \
6799
      "Cannot retrieve locked instance %s" % self.op.instance_name
6800

    
6801
    node = self.cfg.GetNodeInfo(self.op.target_node)
6802
    assert node is not None, \
6803
      "Cannot retrieve locked node %s" % self.op.target_node
6804

    
6805
    self.target_node = target_node = node.name
6806

    
6807
    if target_node == instance.primary_node:
6808
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6809
                                 (instance.name, target_node),
6810
                                 errors.ECODE_STATE)
6811

    
6812
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6813

    
6814
    for idx, dsk in enumerate(instance.disks):
6815
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6816
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6817
                                   " cannot copy" % idx, errors.ECODE_STATE)
6818

    
6819
    _CheckNodeOnline(self, target_node)
6820
    _CheckNodeNotDrained(self, target_node)
6821
    _CheckNodeVmCapable(self, target_node)
6822

    
6823
    if instance.admin_up:
6824
      # check memory requirements on the secondary node
6825
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6826
                           instance.name, bep[constants.BE_MEMORY],
6827
                           instance.hypervisor)
6828
    else:
6829
      self.LogInfo("Not checking memory on the secondary node as"
6830
                   " instance will not be started")
6831

    
6832
    # check bridge existance
6833
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6834

    
6835
  def Exec(self, feedback_fn):
6836
    """Move an instance.
6837

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

6841
    """
6842
    instance = self.instance
6843

    
6844
    source_node = instance.primary_node
6845
    target_node = self.target_node
6846

    
6847
    self.LogInfo("Shutting down instance %s on source node %s",
6848
                 instance.name, source_node)
6849

    
6850
    result = self.rpc.call_instance_shutdown(source_node, instance,
6851
                                             self.op.shutdown_timeout)
6852
    msg = result.fail_msg
6853
    if msg:
6854
      if self.op.ignore_consistency:
6855
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6856
                             " Proceeding anyway. Please make sure node"
6857
                             " %s is down. Error details: %s",
6858
                             instance.name, source_node, source_node, msg)
6859
      else:
6860
        raise errors.OpExecError("Could not shutdown instance %s on"
6861
                                 " node %s: %s" %
6862
                                 (instance.name, source_node, msg))
6863

    
6864
    # create the target disks
6865
    try:
6866
      _CreateDisks(self, instance, target_node=target_node)
6867
    except errors.OpExecError:
6868
      self.LogWarning("Device creation failed, reverting...")
6869
      try:
6870
        _RemoveDisks(self, instance, target_node=target_node)
6871
      finally:
6872
        self.cfg.ReleaseDRBDMinors(instance.name)
6873
        raise
6874

    
6875
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6876

    
6877
    errs = []
6878
    # activate, get path, copy the data over
6879
    for idx, disk in enumerate(instance.disks):
6880
      self.LogInfo("Copying data for disk %d", idx)
6881
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6882
                                               instance.name, True, idx)
6883
      if result.fail_msg:
6884
        self.LogWarning("Can't assemble newly created disk %d: %s",
6885
                        idx, result.fail_msg)
6886
        errs.append(result.fail_msg)
6887
        break
6888
      dev_path = result.payload
6889
      result = self.rpc.call_blockdev_export(source_node, disk,
6890
                                             target_node, dev_path,
6891
                                             cluster_name)
6892
      if result.fail_msg:
6893
        self.LogWarning("Can't copy data over for disk %d: %s",
6894
                        idx, result.fail_msg)
6895
        errs.append(result.fail_msg)
6896
        break
6897

    
6898
    if errs:
6899
      self.LogWarning("Some disks failed to copy, aborting")
6900
      try:
6901
        _RemoveDisks(self, instance, target_node=target_node)
6902
      finally:
6903
        self.cfg.ReleaseDRBDMinors(instance.name)
6904
        raise errors.OpExecError("Errors during disk copy: %s" %
6905
                                 (",".join(errs),))
6906

    
6907
    instance.primary_node = target_node
6908
    self.cfg.Update(instance, feedback_fn)
6909

    
6910
    self.LogInfo("Removing the disks on the original node")
6911
    _RemoveDisks(self, instance, target_node=source_node)
6912

    
6913
    # Only start the instance if it's marked as up
6914
    if instance.admin_up:
6915
      self.LogInfo("Starting instance %s on node %s",
6916
                   instance.name, target_node)
6917

    
6918
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6919
                                           ignore_secondaries=True)
6920
      if not disks_ok:
6921
        _ShutdownInstanceDisks(self, instance)
6922
        raise errors.OpExecError("Can't activate the instance's disks")
6923

    
6924
      result = self.rpc.call_instance_start(target_node, instance,
6925
                                            None, None, False)
6926
      msg = result.fail_msg
6927
      if msg:
6928
        _ShutdownInstanceDisks(self, instance)
6929
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6930
                                 (instance.name, target_node, msg))
6931

    
6932

    
6933
class LUNodeMigrate(LogicalUnit):
6934
  """Migrate all instances from a node.
6935

6936
  """
6937
  HPATH = "node-migrate"
6938
  HTYPE = constants.HTYPE_NODE
6939
  REQ_BGL = False
6940

    
6941
  def CheckArguments(self):
6942
    pass
6943

    
6944
  def ExpandNames(self):
6945
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6946

    
6947
    self.share_locks = _ShareAll()
6948
    self.needed_locks = {
6949
      locking.LEVEL_NODE: [self.op.node_name],
6950
      }
6951

    
6952
  def BuildHooksEnv(self):
6953
    """Build hooks env.
6954

6955
    This runs on the master, the primary and all the secondaries.
6956

6957
    """
6958
    return {
6959
      "NODE_NAME": self.op.node_name,
6960
      }
6961

    
6962
  def BuildHooksNodes(self):
6963
    """Build hooks nodes.
6964

6965
    """
6966
    nl = [self.cfg.GetMasterNode()]
6967
    return (nl, nl)
6968

    
6969
  def CheckPrereq(self):
6970
    pass
6971

    
6972
  def Exec(self, feedback_fn):
6973
    # Prepare jobs for migration instances
6974
    jobs = [
6975
      [opcodes.OpInstanceMigrate(instance_name=inst.name,
6976
                                 mode=self.op.mode,
6977
                                 live=self.op.live,
6978
                                 iallocator=self.op.iallocator,
6979
                                 target_node=self.op.target_node)]
6980
      for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name)
6981
      ]
6982

    
6983
    # TODO: Run iallocator in this opcode and pass correct placement options to
6984
    # OpInstanceMigrate. Since other jobs can modify the cluster between
6985
    # running the iallocator and the actual migration, a good consistency model
6986
    # will have to be found.
6987

    
6988
    assert (frozenset(self.owned_locks(locking.LEVEL_NODE)) ==
6989
            frozenset([self.op.node_name]))
6990

    
6991
    return ResultWithJobs(jobs)
6992

    
6993

    
6994
class TLMigrateInstance(Tasklet):
6995
  """Tasklet class for instance migration.
6996

6997
  @type live: boolean
6998
  @ivar live: whether the migration will be done live or non-live;
6999
      this variable is initalized only after CheckPrereq has run
7000
  @type cleanup: boolean
7001
  @ivar cleanup: Wheater we cleanup from a failed migration
7002
  @type iallocator: string
7003
  @ivar iallocator: The iallocator used to determine target_node
7004
  @type target_node: string
7005
  @ivar target_node: If given, the target_node to reallocate the instance to
7006
  @type failover: boolean
7007
  @ivar failover: Whether operation results in failover or migration
7008
  @type fallback: boolean
7009
  @ivar fallback: Whether fallback to failover is allowed if migration not
7010
                  possible
7011
  @type ignore_consistency: boolean
7012
  @ivar ignore_consistency: Wheter we should ignore consistency between source
7013
                            and target node
7014
  @type shutdown_timeout: int
7015
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
7016

7017
  """
7018
  def __init__(self, lu, instance_name, cleanup=False,
7019
               failover=False, fallback=False,
7020
               ignore_consistency=False,
7021
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
7022
    """Initializes this class.
7023

7024
    """
7025
    Tasklet.__init__(self, lu)
7026

    
7027
    # Parameters
7028
    self.instance_name = instance_name
7029
    self.cleanup = cleanup
7030
    self.live = False # will be overridden later
7031
    self.failover = failover
7032
    self.fallback = fallback
7033
    self.ignore_consistency = ignore_consistency
7034
    self.shutdown_timeout = shutdown_timeout
7035

    
7036
  def CheckPrereq(self):
7037
    """Check prerequisites.
7038

7039
    This checks that the instance is in the cluster.
7040

7041
    """
7042
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
7043
    instance = self.cfg.GetInstanceInfo(instance_name)
7044
    assert instance is not None
7045
    self.instance = instance
7046

    
7047
    if (not self.cleanup and not instance.admin_up and not self.failover and
7048
        self.fallback):
7049
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
7050
                      " to failover")
7051
      self.failover = True
7052

    
7053
    if instance.disk_template not in constants.DTS_MIRRORED:
7054
      if self.failover:
7055
        text = "failovers"
7056
      else:
7057
        text = "migrations"
7058
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
7059
                                 " %s" % (instance.disk_template, text),
7060
                                 errors.ECODE_STATE)
7061

    
7062
    if instance.disk_template in constants.DTS_EXT_MIRROR:
7063
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
7064

    
7065
      if self.lu.op.iallocator:
7066
        self._RunAllocator()
7067
      else:
7068
        # We set set self.target_node as it is required by
7069
        # BuildHooksEnv
7070
        self.target_node = self.lu.op.target_node
7071

    
7072
      # self.target_node is already populated, either directly or by the
7073
      # iallocator run
7074
      target_node = self.target_node
7075
      if self.target_node == instance.primary_node:
7076
        raise errors.OpPrereqError("Cannot migrate instance %s"
7077
                                   " to its primary (%s)" %
7078
                                   (instance.name, instance.primary_node))
7079

    
7080
      if len(self.lu.tasklets) == 1:
7081
        # It is safe to release locks only when we're the only tasklet
7082
        # in the LU
7083
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
7084
                      keep=[instance.primary_node, self.target_node])
7085

    
7086
    else:
7087
      secondary_nodes = instance.secondary_nodes
7088
      if not secondary_nodes:
7089
        raise errors.ConfigurationError("No secondary node but using"
7090
                                        " %s disk template" %
7091
                                        instance.disk_template)
7092
      target_node = secondary_nodes[0]
7093
      if self.lu.op.iallocator or (self.lu.op.target_node and
7094
                                   self.lu.op.target_node != target_node):
7095
        if self.failover:
7096
          text = "failed over"
7097
        else:
7098
          text = "migrated"
7099
        raise errors.OpPrereqError("Instances with disk template %s cannot"
7100
                                   " be %s to arbitrary nodes"
7101
                                   " (neither an iallocator nor a target"
7102
                                   " node can be passed)" %
7103
                                   (instance.disk_template, text),
7104
                                   errors.ECODE_INVAL)
7105

    
7106
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
7107

    
7108
    # check memory requirements on the secondary node
7109
    if not self.failover or instance.admin_up:
7110
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
7111
                           instance.name, i_be[constants.BE_MEMORY],
7112
                           instance.hypervisor)
7113
    else:
7114
      self.lu.LogInfo("Not checking memory on the secondary node as"
7115
                      " instance will not be started")
7116

    
7117
    # check bridge existance
7118
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
7119

    
7120
    if not self.cleanup:
7121
      _CheckNodeNotDrained(self.lu, target_node)
7122
      if not self.failover:
7123
        result = self.rpc.call_instance_migratable(instance.primary_node,
7124
                                                   instance)
7125
        if result.fail_msg and self.fallback:
7126
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
7127
                          " failover")
7128
          self.failover = True
7129
        else:
7130
          result.Raise("Can't migrate, please use failover",
7131
                       prereq=True, ecode=errors.ECODE_STATE)
7132

    
7133
    assert not (self.failover and self.cleanup)
7134

    
7135
    if not self.failover:
7136
      if self.lu.op.live is not None and self.lu.op.mode is not None:
7137
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
7138
                                   " parameters are accepted",
7139
                                   errors.ECODE_INVAL)
7140
      if self.lu.op.live is not None:
7141
        if self.lu.op.live:
7142
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
7143
        else:
7144
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
7145
        # reset the 'live' parameter to None so that repeated
7146
        # invocations of CheckPrereq do not raise an exception
7147
        self.lu.op.live = None
7148
      elif self.lu.op.mode is None:
7149
        # read the default value from the hypervisor
7150
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
7151
                                                skip_globals=False)
7152
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
7153

    
7154
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
7155
    else:
7156
      # Failover is never live
7157
      self.live = False
7158

    
7159
  def _RunAllocator(self):
7160
    """Run the allocator based on input opcode.
7161

7162
    """
7163
    ial = IAllocator(self.cfg, self.rpc,
7164
                     mode=constants.IALLOCATOR_MODE_RELOC,
7165
                     name=self.instance_name,
7166
                     # TODO See why hail breaks with a single node below
7167
                     relocate_from=[self.instance.primary_node,
7168
                                    self.instance.primary_node],
7169
                     )
7170

    
7171
    ial.Run(self.lu.op.iallocator)
7172

    
7173
    if not ial.success:
7174
      raise errors.OpPrereqError("Can't compute nodes using"
7175
                                 " iallocator '%s': %s" %
7176
                                 (self.lu.op.iallocator, ial.info),
7177
                                 errors.ECODE_NORES)
7178
    if len(ial.result) != ial.required_nodes:
7179
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7180
                                 " of nodes (%s), required %s" %
7181
                                 (self.lu.op.iallocator, len(ial.result),
7182
                                  ial.required_nodes), errors.ECODE_FAULT)
7183
    self.target_node = ial.result[0]
7184
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7185
                 self.instance_name, self.lu.op.iallocator,
7186
                 utils.CommaJoin(ial.result))
7187

    
7188
  def _WaitUntilSync(self):
7189
    """Poll with custom rpc for disk sync.
7190

7191
    This uses our own step-based rpc call.
7192

7193
    """
7194
    self.feedback_fn("* wait until resync is done")
7195
    all_done = False
7196
    while not all_done:
7197
      all_done = True
7198
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
7199
                                            self.nodes_ip,
7200
                                            self.instance.disks)
7201
      min_percent = 100
7202
      for node, nres in result.items():
7203
        nres.Raise("Cannot resync disks on node %s" % node)
7204
        node_done, node_percent = nres.payload
7205
        all_done = all_done and node_done
7206
        if node_percent is not None:
7207
          min_percent = min(min_percent, node_percent)
7208
      if not all_done:
7209
        if min_percent < 100:
7210
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
7211
        time.sleep(2)
7212

    
7213
  def _EnsureSecondary(self, node):
7214
    """Demote a node to secondary.
7215

7216
    """
7217
    self.feedback_fn("* switching node %s to secondary mode" % node)
7218

    
7219
    for dev in self.instance.disks:
7220
      self.cfg.SetDiskID(dev, node)
7221

    
7222
    result = self.rpc.call_blockdev_close(node, self.instance.name,
7223
                                          self.instance.disks)
7224
    result.Raise("Cannot change disk to secondary on node %s" % node)
7225

    
7226
  def _GoStandalone(self):
7227
    """Disconnect from the network.
7228

7229
    """
7230
    self.feedback_fn("* changing into standalone mode")
7231
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
7232
                                               self.instance.disks)
7233
    for node, nres in result.items():
7234
      nres.Raise("Cannot disconnect disks node %s" % node)
7235

    
7236
  def _GoReconnect(self, multimaster):
7237
    """Reconnect to the network.
7238

7239
    """
7240
    if multimaster:
7241
      msg = "dual-master"
7242
    else:
7243
      msg = "single-master"
7244
    self.feedback_fn("* changing disks into %s mode" % msg)
7245
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
7246
                                           self.instance.disks,
7247
                                           self.instance.name, multimaster)
7248
    for node, nres in result.items():
7249
      nres.Raise("Cannot change disks config on node %s" % node)
7250

    
7251
  def _ExecCleanup(self):
7252
    """Try to cleanup after a failed migration.
7253

7254
    The cleanup is done by:
7255
      - check that the instance is running only on one node
7256
        (and update the config if needed)
7257
      - change disks on its secondary node to secondary
7258
      - wait until disks are fully synchronized
7259
      - disconnect from the network
7260
      - change disks into single-master mode
7261
      - wait again until disks are fully synchronized
7262

7263
    """
7264
    instance = self.instance
7265
    target_node = self.target_node
7266
    source_node = self.source_node
7267

    
7268
    # check running on only one node
7269
    self.feedback_fn("* checking where the instance actually runs"
7270
                     " (if this hangs, the hypervisor might be in"
7271
                     " a bad state)")
7272
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
7273
    for node, result in ins_l.items():
7274
      result.Raise("Can't contact node %s" % node)
7275

    
7276
    runningon_source = instance.name in ins_l[source_node].payload
7277
    runningon_target = instance.name in ins_l[target_node].payload
7278

    
7279
    if runningon_source and runningon_target:
7280
      raise errors.OpExecError("Instance seems to be running on two nodes,"
7281
                               " or the hypervisor is confused; you will have"
7282
                               " to ensure manually that it runs only on one"
7283
                               " and restart this operation")
7284

    
7285
    if not (runningon_source or runningon_target):
7286
      raise errors.OpExecError("Instance does not seem to be running at all;"
7287
                               " in this case it's safer to repair by"
7288
                               " running 'gnt-instance stop' to ensure disk"
7289
                               " shutdown, and then restarting it")
7290

    
7291
    if runningon_target:
7292
      # the migration has actually succeeded, we need to update the config
7293
      self.feedback_fn("* instance running on secondary node (%s),"
7294
                       " updating config" % target_node)
7295
      instance.primary_node = target_node
7296
      self.cfg.Update(instance, self.feedback_fn)
7297
      demoted_node = source_node
7298
    else:
7299
      self.feedback_fn("* instance confirmed to be running on its"
7300
                       " primary node (%s)" % source_node)
7301
      demoted_node = target_node
7302

    
7303
    if instance.disk_template in constants.DTS_INT_MIRROR:
7304
      self._EnsureSecondary(demoted_node)
7305
      try:
7306
        self._WaitUntilSync()
7307
      except errors.OpExecError:
7308
        # we ignore here errors, since if the device is standalone, it
7309
        # won't be able to sync
7310
        pass
7311
      self._GoStandalone()
7312
      self._GoReconnect(False)
7313
      self._WaitUntilSync()
7314

    
7315
    self.feedback_fn("* done")
7316

    
7317
  def _RevertDiskStatus(self):
7318
    """Try to revert the disk status after a failed migration.
7319

7320
    """
7321
    target_node = self.target_node
7322
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7323
      return
7324

    
7325
    try:
7326
      self._EnsureSecondary(target_node)
7327
      self._GoStandalone()
7328
      self._GoReconnect(False)
7329
      self._WaitUntilSync()
7330
    except errors.OpExecError, err:
7331
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7332
                         " please try to recover the instance manually;"
7333
                         " error '%s'" % str(err))
7334

    
7335
  def _AbortMigration(self):
7336
    """Call the hypervisor code to abort a started migration.
7337

7338
    """
7339
    instance = self.instance
7340
    target_node = self.target_node
7341
    migration_info = self.migration_info
7342

    
7343
    abort_result = self.rpc.call_finalize_migration(target_node,
7344
                                                    instance,
7345
                                                    migration_info,
7346
                                                    False)
7347
    abort_msg = abort_result.fail_msg
7348
    if abort_msg:
7349
      logging.error("Aborting migration failed on target node %s: %s",
7350
                    target_node, abort_msg)
7351
      # Don't raise an exception here, as we stil have to try to revert the
7352
      # disk status, even if this step failed.
7353

    
7354
  def _ExecMigration(self):
7355
    """Migrate an instance.
7356

7357
    The migrate is done by:
7358
      - change the disks into dual-master mode
7359
      - wait until disks are fully synchronized again
7360
      - migrate the instance
7361
      - change disks on the new secondary node (the old primary) to secondary
7362
      - wait until disks are fully synchronized
7363
      - change disks into single-master mode
7364

7365
    """
7366
    instance = self.instance
7367
    target_node = self.target_node
7368
    source_node = self.source_node
7369

    
7370
    # Check for hypervisor version mismatch and warn the user.
7371
    nodeinfo = self.rpc.call_node_info([source_node, target_node],
7372
                                       None, self.instance.hypervisor)
7373
    src_info = nodeinfo[source_node]
7374
    dst_info = nodeinfo[target_node]
7375

    
7376
    if ((constants.HV_NODEINFO_KEY_VERSION in src_info.payload) and
7377
        (constants.HV_NODEINFO_KEY_VERSION in dst_info.payload)):
7378
      src_version = src_info.payload[constants.HV_NODEINFO_KEY_VERSION]
7379
      dst_version = dst_info.payload[constants.HV_NODEINFO_KEY_VERSION]
7380
      if src_version != dst_version:
7381
        self.feedback_fn("* warning: hypervisor version mismatch between"
7382
                         " source (%s) and target (%s) node" %
7383
                         (src_version, dst_version))
7384

    
7385
    self.feedback_fn("* checking disk consistency between source and target")
7386
    for dev in instance.disks:
7387
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7388
        raise errors.OpExecError("Disk %s is degraded or not fully"
7389
                                 " synchronized on target node,"
7390
                                 " aborting migration" % dev.iv_name)
7391

    
7392
    # First get the migration information from the remote node
7393
    result = self.rpc.call_migration_info(source_node, instance)
7394
    msg = result.fail_msg
7395
    if msg:
7396
      log_err = ("Failed fetching source migration information from %s: %s" %
7397
                 (source_node, msg))
7398
      logging.error(log_err)
7399
      raise errors.OpExecError(log_err)
7400

    
7401
    self.migration_info = migration_info = result.payload
7402

    
7403
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7404
      # Then switch the disks to master/master mode
7405
      self._EnsureSecondary(target_node)
7406
      self._GoStandalone()
7407
      self._GoReconnect(True)
7408
      self._WaitUntilSync()
7409

    
7410
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7411
    result = self.rpc.call_accept_instance(target_node,
7412
                                           instance,
7413
                                           migration_info,
7414
                                           self.nodes_ip[target_node])
7415

    
7416
    msg = result.fail_msg
7417
    if msg:
7418
      logging.error("Instance pre-migration failed, trying to revert"
7419
                    " disk status: %s", msg)
7420
      self.feedback_fn("Pre-migration failed, aborting")
7421
      self._AbortMigration()
7422
      self._RevertDiskStatus()
7423
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7424
                               (instance.name, msg))
7425

    
7426
    self.feedback_fn("* migrating instance to %s" % target_node)
7427
    result = self.rpc.call_instance_migrate(source_node, instance,
7428
                                            self.nodes_ip[target_node],
7429
                                            self.live)
7430
    msg = result.fail_msg
7431
    if msg:
7432
      logging.error("Instance migration failed, trying to revert"
7433
                    " disk status: %s", msg)
7434
      self.feedback_fn("Migration failed, aborting")
7435
      self._AbortMigration()
7436
      self._RevertDiskStatus()
7437
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7438
                               (instance.name, msg))
7439

    
7440
    instance.primary_node = target_node
7441
    # distribute new instance config to the other nodes
7442
    self.cfg.Update(instance, self.feedback_fn)
7443

    
7444
    result = self.rpc.call_finalize_migration(target_node,
7445
                                              instance,
7446
                                              migration_info,
7447
                                              True)
7448
    msg = result.fail_msg
7449
    if msg:
7450
      logging.error("Instance migration succeeded, but finalization failed:"
7451
                    " %s", msg)
7452
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7453
                               msg)
7454

    
7455
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7456
      self._EnsureSecondary(source_node)
7457
      self._WaitUntilSync()
7458
      self._GoStandalone()
7459
      self._GoReconnect(False)
7460
      self._WaitUntilSync()
7461

    
7462
    self.feedback_fn("* done")
7463

    
7464
  def _ExecFailover(self):
7465
    """Failover an instance.
7466

7467
    The failover is done by shutting it down on its present node and
7468
    starting it on the secondary.
7469

7470
    """
7471
    instance = self.instance
7472
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7473

    
7474
    source_node = instance.primary_node
7475
    target_node = self.target_node
7476

    
7477
    if instance.admin_up:
7478
      self.feedback_fn("* checking disk consistency between source and target")
7479
      for dev in instance.disks:
7480
        # for drbd, these are drbd over lvm
7481
        if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7482
          if primary_node.offline:
7483
            self.feedback_fn("Node %s is offline, ignoring degraded disk %s on"
7484
                             " target node %s" %
7485
                             (primary_node.name, dev.iv_name, target_node))
7486
          elif not self.ignore_consistency:
7487
            raise errors.OpExecError("Disk %s is degraded on target node,"
7488
                                     " aborting failover" % dev.iv_name)
7489
    else:
7490
      self.feedback_fn("* not checking disk consistency as instance is not"
7491
                       " running")
7492

    
7493
    self.feedback_fn("* shutting down instance on source node")
7494
    logging.info("Shutting down instance %s on node %s",
7495
                 instance.name, source_node)
7496

    
7497
    result = self.rpc.call_instance_shutdown(source_node, instance,
7498
                                             self.shutdown_timeout)
7499
    msg = result.fail_msg
7500
    if msg:
7501
      if self.ignore_consistency or primary_node.offline:
7502
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7503
                           " proceeding anyway; please make sure node"
7504
                           " %s is down; error details: %s",
7505
                           instance.name, source_node, source_node, msg)
7506
      else:
7507
        raise errors.OpExecError("Could not shutdown instance %s on"
7508
                                 " node %s: %s" %
7509
                                 (instance.name, source_node, msg))
7510

    
7511
    self.feedback_fn("* deactivating the instance's disks on source node")
7512
    if not _ShutdownInstanceDisks(self.lu, instance, ignore_primary=True):
7513
      raise errors.OpExecError("Can't shut down the instance's disks")
7514

    
7515
    instance.primary_node = target_node
7516
    # distribute new instance config to the other nodes
7517
    self.cfg.Update(instance, self.feedback_fn)
7518

    
7519
    # Only start the instance if it's marked as up
7520
    if instance.admin_up:
7521
      self.feedback_fn("* activating the instance's disks on target node %s" %
7522
                       target_node)
7523
      logging.info("Starting instance %s on node %s",
7524
                   instance.name, target_node)
7525

    
7526
      disks_ok, _ = _AssembleInstanceDisks(self.lu, instance,
7527
                                           ignore_secondaries=True)
7528
      if not disks_ok:
7529
        _ShutdownInstanceDisks(self.lu, instance)
7530
        raise errors.OpExecError("Can't activate the instance's disks")
7531

    
7532
      self.feedback_fn("* starting the instance on the target node %s" %
7533
                       target_node)
7534
      result = self.rpc.call_instance_start(target_node, instance, None, None,
7535
                                            False)
7536
      msg = result.fail_msg
7537
      if msg:
7538
        _ShutdownInstanceDisks(self.lu, instance)
7539
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7540
                                 (instance.name, target_node, msg))
7541

    
7542
  def Exec(self, feedback_fn):
7543
    """Perform the migration.
7544

7545
    """
7546
    self.feedback_fn = feedback_fn
7547
    self.source_node = self.instance.primary_node
7548

    
7549
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7550
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7551
      self.target_node = self.instance.secondary_nodes[0]
7552
      # Otherwise self.target_node has been populated either
7553
      # directly, or through an iallocator.
7554

    
7555
    self.all_nodes = [self.source_node, self.target_node]
7556
    self.nodes_ip = dict((name, node.secondary_ip) for (name, node)
7557
                         in self.cfg.GetMultiNodeInfo(self.all_nodes))
7558

    
7559
    if self.failover:
7560
      feedback_fn("Failover instance %s" % self.instance.name)
7561
      self._ExecFailover()
7562
    else:
7563
      feedback_fn("Migrating instance %s" % self.instance.name)
7564

    
7565
      if self.cleanup:
7566
        return self._ExecCleanup()
7567
      else:
7568
        return self._ExecMigration()
7569

    
7570

    
7571
def _CreateBlockDev(lu, node, instance, device, force_create,
7572
                    info, force_open):
7573
  """Create a tree of block devices on a given node.
7574

7575
  If this device type has to be created on secondaries, create it and
7576
  all its children.
7577

7578
  If not, just recurse to children keeping the same 'force' value.
7579

7580
  @param lu: the lu on whose behalf we execute
7581
  @param node: the node on which to create the device
7582
  @type instance: L{objects.Instance}
7583
  @param instance: the instance which owns the device
7584
  @type device: L{objects.Disk}
7585
  @param device: the device to create
7586
  @type force_create: boolean
7587
  @param force_create: whether to force creation of this device; this
7588
      will be change to True whenever we find a device which has
7589
      CreateOnSecondary() attribute
7590
  @param info: the extra 'metadata' we should attach to the device
7591
      (this will be represented as a LVM tag)
7592
  @type force_open: boolean
7593
  @param force_open: this parameter will be passes to the
7594
      L{backend.BlockdevCreate} function where it specifies
7595
      whether we run on primary or not, and it affects both
7596
      the child assembly and the device own Open() execution
7597

7598
  """
7599
  if device.CreateOnSecondary():
7600
    force_create = True
7601

    
7602
  if device.children:
7603
    for child in device.children:
7604
      _CreateBlockDev(lu, node, instance, child, force_create,
7605
                      info, force_open)
7606

    
7607
  if not force_create:
7608
    return
7609

    
7610
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7611

    
7612

    
7613
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7614
  """Create a single block device on a given node.
7615

7616
  This will not recurse over children of the device, so they must be
7617
  created in advance.
7618

7619
  @param lu: the lu on whose behalf we execute
7620
  @param node: the node on which to create the device
7621
  @type instance: L{objects.Instance}
7622
  @param instance: the instance which owns the device
7623
  @type device: L{objects.Disk}
7624
  @param device: the device to create
7625
  @param info: the extra 'metadata' we should attach to the device
7626
      (this will be represented as a LVM tag)
7627
  @type force_open: boolean
7628
  @param force_open: this parameter will be passes to the
7629
      L{backend.BlockdevCreate} function where it specifies
7630
      whether we run on primary or not, and it affects both
7631
      the child assembly and the device own Open() execution
7632

7633
  """
7634
  lu.cfg.SetDiskID(device, node)
7635
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7636
                                       instance.name, force_open, info)
7637
  result.Raise("Can't create block device %s on"
7638
               " node %s for instance %s" % (device, node, instance.name))
7639
  if device.physical_id is None:
7640
    device.physical_id = result.payload
7641

    
7642

    
7643
def _GenerateUniqueNames(lu, exts):
7644
  """Generate a suitable LV name.
7645

7646
  This will generate a logical volume name for the given instance.
7647

7648
  """
7649
  results = []
7650
  for val in exts:
7651
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7652
    results.append("%s%s" % (new_id, val))
7653
  return results
7654

    
7655

    
7656
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7657
                         iv_name, p_minor, s_minor):
7658
  """Generate a drbd8 device complete with its children.
7659

7660
  """
7661
  assert len(vgnames) == len(names) == 2
7662
  port = lu.cfg.AllocatePort()
7663
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7664
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7665
                          logical_id=(vgnames[0], names[0]))
7666
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7667
                          logical_id=(vgnames[1], names[1]))
7668
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7669
                          logical_id=(primary, secondary, port,
7670
                                      p_minor, s_minor,
7671
                                      shared_secret),
7672
                          children=[dev_data, dev_meta],
7673
                          iv_name=iv_name)
7674
  return drbd_dev
7675

    
7676

    
7677
def _GenerateDiskTemplate(lu, template_name,
7678
                          instance_name, primary_node,
7679
                          secondary_nodes, disk_info,
7680
                          file_storage_dir, file_driver,
7681
                          base_index, feedback_fn):
7682
  """Generate the entire disk layout for a given template type.
7683

7684
  """
7685
  #TODO: compute space requirements
7686

    
7687
  vgname = lu.cfg.GetVGName()
7688
  disk_count = len(disk_info)
7689
  disks = []
7690
  if template_name == constants.DT_DISKLESS:
7691
    pass
7692
  elif template_name == constants.DT_PLAIN:
7693
    if len(secondary_nodes) != 0:
7694
      raise errors.ProgrammerError("Wrong template configuration")
7695

    
7696
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7697
                                      for i in range(disk_count)])
7698
    for idx, disk in enumerate(disk_info):
7699
      disk_index = idx + base_index
7700
      vg = disk.get(constants.IDISK_VG, vgname)
7701
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7702
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7703
                              size=disk[constants.IDISK_SIZE],
7704
                              logical_id=(vg, names[idx]),
7705
                              iv_name="disk/%d" % disk_index,
7706
                              mode=disk[constants.IDISK_MODE])
7707
      disks.append(disk_dev)
7708
  elif template_name == constants.DT_DRBD8:
7709
    if len(secondary_nodes) != 1:
7710
      raise errors.ProgrammerError("Wrong template configuration")
7711
    remote_node = secondary_nodes[0]
7712
    minors = lu.cfg.AllocateDRBDMinor(
7713
      [primary_node, remote_node] * len(disk_info), instance_name)
7714

    
7715
    names = []
7716
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7717
                                               for i in range(disk_count)]):
7718
      names.append(lv_prefix + "_data")
7719
      names.append(lv_prefix + "_meta")
7720
    for idx, disk in enumerate(disk_info):
7721
      disk_index = idx + base_index
7722
      data_vg = disk.get(constants.IDISK_VG, vgname)
7723
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7724
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7725
                                      disk[constants.IDISK_SIZE],
7726
                                      [data_vg, meta_vg],
7727
                                      names[idx * 2:idx * 2 + 2],
7728
                                      "disk/%d" % disk_index,
7729
                                      minors[idx * 2], minors[idx * 2 + 1])
7730
      disk_dev.mode = disk[constants.IDISK_MODE]
7731
      disks.append(disk_dev)
7732
  elif template_name == constants.DT_FILE:
7733
    if len(secondary_nodes) != 0:
7734
      raise errors.ProgrammerError("Wrong template configuration")
7735

    
7736
    opcodes.RequireFileStorage()
7737

    
7738
    for idx, disk in enumerate(disk_info):
7739
      disk_index = idx + base_index
7740
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7741
                              size=disk[constants.IDISK_SIZE],
7742
                              iv_name="disk/%d" % disk_index,
7743
                              logical_id=(file_driver,
7744
                                          "%s/disk%d" % (file_storage_dir,
7745
                                                         disk_index)),
7746
                              mode=disk[constants.IDISK_MODE])
7747
      disks.append(disk_dev)
7748
  elif template_name == constants.DT_SHARED_FILE:
7749
    if len(secondary_nodes) != 0:
7750
      raise errors.ProgrammerError("Wrong template configuration")
7751

    
7752
    opcodes.RequireSharedFileStorage()
7753

    
7754
    for idx, disk in enumerate(disk_info):
7755
      disk_index = idx + base_index
7756
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7757
                              size=disk[constants.IDISK_SIZE],
7758
                              iv_name="disk/%d" % disk_index,
7759
                              logical_id=(file_driver,
7760
                                          "%s/disk%d" % (file_storage_dir,
7761
                                                         disk_index)),
7762
                              mode=disk[constants.IDISK_MODE])
7763
      disks.append(disk_dev)
7764
  elif template_name == constants.DT_BLOCK:
7765
    if len(secondary_nodes) != 0:
7766
      raise errors.ProgrammerError("Wrong template configuration")
7767

    
7768
    for idx, disk in enumerate(disk_info):
7769
      disk_index = idx + base_index
7770
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7771
                              size=disk[constants.IDISK_SIZE],
7772
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7773
                                          disk[constants.IDISK_ADOPT]),
7774
                              iv_name="disk/%d" % disk_index,
7775
                              mode=disk[constants.IDISK_MODE])
7776
      disks.append(disk_dev)
7777

    
7778
  else:
7779
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7780
  return disks
7781

    
7782

    
7783
def _GetInstanceInfoText(instance):
7784
  """Compute that text that should be added to the disk's metadata.
7785

7786
  """
7787
  return "originstname+%s" % instance.name
7788

    
7789

    
7790
def _CalcEta(time_taken, written, total_size):
7791
  """Calculates the ETA based on size written and total size.
7792

7793
  @param time_taken: The time taken so far
7794
  @param written: amount written so far
7795
  @param total_size: The total size of data to be written
7796
  @return: The remaining time in seconds
7797

7798
  """
7799
  avg_time = time_taken / float(written)
7800
  return (total_size - written) * avg_time
7801

    
7802

    
7803
def _WipeDisks(lu, instance):
7804
  """Wipes instance disks.
7805

7806
  @type lu: L{LogicalUnit}
7807
  @param lu: the logical unit on whose behalf we execute
7808
  @type instance: L{objects.Instance}
7809
  @param instance: the instance whose disks we should create
7810
  @return: the success of the wipe
7811

7812
  """
7813
  node = instance.primary_node
7814

    
7815
  for device in instance.disks:
7816
    lu.cfg.SetDiskID(device, node)
7817

    
7818
  logging.info("Pause sync of instance %s disks", instance.name)
7819
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7820

    
7821
  for idx, success in enumerate(result.payload):
7822
    if not success:
7823
      logging.warn("pause-sync of instance %s for disks %d failed",
7824
                   instance.name, idx)
7825

    
7826
  try:
7827
    for idx, device in enumerate(instance.disks):
7828
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7829
      # MAX_WIPE_CHUNK at max
7830
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7831
                            constants.MIN_WIPE_CHUNK_PERCENT)
7832
      # we _must_ make this an int, otherwise rounding errors will
7833
      # occur
7834
      wipe_chunk_size = int(wipe_chunk_size)
7835

    
7836
      lu.LogInfo("* Wiping disk %d", idx)
7837
      logging.info("Wiping disk %d for instance %s, node %s using"
7838
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7839

    
7840
      offset = 0
7841
      size = device.size
7842
      last_output = 0
7843
      start_time = time.time()
7844

    
7845
      while offset < size:
7846
        wipe_size = min(wipe_chunk_size, size - offset)
7847
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7848
                      idx, offset, wipe_size)
7849
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7850
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7851
                     (idx, offset, wipe_size))
7852
        now = time.time()
7853
        offset += wipe_size
7854
        if now - last_output >= 60:
7855
          eta = _CalcEta(now - start_time, offset, size)
7856
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7857
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7858
          last_output = now
7859
  finally:
7860
    logging.info("Resume sync of instance %s disks", instance.name)
7861

    
7862
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7863

    
7864
    for idx, success in enumerate(result.payload):
7865
      if not success:
7866
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7867
                      " look at the status and troubleshoot the issue", idx)
7868
        logging.warn("resume-sync of instance %s for disks %d failed",
7869
                     instance.name, idx)
7870

    
7871

    
7872
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7873
  """Create all disks for an instance.
7874

7875
  This abstracts away some work from AddInstance.
7876

7877
  @type lu: L{LogicalUnit}
7878
  @param lu: the logical unit on whose behalf we execute
7879
  @type instance: L{objects.Instance}
7880
  @param instance: the instance whose disks we should create
7881
  @type to_skip: list
7882
  @param to_skip: list of indices to skip
7883
  @type target_node: string
7884
  @param target_node: if passed, overrides the target node for creation
7885
  @rtype: boolean
7886
  @return: the success of the creation
7887

7888
  """
7889
  info = _GetInstanceInfoText(instance)
7890
  if target_node is None:
7891
    pnode = instance.primary_node
7892
    all_nodes = instance.all_nodes
7893
  else:
7894
    pnode = target_node
7895
    all_nodes = [pnode]
7896

    
7897
  if instance.disk_template in constants.DTS_FILEBASED:
7898
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7899
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7900

    
7901
    result.Raise("Failed to create directory '%s' on"
7902
                 " node %s" % (file_storage_dir, pnode))
7903

    
7904
  # Note: this needs to be kept in sync with adding of disks in
7905
  # LUInstanceSetParams
7906
  for idx, device in enumerate(instance.disks):
7907
    if to_skip and idx in to_skip:
7908
      continue
7909
    logging.info("Creating volume %s for instance %s",
7910
                 device.iv_name, instance.name)
7911
    #HARDCODE
7912
    for node in all_nodes:
7913
      f_create = node == pnode
7914
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7915

    
7916

    
7917
def _RemoveDisks(lu, instance, target_node=None):
7918
  """Remove all disks for an instance.
7919

7920
  This abstracts away some work from `AddInstance()` and
7921
  `RemoveInstance()`. Note that in case some of the devices couldn't
7922
  be removed, the removal will continue with the other ones (compare
7923
  with `_CreateDisks()`).
7924

7925
  @type lu: L{LogicalUnit}
7926
  @param lu: the logical unit on whose behalf we execute
7927
  @type instance: L{objects.Instance}
7928
  @param instance: the instance whose disks we should remove
7929
  @type target_node: string
7930
  @param target_node: used to override the node on which to remove the disks
7931
  @rtype: boolean
7932
  @return: the success of the removal
7933

7934
  """
7935
  logging.info("Removing block devices for instance %s", instance.name)
7936

    
7937
  all_result = True
7938
  for device in instance.disks:
7939
    if target_node:
7940
      edata = [(target_node, device)]
7941
    else:
7942
      edata = device.ComputeNodeTree(instance.primary_node)
7943
    for node, disk in edata:
7944
      lu.cfg.SetDiskID(disk, node)
7945
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7946
      if msg:
7947
        lu.LogWarning("Could not remove block device %s on node %s,"
7948
                      " continuing anyway: %s", device.iv_name, node, msg)
7949
        all_result = False
7950

    
7951
  if instance.disk_template == constants.DT_FILE:
7952
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7953
    if target_node:
7954
      tgt = target_node
7955
    else:
7956
      tgt = instance.primary_node
7957
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7958
    if result.fail_msg:
7959
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7960
                    file_storage_dir, instance.primary_node, result.fail_msg)
7961
      all_result = False
7962

    
7963
  return all_result
7964

    
7965

    
7966
def _ComputeDiskSizePerVG(disk_template, disks):
7967
  """Compute disk size requirements in the volume group
7968

7969
  """
7970
  def _compute(disks, payload):
7971
    """Universal algorithm.
7972

7973
    """
7974
    vgs = {}
7975
    for disk in disks:
7976
      vgs[disk[constants.IDISK_VG]] = \
7977
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7978

    
7979
    return vgs
7980

    
7981
  # Required free disk space as a function of disk and swap space
7982
  req_size_dict = {
7983
    constants.DT_DISKLESS: {},
7984
    constants.DT_PLAIN: _compute(disks, 0),
7985
    # 128 MB are added for drbd metadata for each disk
7986
    constants.DT_DRBD8: _compute(disks, 128),
7987
    constants.DT_FILE: {},
7988
    constants.DT_SHARED_FILE: {},
7989
  }
7990

    
7991
  if disk_template not in req_size_dict:
7992
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7993
                                 " is unknown" % disk_template)
7994

    
7995
  return req_size_dict[disk_template]
7996

    
7997

    
7998
def _ComputeDiskSize(disk_template, disks):
7999
  """Compute disk size requirements in the volume group
8000

8001
  """
8002
  # Required free disk space as a function of disk and swap space
8003
  req_size_dict = {
8004
    constants.DT_DISKLESS: None,
8005
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
8006
    # 128 MB are added for drbd metadata for each disk
8007
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
8008
    constants.DT_FILE: None,
8009
    constants.DT_SHARED_FILE: 0,
8010
    constants.DT_BLOCK: 0,
8011
  }
8012

    
8013
  if disk_template not in req_size_dict:
8014
    raise errors.ProgrammerError("Disk template '%s' size requirement"
8015
                                 " is unknown" % disk_template)
8016

    
8017
  return req_size_dict[disk_template]
8018

    
8019

    
8020
def _FilterVmNodes(lu, nodenames):
8021
  """Filters out non-vm_capable nodes from a list.
8022

8023
  @type lu: L{LogicalUnit}
8024
  @param lu: the logical unit for which we check
8025
  @type nodenames: list
8026
  @param nodenames: the list of nodes on which we should check
8027
  @rtype: list
8028
  @return: the list of vm-capable nodes
8029

8030
  """
8031
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
8032
  return [name for name in nodenames if name not in vm_nodes]
8033

    
8034

    
8035
def _CheckHVParams(lu, nodenames, hvname, hvparams):
8036
  """Hypervisor parameter validation.
8037

8038
  This function abstract the hypervisor parameter validation to be
8039
  used in both instance create and instance modify.
8040

8041
  @type lu: L{LogicalUnit}
8042
  @param lu: the logical unit for which we check
8043
  @type nodenames: list
8044
  @param nodenames: the list of nodes on which we should check
8045
  @type hvname: string
8046
  @param hvname: the name of the hypervisor we should use
8047
  @type hvparams: dict
8048
  @param hvparams: the parameters which we need to check
8049
  @raise errors.OpPrereqError: if the parameters are not valid
8050

8051
  """
8052
  nodenames = _FilterVmNodes(lu, nodenames)
8053
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
8054
                                                  hvname,
8055
                                                  hvparams)
8056
  for node in nodenames:
8057
    info = hvinfo[node]
8058
    if info.offline:
8059
      continue
8060
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
8061

    
8062

    
8063
def _CheckOSParams(lu, required, nodenames, osname, osparams):
8064
  """OS parameters validation.
8065

8066
  @type lu: L{LogicalUnit}
8067
  @param lu: the logical unit for which we check
8068
  @type required: boolean
8069
  @param required: whether the validation should fail if the OS is not
8070
      found
8071
  @type nodenames: list
8072
  @param nodenames: the list of nodes on which we should check
8073
  @type osname: string
8074
  @param osname: the name of the hypervisor we should use
8075
  @type osparams: dict
8076
  @param osparams: the parameters which we need to check
8077
  @raise errors.OpPrereqError: if the parameters are not valid
8078

8079
  """
8080
  nodenames = _FilterVmNodes(lu, nodenames)
8081
  result = lu.rpc.call_os_validate(required, nodenames, osname,
8082
                                   [constants.OS_VALIDATE_PARAMETERS],
8083
                                   osparams)
8084
  for node, nres in result.items():
8085
    # we don't check for offline cases since this should be run only
8086
    # against the master node and/or an instance's nodes
8087
    nres.Raise("OS Parameters validation failed on node %s" % node)
8088
    if not nres.payload:
8089
      lu.LogInfo("OS %s not found on node %s, validation skipped",
8090
                 osname, node)
8091

    
8092

    
8093
class LUInstanceCreate(LogicalUnit):
8094
  """Create an instance.
8095

8096
  """
8097
  HPATH = "instance-add"
8098
  HTYPE = constants.HTYPE_INSTANCE
8099
  REQ_BGL = False
8100

    
8101
  def CheckArguments(self):
8102
    """Check arguments.
8103

8104
    """
8105
    # do not require name_check to ease forward/backward compatibility
8106
    # for tools
8107
    if self.op.no_install and self.op.start:
8108
      self.LogInfo("No-installation mode selected, disabling startup")
8109
      self.op.start = False
8110
    # validate/normalize the instance name
8111
    self.op.instance_name = \
8112
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
8113

    
8114
    if self.op.ip_check and not self.op.name_check:
8115
      # TODO: make the ip check more flexible and not depend on the name check
8116
      raise errors.OpPrereqError("Cannot do IP address check without a name"
8117
                                 " check", errors.ECODE_INVAL)
8118

    
8119
    # check nics' parameter names
8120
    for nic in self.op.nics:
8121
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
8122

    
8123
    # check disks. parameter names and consistent adopt/no-adopt strategy
8124
    has_adopt = has_no_adopt = False
8125
    for disk in self.op.disks:
8126
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
8127
      if constants.IDISK_ADOPT in disk:
8128
        has_adopt = True
8129
      else:
8130
        has_no_adopt = True
8131
    if has_adopt and has_no_adopt:
8132
      raise errors.OpPrereqError("Either all disks are adopted or none is",
8133
                                 errors.ECODE_INVAL)
8134
    if has_adopt:
8135
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
8136
        raise errors.OpPrereqError("Disk adoption is not supported for the"
8137
                                   " '%s' disk template" %
8138
                                   self.op.disk_template,
8139
                                   errors.ECODE_INVAL)
8140
      if self.op.iallocator is not None:
8141
        raise errors.OpPrereqError("Disk adoption not allowed with an"
8142
                                   " iallocator script", errors.ECODE_INVAL)
8143
      if self.op.mode == constants.INSTANCE_IMPORT:
8144
        raise errors.OpPrereqError("Disk adoption not allowed for"
8145
                                   " instance import", errors.ECODE_INVAL)
8146
    else:
8147
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
8148
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
8149
                                   " but no 'adopt' parameter given" %
8150
                                   self.op.disk_template,
8151
                                   errors.ECODE_INVAL)
8152

    
8153
    self.adopt_disks = has_adopt
8154

    
8155
    # instance name verification
8156
    if self.op.name_check:
8157
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
8158
      self.op.instance_name = self.hostname1.name
8159
      # used in CheckPrereq for ip ping check
8160
      self.check_ip = self.hostname1.ip
8161
    else:
8162
      self.check_ip = None
8163

    
8164
    # file storage checks
8165
    if (self.op.file_driver and
8166
        not self.op.file_driver in constants.FILE_DRIVER):
8167
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
8168
                                 self.op.file_driver, errors.ECODE_INVAL)
8169

    
8170
    if self.op.disk_template == constants.DT_FILE:
8171
      opcodes.RequireFileStorage()
8172
    elif self.op.disk_template == constants.DT_SHARED_FILE:
8173
      opcodes.RequireSharedFileStorage()
8174

    
8175
    ### Node/iallocator related checks
8176
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
8177

    
8178
    if self.op.pnode is not None:
8179
      if self.op.disk_template in constants.DTS_INT_MIRROR:
8180
        if self.op.snode is None:
8181
          raise errors.OpPrereqError("The networked disk templates need"
8182
                                     " a mirror node", errors.ECODE_INVAL)
8183
      elif self.op.snode:
8184
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
8185
                        " template")
8186
        self.op.snode = None
8187

    
8188
    self._cds = _GetClusterDomainSecret()
8189

    
8190
    if self.op.mode == constants.INSTANCE_IMPORT:
8191
      # On import force_variant must be True, because if we forced it at
8192
      # initial install, our only chance when importing it back is that it
8193
      # works again!
8194
      self.op.force_variant = True
8195

    
8196
      if self.op.no_install:
8197
        self.LogInfo("No-installation mode has no effect during import")
8198

    
8199
    elif self.op.mode == constants.INSTANCE_CREATE:
8200
      if self.op.os_type is None:
8201
        raise errors.OpPrereqError("No guest OS specified",
8202
                                   errors.ECODE_INVAL)
8203
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
8204
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
8205
                                   " installation" % self.op.os_type,
8206
                                   errors.ECODE_STATE)
8207
      if self.op.disk_template is None:
8208
        raise errors.OpPrereqError("No disk template specified",
8209
                                   errors.ECODE_INVAL)
8210

    
8211
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8212
      # Check handshake to ensure both clusters have the same domain secret
8213
      src_handshake = self.op.source_handshake
8214
      if not src_handshake:
8215
        raise errors.OpPrereqError("Missing source handshake",
8216
                                   errors.ECODE_INVAL)
8217

    
8218
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
8219
                                                           src_handshake)
8220
      if errmsg:
8221
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
8222
                                   errors.ECODE_INVAL)
8223

    
8224
      # Load and check source CA
8225
      self.source_x509_ca_pem = self.op.source_x509_ca
8226
      if not self.source_x509_ca_pem:
8227
        raise errors.OpPrereqError("Missing source X509 CA",
8228
                                   errors.ECODE_INVAL)
8229

    
8230
      try:
8231
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
8232
                                                    self._cds)
8233
      except OpenSSL.crypto.Error, err:
8234
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
8235
                                   (err, ), errors.ECODE_INVAL)
8236

    
8237
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
8238
      if errcode is not None:
8239
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
8240
                                   errors.ECODE_INVAL)
8241

    
8242
      self.source_x509_ca = cert
8243

    
8244
      src_instance_name = self.op.source_instance_name
8245
      if not src_instance_name:
8246
        raise errors.OpPrereqError("Missing source instance name",
8247
                                   errors.ECODE_INVAL)
8248

    
8249
      self.source_instance_name = \
8250
          netutils.GetHostname(name=src_instance_name).name
8251

    
8252
    else:
8253
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
8254
                                 self.op.mode, errors.ECODE_INVAL)
8255

    
8256
  def ExpandNames(self):
8257
    """ExpandNames for CreateInstance.
8258

8259
    Figure out the right locks for instance creation.
8260

8261
    """
8262
    self.needed_locks = {}
8263

    
8264
    instance_name = self.op.instance_name
8265
    # this is just a preventive check, but someone might still add this
8266
    # instance in the meantime, and creation will fail at lock-add time
8267
    if instance_name in self.cfg.GetInstanceList():
8268
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
8269
                                 instance_name, errors.ECODE_EXISTS)
8270

    
8271
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
8272

    
8273
    if self.op.iallocator:
8274
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8275
    else:
8276
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
8277
      nodelist = [self.op.pnode]
8278
      if self.op.snode is not None:
8279
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
8280
        nodelist.append(self.op.snode)
8281
      self.needed_locks[locking.LEVEL_NODE] = nodelist
8282

    
8283
    # in case of import lock the source node too
8284
    if self.op.mode == constants.INSTANCE_IMPORT:
8285
      src_node = self.op.src_node
8286
      src_path = self.op.src_path
8287

    
8288
      if src_path is None:
8289
        self.op.src_path = src_path = self.op.instance_name
8290

    
8291
      if src_node is None:
8292
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8293
        self.op.src_node = None
8294
        if os.path.isabs(src_path):
8295
          raise errors.OpPrereqError("Importing an instance from a path"
8296
                                     " requires a source node option",
8297
                                     errors.ECODE_INVAL)
8298
      else:
8299
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
8300
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
8301
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
8302
        if not os.path.isabs(src_path):
8303
          self.op.src_path = src_path = \
8304
            utils.PathJoin(constants.EXPORT_DIR, src_path)
8305

    
8306
  def _RunAllocator(self):
8307
    """Run the allocator based on input opcode.
8308

8309
    """
8310
    nics = [n.ToDict() for n in self.nics]
8311
    ial = IAllocator(self.cfg, self.rpc,
8312
                     mode=constants.IALLOCATOR_MODE_ALLOC,
8313
                     name=self.op.instance_name,
8314
                     disk_template=self.op.disk_template,
8315
                     tags=self.op.tags,
8316
                     os=self.op.os_type,
8317
                     vcpus=self.be_full[constants.BE_VCPUS],
8318
                     memory=self.be_full[constants.BE_MEMORY],
8319
                     disks=self.disks,
8320
                     nics=nics,
8321
                     hypervisor=self.op.hypervisor,
8322
                     )
8323

    
8324
    ial.Run(self.op.iallocator)
8325

    
8326
    if not ial.success:
8327
      raise errors.OpPrereqError("Can't compute nodes using"
8328
                                 " iallocator '%s': %s" %
8329
                                 (self.op.iallocator, ial.info),
8330
                                 errors.ECODE_NORES)
8331
    if len(ial.result) != ial.required_nodes:
8332
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8333
                                 " of nodes (%s), required %s" %
8334
                                 (self.op.iallocator, len(ial.result),
8335
                                  ial.required_nodes), errors.ECODE_FAULT)
8336
    self.op.pnode = ial.result[0]
8337
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8338
                 self.op.instance_name, self.op.iallocator,
8339
                 utils.CommaJoin(ial.result))
8340
    if ial.required_nodes == 2:
8341
      self.op.snode = ial.result[1]
8342

    
8343
  def BuildHooksEnv(self):
8344
    """Build hooks env.
8345

8346
    This runs on master, primary and secondary nodes of the instance.
8347

8348
    """
8349
    env = {
8350
      "ADD_MODE": self.op.mode,
8351
      }
8352
    if self.op.mode == constants.INSTANCE_IMPORT:
8353
      env["SRC_NODE"] = self.op.src_node
8354
      env["SRC_PATH"] = self.op.src_path
8355
      env["SRC_IMAGES"] = self.src_images
8356

    
8357
    env.update(_BuildInstanceHookEnv(
8358
      name=self.op.instance_name,
8359
      primary_node=self.op.pnode,
8360
      secondary_nodes=self.secondaries,
8361
      status=self.op.start,
8362
      os_type=self.op.os_type,
8363
      memory=self.be_full[constants.BE_MEMORY],
8364
      vcpus=self.be_full[constants.BE_VCPUS],
8365
      nics=_NICListToTuple(self, self.nics),
8366
      disk_template=self.op.disk_template,
8367
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8368
             for d in self.disks],
8369
      bep=self.be_full,
8370
      hvp=self.hv_full,
8371
      hypervisor_name=self.op.hypervisor,
8372
      tags=self.op.tags,
8373
    ))
8374

    
8375
    return env
8376

    
8377
  def BuildHooksNodes(self):
8378
    """Build hooks nodes.
8379

8380
    """
8381
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8382
    return nl, nl
8383

    
8384
  def _ReadExportInfo(self):
8385
    """Reads the export information from disk.
8386

8387
    It will override the opcode source node and path with the actual
8388
    information, if these two were not specified before.
8389

8390
    @return: the export information
8391

8392
    """
8393
    assert self.op.mode == constants.INSTANCE_IMPORT
8394

    
8395
    src_node = self.op.src_node
8396
    src_path = self.op.src_path
8397

    
8398
    if src_node is None:
8399
      locked_nodes = self.owned_locks(locking.LEVEL_NODE)
8400
      exp_list = self.rpc.call_export_list(locked_nodes)
8401
      found = False
8402
      for node in exp_list:
8403
        if exp_list[node].fail_msg:
8404
          continue
8405
        if src_path in exp_list[node].payload:
8406
          found = True
8407
          self.op.src_node = src_node = node
8408
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8409
                                                       src_path)
8410
          break
8411
      if not found:
8412
        raise errors.OpPrereqError("No export found for relative path %s" %
8413
                                    src_path, errors.ECODE_INVAL)
8414

    
8415
    _CheckNodeOnline(self, src_node)
8416
    result = self.rpc.call_export_info(src_node, src_path)
8417
    result.Raise("No export or invalid export found in dir %s" % src_path)
8418

    
8419
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8420
    if not export_info.has_section(constants.INISECT_EXP):
8421
      raise errors.ProgrammerError("Corrupted export config",
8422
                                   errors.ECODE_ENVIRON)
8423

    
8424
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8425
    if (int(ei_version) != constants.EXPORT_VERSION):
8426
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8427
                                 (ei_version, constants.EXPORT_VERSION),
8428
                                 errors.ECODE_ENVIRON)
8429
    return export_info
8430

    
8431
  def _ReadExportParams(self, einfo):
8432
    """Use export parameters as defaults.
8433

8434
    In case the opcode doesn't specify (as in override) some instance
8435
    parameters, then try to use them from the export information, if
8436
    that declares them.
8437

8438
    """
8439
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8440

    
8441
    if self.op.disk_template is None:
8442
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8443
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8444
                                          "disk_template")
8445
      else:
8446
        raise errors.OpPrereqError("No disk template specified and the export"
8447
                                   " is missing the disk_template information",
8448
                                   errors.ECODE_INVAL)
8449

    
8450
    if not self.op.disks:
8451
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
8452
        disks = []
8453
        # TODO: import the disk iv_name too
8454
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8455
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8456
          disks.append({constants.IDISK_SIZE: disk_sz})
8457
        self.op.disks = disks
8458
      else:
8459
        raise errors.OpPrereqError("No disk info specified and the export"
8460
                                   " is missing the disk information",
8461
                                   errors.ECODE_INVAL)
8462

    
8463
    if (not self.op.nics and
8464
        einfo.has_option(constants.INISECT_INS, "nic_count")):
8465
      nics = []
8466
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8467
        ndict = {}
8468
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8469
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8470
          ndict[name] = v
8471
        nics.append(ndict)
8472
      self.op.nics = nics
8473

    
8474
    if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
8475
      self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
8476

    
8477
    if (self.op.hypervisor is None and
8478
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
8479
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8480

    
8481
    if einfo.has_section(constants.INISECT_HYP):
8482
      # use the export parameters but do not override the ones
8483
      # specified by the user
8484
      for name, value in einfo.items(constants.INISECT_HYP):
8485
        if name not in self.op.hvparams:
8486
          self.op.hvparams[name] = value
8487

    
8488
    if einfo.has_section(constants.INISECT_BEP):
8489
      # use the parameters, without overriding
8490
      for name, value in einfo.items(constants.INISECT_BEP):
8491
        if name not in self.op.beparams:
8492
          self.op.beparams[name] = value
8493
    else:
8494
      # try to read the parameters old style, from the main section
8495
      for name in constants.BES_PARAMETERS:
8496
        if (name not in self.op.beparams and
8497
            einfo.has_option(constants.INISECT_INS, name)):
8498
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8499

    
8500
    if einfo.has_section(constants.INISECT_OSP):
8501
      # use the parameters, without overriding
8502
      for name, value in einfo.items(constants.INISECT_OSP):
8503
        if name not in self.op.osparams:
8504
          self.op.osparams[name] = value
8505

    
8506
  def _RevertToDefaults(self, cluster):
8507
    """Revert the instance parameters to the default values.
8508

8509
    """
8510
    # hvparams
8511
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8512
    for name in self.op.hvparams.keys():
8513
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8514
        del self.op.hvparams[name]
8515
    # beparams
8516
    be_defs = cluster.SimpleFillBE({})
8517
    for name in self.op.beparams.keys():
8518
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8519
        del self.op.beparams[name]
8520
    # nic params
8521
    nic_defs = cluster.SimpleFillNIC({})
8522
    for nic in self.op.nics:
8523
      for name in constants.NICS_PARAMETERS:
8524
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8525
          del nic[name]
8526
    # osparams
8527
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8528
    for name in self.op.osparams.keys():
8529
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8530
        del self.op.osparams[name]
8531

    
8532
  def _CalculateFileStorageDir(self):
8533
    """Calculate final instance file storage dir.
8534

8535
    """
8536
    # file storage dir calculation/check
8537
    self.instance_file_storage_dir = None
8538
    if self.op.disk_template in constants.DTS_FILEBASED:
8539
      # build the full file storage dir path
8540
      joinargs = []
8541

    
8542
      if self.op.disk_template == constants.DT_SHARED_FILE:
8543
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8544
      else:
8545
        get_fsd_fn = self.cfg.GetFileStorageDir
8546

    
8547
      cfg_storagedir = get_fsd_fn()
8548
      if not cfg_storagedir:
8549
        raise errors.OpPrereqError("Cluster file storage dir not defined")
8550
      joinargs.append(cfg_storagedir)
8551

    
8552
      if self.op.file_storage_dir is not None:
8553
        joinargs.append(self.op.file_storage_dir)
8554

    
8555
      joinargs.append(self.op.instance_name)
8556

    
8557
      # pylint: disable=W0142
8558
      self.instance_file_storage_dir = utils.PathJoin(*joinargs)
8559

    
8560
  def CheckPrereq(self):
8561
    """Check prerequisites.
8562

8563
    """
8564
    self._CalculateFileStorageDir()
8565

    
8566
    if self.op.mode == constants.INSTANCE_IMPORT:
8567
      export_info = self._ReadExportInfo()
8568
      self._ReadExportParams(export_info)
8569

    
8570
    if (not self.cfg.GetVGName() and
8571
        self.op.disk_template not in constants.DTS_NOT_LVM):
8572
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8573
                                 " instances", errors.ECODE_STATE)
8574

    
8575
    if self.op.hypervisor is None:
8576
      self.op.hypervisor = self.cfg.GetHypervisorType()
8577

    
8578
    cluster = self.cfg.GetClusterInfo()
8579
    enabled_hvs = cluster.enabled_hypervisors
8580
    if self.op.hypervisor not in enabled_hvs:
8581
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8582
                                 " cluster (%s)" % (self.op.hypervisor,
8583
                                  ",".join(enabled_hvs)),
8584
                                 errors.ECODE_STATE)
8585

    
8586
    # Check tag validity
8587
    for tag in self.op.tags:
8588
      objects.TaggableObject.ValidateTag(tag)
8589

    
8590
    # check hypervisor parameter syntax (locally)
8591
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8592
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8593
                                      self.op.hvparams)
8594
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8595
    hv_type.CheckParameterSyntax(filled_hvp)
8596
    self.hv_full = filled_hvp
8597
    # check that we don't specify global parameters on an instance
8598
    _CheckGlobalHvParams(self.op.hvparams)
8599

    
8600
    # fill and remember the beparams dict
8601
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8602
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8603

    
8604
    # build os parameters
8605
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8606

    
8607
    # now that hvp/bep are in final format, let's reset to defaults,
8608
    # if told to do so
8609
    if self.op.identify_defaults:
8610
      self._RevertToDefaults(cluster)
8611

    
8612
    # NIC buildup
8613
    self.nics = []
8614
    for idx, nic in enumerate(self.op.nics):
8615
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8616
      nic_mode = nic_mode_req
8617
      if nic_mode is None:
8618
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8619

    
8620
      # in routed mode, for the first nic, the default ip is 'auto'
8621
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8622
        default_ip_mode = constants.VALUE_AUTO
8623
      else:
8624
        default_ip_mode = constants.VALUE_NONE
8625

    
8626
      # ip validity checks
8627
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8628
      if ip is None or ip.lower() == constants.VALUE_NONE:
8629
        nic_ip = None
8630
      elif ip.lower() == constants.VALUE_AUTO:
8631
        if not self.op.name_check:
8632
          raise errors.OpPrereqError("IP address set to auto but name checks"
8633
                                     " have been skipped",
8634
                                     errors.ECODE_INVAL)
8635
        nic_ip = self.hostname1.ip
8636
      else:
8637
        if not netutils.IPAddress.IsValid(ip):
8638
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8639
                                     errors.ECODE_INVAL)
8640
        nic_ip = ip
8641

    
8642
      # TODO: check the ip address for uniqueness
8643
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8644
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8645
                                   errors.ECODE_INVAL)
8646

    
8647
      # MAC address verification
8648
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8649
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8650
        mac = utils.NormalizeAndValidateMac(mac)
8651

    
8652
        try:
8653
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8654
        except errors.ReservationError:
8655
          raise errors.OpPrereqError("MAC address %s already in use"
8656
                                     " in cluster" % mac,
8657
                                     errors.ECODE_NOTUNIQUE)
8658

    
8659
      #  Build nic parameters
8660
      link = nic.get(constants.INIC_LINK, None)
8661
      nicparams = {}
8662
      if nic_mode_req:
8663
        nicparams[constants.NIC_MODE] = nic_mode_req
8664
      if link:
8665
        nicparams[constants.NIC_LINK] = link
8666

    
8667
      check_params = cluster.SimpleFillNIC(nicparams)
8668
      objects.NIC.CheckParameterSyntax(check_params)
8669
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8670

    
8671
    # disk checks/pre-build
8672
    default_vg = self.cfg.GetVGName()
8673
    self.disks = []
8674
    for disk in self.op.disks:
8675
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8676
      if mode not in constants.DISK_ACCESS_SET:
8677
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8678
                                   mode, errors.ECODE_INVAL)
8679
      size = disk.get(constants.IDISK_SIZE, None)
8680
      if size is None:
8681
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8682
      try:
8683
        size = int(size)
8684
      except (TypeError, ValueError):
8685
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8686
                                   errors.ECODE_INVAL)
8687

    
8688
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8689
      new_disk = {
8690
        constants.IDISK_SIZE: size,
8691
        constants.IDISK_MODE: mode,
8692
        constants.IDISK_VG: data_vg,
8693
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8694
        }
8695
      if constants.IDISK_ADOPT in disk:
8696
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8697
      self.disks.append(new_disk)
8698

    
8699
    if self.op.mode == constants.INSTANCE_IMPORT:
8700

    
8701
      # Check that the new instance doesn't have less disks than the export
8702
      instance_disks = len(self.disks)
8703
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8704
      if instance_disks < export_disks:
8705
        raise errors.OpPrereqError("Not enough disks to import."
8706
                                   " (instance: %d, export: %d)" %
8707
                                   (instance_disks, export_disks),
8708
                                   errors.ECODE_INVAL)
8709

    
8710
      disk_images = []
8711
      for idx in range(export_disks):
8712
        option = "disk%d_dump" % idx
8713
        if export_info.has_option(constants.INISECT_INS, option):
8714
          # FIXME: are the old os-es, disk sizes, etc. useful?
8715
          export_name = export_info.get(constants.INISECT_INS, option)
8716
          image = utils.PathJoin(self.op.src_path, export_name)
8717
          disk_images.append(image)
8718
        else:
8719
          disk_images.append(False)
8720

    
8721
      self.src_images = disk_images
8722

    
8723
      old_name = export_info.get(constants.INISECT_INS, "name")
8724
      try:
8725
        exp_nic_count = export_info.getint(constants.INISECT_INS, "nic_count")
8726
      except (TypeError, ValueError), err:
8727
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8728
                                   " an integer: %s" % str(err),
8729
                                   errors.ECODE_STATE)
8730
      if self.op.instance_name == old_name:
8731
        for idx, nic in enumerate(self.nics):
8732
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8733
            nic_mac_ini = "nic%d_mac" % idx
8734
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8735

    
8736
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8737

    
8738
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8739
    if self.op.ip_check:
8740
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8741
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8742
                                   (self.check_ip, self.op.instance_name),
8743
                                   errors.ECODE_NOTUNIQUE)
8744

    
8745
    #### mac address generation
8746
    # By generating here the mac address both the allocator and the hooks get
8747
    # the real final mac address rather than the 'auto' or 'generate' value.
8748
    # There is a race condition between the generation and the instance object
8749
    # creation, which means that we know the mac is valid now, but we're not
8750
    # sure it will be when we actually add the instance. If things go bad
8751
    # adding the instance will abort because of a duplicate mac, and the
8752
    # creation job will fail.
8753
    for nic in self.nics:
8754
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8755
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8756

    
8757
    #### allocator run
8758

    
8759
    if self.op.iallocator is not None:
8760
      self._RunAllocator()
8761

    
8762
    #### node related checks
8763

    
8764
    # check primary node
8765
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8766
    assert self.pnode is not None, \
8767
      "Cannot retrieve locked node %s" % self.op.pnode
8768
    if pnode.offline:
8769
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8770
                                 pnode.name, errors.ECODE_STATE)
8771
    if pnode.drained:
8772
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8773
                                 pnode.name, errors.ECODE_STATE)
8774
    if not pnode.vm_capable:
8775
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8776
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8777

    
8778
    self.secondaries = []
8779

    
8780
    # mirror node verification
8781
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8782
      if self.op.snode == pnode.name:
8783
        raise errors.OpPrereqError("The secondary node cannot be the"
8784
                                   " primary node", errors.ECODE_INVAL)
8785
      _CheckNodeOnline(self, self.op.snode)
8786
      _CheckNodeNotDrained(self, self.op.snode)
8787
      _CheckNodeVmCapable(self, self.op.snode)
8788
      self.secondaries.append(self.op.snode)
8789

    
8790
    nodenames = [pnode.name] + self.secondaries
8791

    
8792
    if not self.adopt_disks:
8793
      # Check lv size requirements, if not adopting
8794
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8795
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8796

    
8797
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8798
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8799
                                disk[constants.IDISK_ADOPT])
8800
                     for disk in self.disks])
8801
      if len(all_lvs) != len(self.disks):
8802
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8803
                                   errors.ECODE_INVAL)
8804
      for lv_name in all_lvs:
8805
        try:
8806
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8807
          # to ReserveLV uses the same syntax
8808
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8809
        except errors.ReservationError:
8810
          raise errors.OpPrereqError("LV named %s used by another instance" %
8811
                                     lv_name, errors.ECODE_NOTUNIQUE)
8812

    
8813
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8814
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8815

    
8816
      node_lvs = self.rpc.call_lv_list([pnode.name],
8817
                                       vg_names.payload.keys())[pnode.name]
8818
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8819
      node_lvs = node_lvs.payload
8820

    
8821
      delta = all_lvs.difference(node_lvs.keys())
8822
      if delta:
8823
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8824
                                   utils.CommaJoin(delta),
8825
                                   errors.ECODE_INVAL)
8826
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8827
      if online_lvs:
8828
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8829
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8830
                                   errors.ECODE_STATE)
8831
      # update the size of disk based on what is found
8832
      for dsk in self.disks:
8833
        dsk[constants.IDISK_SIZE] = \
8834
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8835
                                        dsk[constants.IDISK_ADOPT])][0]))
8836

    
8837
    elif self.op.disk_template == constants.DT_BLOCK:
8838
      # Normalize and de-duplicate device paths
8839
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8840
                       for disk in self.disks])
8841
      if len(all_disks) != len(self.disks):
8842
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8843
                                   errors.ECODE_INVAL)
8844
      baddisks = [d for d in all_disks
8845
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8846
      if baddisks:
8847
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8848
                                   " cannot be adopted" %
8849
                                   (", ".join(baddisks),
8850
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8851
                                   errors.ECODE_INVAL)
8852

    
8853
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8854
                                            list(all_disks))[pnode.name]
8855
      node_disks.Raise("Cannot get block device information from node %s" %
8856
                       pnode.name)
8857
      node_disks = node_disks.payload
8858
      delta = all_disks.difference(node_disks.keys())
8859
      if delta:
8860
        raise errors.OpPrereqError("Missing block device(s): %s" %
8861
                                   utils.CommaJoin(delta),
8862
                                   errors.ECODE_INVAL)
8863
      for dsk in self.disks:
8864
        dsk[constants.IDISK_SIZE] = \
8865
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8866

    
8867
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8868

    
8869
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8870
    # check OS parameters (remotely)
8871
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8872

    
8873
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8874

    
8875
    # memory check on primary node
8876
    if self.op.start:
8877
      _CheckNodeFreeMemory(self, self.pnode.name,
8878
                           "creating instance %s" % self.op.instance_name,
8879
                           self.be_full[constants.BE_MEMORY],
8880
                           self.op.hypervisor)
8881

    
8882
    self.dry_run_result = list(nodenames)
8883

    
8884
  def Exec(self, feedback_fn):
8885
    """Create and add the instance to the cluster.
8886

8887
    """
8888
    instance = self.op.instance_name
8889
    pnode_name = self.pnode.name
8890

    
8891
    ht_kind = self.op.hypervisor
8892
    if ht_kind in constants.HTS_REQ_PORT:
8893
      network_port = self.cfg.AllocatePort()
8894
    else:
8895
      network_port = None
8896

    
8897
    disks = _GenerateDiskTemplate(self,
8898
                                  self.op.disk_template,
8899
                                  instance, pnode_name,
8900
                                  self.secondaries,
8901
                                  self.disks,
8902
                                  self.instance_file_storage_dir,
8903
                                  self.op.file_driver,
8904
                                  0,
8905
                                  feedback_fn)
8906

    
8907
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8908
                            primary_node=pnode_name,
8909
                            nics=self.nics, disks=disks,
8910
                            disk_template=self.op.disk_template,
8911
                            admin_up=False,
8912
                            network_port=network_port,
8913
                            beparams=self.op.beparams,
8914
                            hvparams=self.op.hvparams,
8915
                            hypervisor=self.op.hypervisor,
8916
                            osparams=self.op.osparams,
8917
                            )
8918

    
8919
    if self.op.tags:
8920
      for tag in self.op.tags:
8921
        iobj.AddTag(tag)
8922

    
8923
    if self.adopt_disks:
8924
      if self.op.disk_template == constants.DT_PLAIN:
8925
        # rename LVs to the newly-generated names; we need to construct
8926
        # 'fake' LV disks with the old data, plus the new unique_id
8927
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8928
        rename_to = []
8929
        for t_dsk, a_dsk in zip(tmp_disks, self.disks):
8930
          rename_to.append(t_dsk.logical_id)
8931
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8932
          self.cfg.SetDiskID(t_dsk, pnode_name)
8933
        result = self.rpc.call_blockdev_rename(pnode_name,
8934
                                               zip(tmp_disks, rename_to))
8935
        result.Raise("Failed to rename adoped LVs")
8936
    else:
8937
      feedback_fn("* creating instance disks...")
8938
      try:
8939
        _CreateDisks(self, iobj)
8940
      except errors.OpExecError:
8941
        self.LogWarning("Device creation failed, reverting...")
8942
        try:
8943
          _RemoveDisks(self, iobj)
8944
        finally:
8945
          self.cfg.ReleaseDRBDMinors(instance)
8946
          raise
8947

    
8948
    feedback_fn("adding instance %s to cluster config" % instance)
8949

    
8950
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8951

    
8952
    # Declare that we don't want to remove the instance lock anymore, as we've
8953
    # added the instance to the config
8954
    del self.remove_locks[locking.LEVEL_INSTANCE]
8955

    
8956
    if self.op.mode == constants.INSTANCE_IMPORT:
8957
      # Release unused nodes
8958
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8959
    else:
8960
      # Release all nodes
8961
      _ReleaseLocks(self, locking.LEVEL_NODE)
8962

    
8963
    disk_abort = False
8964
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8965
      feedback_fn("* wiping instance disks...")
8966
      try:
8967
        _WipeDisks(self, iobj)
8968
      except errors.OpExecError, err:
8969
        logging.exception("Wiping disks failed")
8970
        self.LogWarning("Wiping instance disks failed (%s)", err)
8971
        disk_abort = True
8972

    
8973
    if disk_abort:
8974
      # Something is already wrong with the disks, don't do anything else
8975
      pass
8976
    elif self.op.wait_for_sync:
8977
      disk_abort = not _WaitForSync(self, iobj)
8978
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8979
      # make sure the disks are not degraded (still sync-ing is ok)
8980
      feedback_fn("* checking mirrors status")
8981
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8982
    else:
8983
      disk_abort = False
8984

    
8985
    if disk_abort:
8986
      _RemoveDisks(self, iobj)
8987
      self.cfg.RemoveInstance(iobj.name)
8988
      # Make sure the instance lock gets removed
8989
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8990
      raise errors.OpExecError("There are some degraded disks for"
8991
                               " this instance")
8992

    
8993
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8994
      if self.op.mode == constants.INSTANCE_CREATE:
8995
        if not self.op.no_install:
8996
          pause_sync = (iobj.disk_template in constants.DTS_INT_MIRROR and
8997
                        not self.op.wait_for_sync)
8998
          if pause_sync:
8999
            feedback_fn("* pausing disk sync to install instance OS")
9000
            result = self.rpc.call_blockdev_pause_resume_sync(pnode_name,
9001
                                                              iobj.disks, True)
9002
            for idx, success in enumerate(result.payload):
9003
              if not success:
9004
                logging.warn("pause-sync of instance %s for disk %d failed",
9005
                             instance, idx)
9006

    
9007
          feedback_fn("* running the instance OS create scripts...")
9008
          # FIXME: pass debug option from opcode to backend
9009
          os_add_result = \
9010
            self.rpc.call_instance_os_add(pnode_name, iobj, False,
9011
                                          self.op.debug_level)
9012
          if pause_sync:
9013
            feedback_fn("* resuming disk sync")
9014
            result = self.rpc.call_blockdev_pause_resume_sync(pnode_name,
9015
                                                              iobj.disks, False)
9016
            for idx, success in enumerate(result.payload):
9017
              if not success:
9018
                logging.warn("resume-sync of instance %s for disk %d failed",
9019
                             instance, idx)
9020

    
9021
          os_add_result.Raise("Could not add os for instance %s"
9022
                              " on node %s" % (instance, pnode_name))
9023

    
9024
      elif self.op.mode == constants.INSTANCE_IMPORT:
9025
        feedback_fn("* running the instance OS import scripts...")
9026

    
9027
        transfers = []
9028

    
9029
        for idx, image in enumerate(self.src_images):
9030
          if not image:
9031
            continue
9032

    
9033
          # FIXME: pass debug option from opcode to backend
9034
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
9035
                                             constants.IEIO_FILE, (image, ),
9036
                                             constants.IEIO_SCRIPT,
9037
                                             (iobj.disks[idx], idx),
9038
                                             None)
9039
          transfers.append(dt)
9040

    
9041
        import_result = \
9042
          masterd.instance.TransferInstanceData(self, feedback_fn,
9043
                                                self.op.src_node, pnode_name,
9044
                                                self.pnode.secondary_ip,
9045
                                                iobj, transfers)
9046
        if not compat.all(import_result):
9047
          self.LogWarning("Some disks for instance %s on node %s were not"
9048
                          " imported successfully" % (instance, pnode_name))
9049

    
9050
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
9051
        feedback_fn("* preparing remote import...")
9052
        # The source cluster will stop the instance before attempting to make a
9053
        # connection. In some cases stopping an instance can take a long time,
9054
        # hence the shutdown timeout is added to the connection timeout.
9055
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
9056
                           self.op.source_shutdown_timeout)
9057
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9058

    
9059
        assert iobj.primary_node == self.pnode.name
9060
        disk_results = \
9061
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
9062
                                        self.source_x509_ca,
9063
                                        self._cds, timeouts)
9064
        if not compat.all(disk_results):
9065
          # TODO: Should the instance still be started, even if some disks
9066
          # failed to import (valid for local imports, too)?
9067
          self.LogWarning("Some disks for instance %s on node %s were not"
9068
                          " imported successfully" % (instance, pnode_name))
9069

    
9070
        # Run rename script on newly imported instance
9071
        assert iobj.name == instance
9072
        feedback_fn("Running rename script for %s" % instance)
9073
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
9074
                                                   self.source_instance_name,
9075
                                                   self.op.debug_level)
9076
        if result.fail_msg:
9077
          self.LogWarning("Failed to run rename script for %s on node"
9078
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
9079

    
9080
      else:
9081
        # also checked in the prereq part
9082
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
9083
                                     % self.op.mode)
9084

    
9085
    if self.op.start:
9086
      iobj.admin_up = True
9087
      self.cfg.Update(iobj, feedback_fn)
9088
      logging.info("Starting instance %s on node %s", instance, pnode_name)
9089
      feedback_fn("* starting instance...")
9090
      result = self.rpc.call_instance_start(pnode_name, iobj,
9091
                                            None, None, False)
9092
      result.Raise("Could not start instance")
9093

    
9094
    return list(iobj.all_nodes)
9095

    
9096

    
9097
class LUInstanceConsole(NoHooksLU):
9098
  """Connect to an instance's console.
9099

9100
  This is somewhat special in that it returns the command line that
9101
  you need to run on the master node in order to connect to the
9102
  console.
9103

9104
  """
9105
  REQ_BGL = False
9106

    
9107
  def ExpandNames(self):
9108
    self._ExpandAndLockInstance()
9109

    
9110
  def CheckPrereq(self):
9111
    """Check prerequisites.
9112

9113
    This checks that the instance is in the cluster.
9114

9115
    """
9116
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9117
    assert self.instance is not None, \
9118
      "Cannot retrieve locked instance %s" % self.op.instance_name
9119
    _CheckNodeOnline(self, self.instance.primary_node)
9120

    
9121
  def Exec(self, feedback_fn):
9122
    """Connect to the console of an instance
9123

9124
    """
9125
    instance = self.instance
9126
    node = instance.primary_node
9127

    
9128
    node_insts = self.rpc.call_instance_list([node],
9129
                                             [instance.hypervisor])[node]
9130
    node_insts.Raise("Can't get node information from %s" % node)
9131

    
9132
    if instance.name not in node_insts.payload:
9133
      if instance.admin_up:
9134
        state = constants.INSTST_ERRORDOWN
9135
      else:
9136
        state = constants.INSTST_ADMINDOWN
9137
      raise errors.OpExecError("Instance %s is not running (state %s)" %
9138
                               (instance.name, state))
9139

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

    
9142
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
9143

    
9144

    
9145
def _GetInstanceConsole(cluster, instance):
9146
  """Returns console information for an instance.
9147

9148
  @type cluster: L{objects.Cluster}
9149
  @type instance: L{objects.Instance}
9150
  @rtype: dict
9151

9152
  """
9153
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
9154
  # beparams and hvparams are passed separately, to avoid editing the
9155
  # instance and then saving the defaults in the instance itself.
9156
  hvparams = cluster.FillHV(instance)
9157
  beparams = cluster.FillBE(instance)
9158
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
9159

    
9160
  assert console.instance == instance.name
9161
  assert console.Validate()
9162

    
9163
  return console.ToDict()
9164

    
9165

    
9166
class LUInstanceReplaceDisks(LogicalUnit):
9167
  """Replace the disks of an instance.
9168

9169
  """
9170
  HPATH = "mirrors-replace"
9171
  HTYPE = constants.HTYPE_INSTANCE
9172
  REQ_BGL = False
9173

    
9174
  def CheckArguments(self):
9175
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
9176
                                  self.op.iallocator)
9177

    
9178
  def ExpandNames(self):
9179
    self._ExpandAndLockInstance()
9180

    
9181
    assert locking.LEVEL_NODE not in self.needed_locks
9182
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
9183

    
9184
    assert self.op.iallocator is None or self.op.remote_node is None, \
9185
      "Conflicting options"
9186

    
9187
    if self.op.remote_node is not None:
9188
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9189

    
9190
      # Warning: do not remove the locking of the new secondary here
9191
      # unless DRBD8.AddChildren is changed to work in parallel;
9192
      # currently it doesn't since parallel invocations of
9193
      # FindUnusedMinor will conflict
9194
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
9195
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
9196
    else:
9197
      self.needed_locks[locking.LEVEL_NODE] = []
9198
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9199

    
9200
      if self.op.iallocator is not None:
9201
        # iallocator will select a new node in the same group
9202
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
9203

    
9204
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
9205
                                   self.op.iallocator, self.op.remote_node,
9206
                                   self.op.disks, False, self.op.early_release)
9207

    
9208
    self.tasklets = [self.replacer]
9209

    
9210
  def DeclareLocks(self, level):
9211
    if level == locking.LEVEL_NODEGROUP:
9212
      assert self.op.remote_node is None
9213
      assert self.op.iallocator is not None
9214
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
9215

    
9216
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
9217
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
9218
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
9219

    
9220
    elif level == locking.LEVEL_NODE:
9221
      if self.op.iallocator is not None:
9222
        assert self.op.remote_node is None
9223
        assert not self.needed_locks[locking.LEVEL_NODE]
9224

    
9225
        # Lock member nodes of all locked groups
9226
        self.needed_locks[locking.LEVEL_NODE] = [node_name
9227
          for group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
9228
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
9229
      else:
9230
        self._LockInstancesNodes()
9231

    
9232
  def BuildHooksEnv(self):
9233
    """Build hooks env.
9234

9235
    This runs on the master, the primary and all the secondaries.
9236

9237
    """
9238
    instance = self.replacer.instance
9239
    env = {
9240
      "MODE": self.op.mode,
9241
      "NEW_SECONDARY": self.op.remote_node,
9242
      "OLD_SECONDARY": instance.secondary_nodes[0],
9243
      }
9244
    env.update(_BuildInstanceHookEnvByObject(self, instance))
9245
    return env
9246

    
9247
  def BuildHooksNodes(self):
9248
    """Build hooks nodes.
9249

9250
    """
9251
    instance = self.replacer.instance
9252
    nl = [
9253
      self.cfg.GetMasterNode(),
9254
      instance.primary_node,
9255
      ]
9256
    if self.op.remote_node is not None:
9257
      nl.append(self.op.remote_node)
9258
    return nl, nl
9259

    
9260
  def CheckPrereq(self):
9261
    """Check prerequisites.
9262

9263
    """
9264
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
9265
            self.op.iallocator is None)
9266

    
9267
    owned_groups = self.owned_locks(locking.LEVEL_NODEGROUP)
9268
    if owned_groups:
9269
      _CheckInstanceNodeGroups(self.cfg, self.op.instance_name, owned_groups)
9270

    
9271
    return LogicalUnit.CheckPrereq(self)
9272

    
9273

    
9274
class TLReplaceDisks(Tasklet):
9275
  """Replaces disks for an instance.
9276

9277
  Note: Locking is not within the scope of this class.
9278

9279
  """
9280
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
9281
               disks, delay_iallocator, early_release):
9282
    """Initializes this class.
9283

9284
    """
9285
    Tasklet.__init__(self, lu)
9286

    
9287
    # Parameters
9288
    self.instance_name = instance_name
9289
    self.mode = mode
9290
    self.iallocator_name = iallocator_name
9291
    self.remote_node = remote_node
9292
    self.disks = disks
9293
    self.delay_iallocator = delay_iallocator
9294
    self.early_release = early_release
9295

    
9296
    # Runtime data
9297
    self.instance = None
9298
    self.new_node = None
9299
    self.target_node = None
9300
    self.other_node = None
9301
    self.remote_node_info = None
9302
    self.node_secondary_ip = None
9303

    
9304
  @staticmethod
9305
  def CheckArguments(mode, remote_node, iallocator):
9306
    """Helper function for users of this class.
9307

9308
    """
9309
    # check for valid parameter combination
9310
    if mode == constants.REPLACE_DISK_CHG:
9311
      if remote_node is None and iallocator is None:
9312
        raise errors.OpPrereqError("When changing the secondary either an"
9313
                                   " iallocator script must be used or the"
9314
                                   " new node given", errors.ECODE_INVAL)
9315

    
9316
      if remote_node is not None and iallocator is not None:
9317
        raise errors.OpPrereqError("Give either the iallocator or the new"
9318
                                   " secondary, not both", errors.ECODE_INVAL)
9319

    
9320
    elif remote_node is not None or iallocator is not None:
9321
      # Not replacing the secondary
9322
      raise errors.OpPrereqError("The iallocator and new node options can"
9323
                                 " only be used when changing the"
9324
                                 " secondary node", errors.ECODE_INVAL)
9325

    
9326
  @staticmethod
9327
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
9328
    """Compute a new secondary node using an IAllocator.
9329

9330
    """
9331
    ial = IAllocator(lu.cfg, lu.rpc,
9332
                     mode=constants.IALLOCATOR_MODE_RELOC,
9333
                     name=instance_name,
9334
                     relocate_from=list(relocate_from))
9335

    
9336
    ial.Run(iallocator_name)
9337

    
9338
    if not ial.success:
9339
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
9340
                                 " %s" % (iallocator_name, ial.info),
9341
                                 errors.ECODE_NORES)
9342

    
9343
    if len(ial.result) != ial.required_nodes:
9344
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9345
                                 " of nodes (%s), required %s" %
9346
                                 (iallocator_name,
9347
                                  len(ial.result), ial.required_nodes),
9348
                                 errors.ECODE_FAULT)
9349

    
9350
    remote_node_name = ial.result[0]
9351

    
9352
    lu.LogInfo("Selected new secondary for instance '%s': %s",
9353
               instance_name, remote_node_name)
9354

    
9355
    return remote_node_name
9356

    
9357
  def _FindFaultyDisks(self, node_name):
9358
    """Wrapper for L{_FindFaultyInstanceDisks}.
9359

9360
    """
9361
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9362
                                    node_name, True)
9363

    
9364
  def _CheckDisksActivated(self, instance):
9365
    """Checks if the instance disks are activated.
9366

9367
    @param instance: The instance to check disks
9368
    @return: True if they are activated, False otherwise
9369

9370
    """
9371
    nodes = instance.all_nodes
9372

    
9373
    for idx, dev in enumerate(instance.disks):
9374
      for node in nodes:
9375
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9376
        self.cfg.SetDiskID(dev, node)
9377

    
9378
        result = self.rpc.call_blockdev_find(node, dev)
9379

    
9380
        if result.offline:
9381
          continue
9382
        elif result.fail_msg or not result.payload:
9383
          return False
9384

    
9385
    return True
9386

    
9387
  def CheckPrereq(self):
9388
    """Check prerequisites.
9389

9390
    This checks that the instance is in the cluster.
9391

9392
    """
9393
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9394
    assert instance is not None, \
9395
      "Cannot retrieve locked instance %s" % self.instance_name
9396

    
9397
    if instance.disk_template != constants.DT_DRBD8:
9398
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9399
                                 " instances", errors.ECODE_INVAL)
9400

    
9401
    if len(instance.secondary_nodes) != 1:
9402
      raise errors.OpPrereqError("The instance has a strange layout,"
9403
                                 " expected one secondary but found %d" %
9404
                                 len(instance.secondary_nodes),
9405
                                 errors.ECODE_FAULT)
9406

    
9407
    if not self.delay_iallocator:
9408
      self._CheckPrereq2()
9409

    
9410
  def _CheckPrereq2(self):
9411
    """Check prerequisites, second part.
9412

9413
    This function should always be part of CheckPrereq. It was separated and is
9414
    now called from Exec because during node evacuation iallocator was only
9415
    called with an unmodified cluster model, not taking planned changes into
9416
    account.
9417

9418
    """
9419
    instance = self.instance
9420
    secondary_node = instance.secondary_nodes[0]
9421

    
9422
    if self.iallocator_name is None:
9423
      remote_node = self.remote_node
9424
    else:
9425
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
9426
                                       instance.name, instance.secondary_nodes)
9427

    
9428
    if remote_node is None:
9429
      self.remote_node_info = None
9430
    else:
9431
      assert remote_node in self.lu.owned_locks(locking.LEVEL_NODE), \
9432
             "Remote node '%s' is not locked" % remote_node
9433

    
9434
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9435
      assert self.remote_node_info is not None, \
9436
        "Cannot retrieve locked node %s" % remote_node
9437

    
9438
    if remote_node == self.instance.primary_node:
9439
      raise errors.OpPrereqError("The specified node is the primary node of"
9440
                                 " the instance", errors.ECODE_INVAL)
9441

    
9442
    if remote_node == secondary_node:
9443
      raise errors.OpPrereqError("The specified node is already the"
9444
                                 " secondary node of the instance",
9445
                                 errors.ECODE_INVAL)
9446

    
9447
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9448
                                    constants.REPLACE_DISK_CHG):
9449
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
9450
                                 errors.ECODE_INVAL)
9451

    
9452
    if self.mode == constants.REPLACE_DISK_AUTO:
9453
      if not self._CheckDisksActivated(instance):
9454
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
9455
                                   " first" % self.instance_name,
9456
                                   errors.ECODE_STATE)
9457
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
9458
      faulty_secondary = self._FindFaultyDisks(secondary_node)
9459

    
9460
      if faulty_primary and faulty_secondary:
9461
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9462
                                   " one node and can not be repaired"
9463
                                   " automatically" % self.instance_name,
9464
                                   errors.ECODE_STATE)
9465

    
9466
      if faulty_primary:
9467
        self.disks = faulty_primary
9468
        self.target_node = instance.primary_node
9469
        self.other_node = secondary_node
9470
        check_nodes = [self.target_node, self.other_node]
9471
      elif faulty_secondary:
9472
        self.disks = faulty_secondary
9473
        self.target_node = secondary_node
9474
        self.other_node = instance.primary_node
9475
        check_nodes = [self.target_node, self.other_node]
9476
      else:
9477
        self.disks = []
9478
        check_nodes = []
9479

    
9480
    else:
9481
      # Non-automatic modes
9482
      if self.mode == constants.REPLACE_DISK_PRI:
9483
        self.target_node = instance.primary_node
9484
        self.other_node = secondary_node
9485
        check_nodes = [self.target_node, self.other_node]
9486

    
9487
      elif self.mode == constants.REPLACE_DISK_SEC:
9488
        self.target_node = secondary_node
9489
        self.other_node = instance.primary_node
9490
        check_nodes = [self.target_node, self.other_node]
9491

    
9492
      elif self.mode == constants.REPLACE_DISK_CHG:
9493
        self.new_node = remote_node
9494
        self.other_node = instance.primary_node
9495
        self.target_node = secondary_node
9496
        check_nodes = [self.new_node, self.other_node]
9497

    
9498
        _CheckNodeNotDrained(self.lu, remote_node)
9499
        _CheckNodeVmCapable(self.lu, remote_node)
9500

    
9501
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
9502
        assert old_node_info is not None
9503
        if old_node_info.offline and not self.early_release:
9504
          # doesn't make sense to delay the release
9505
          self.early_release = True
9506
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9507
                          " early-release mode", secondary_node)
9508

    
9509
      else:
9510
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9511
                                     self.mode)
9512

    
9513
      # If not specified all disks should be replaced
9514
      if not self.disks:
9515
        self.disks = range(len(self.instance.disks))
9516

    
9517
    for node in check_nodes:
9518
      _CheckNodeOnline(self.lu, node)
9519

    
9520
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
9521
                                                          self.other_node,
9522
                                                          self.target_node]
9523
                              if node_name is not None)
9524

    
9525
    # Release unneeded node locks
9526
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9527

    
9528
    # Release any owned node group
9529
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9530
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9531

    
9532
    # Check whether disks are valid
9533
    for disk_idx in self.disks:
9534
      instance.FindDisk(disk_idx)
9535

    
9536
    # Get secondary node IP addresses
9537
    self.node_secondary_ip = dict((name, node.secondary_ip) for (name, node)
9538
                                  in self.cfg.GetMultiNodeInfo(touched_nodes))
9539

    
9540
  def Exec(self, feedback_fn):
9541
    """Execute disk replacement.
9542

9543
    This dispatches the disk replacement to the appropriate handler.
9544

9545
    """
9546
    if self.delay_iallocator:
9547
      self._CheckPrereq2()
9548

    
9549
    if __debug__:
9550
      # Verify owned locks before starting operation
9551
      owned_nodes = self.lu.owned_locks(locking.LEVEL_NODE)
9552
      assert set(owned_nodes) == set(self.node_secondary_ip), \
9553
          ("Incorrect node locks, owning %s, expected %s" %
9554
           (owned_nodes, self.node_secondary_ip.keys()))
9555

    
9556
      owned_instances = self.lu.owned_locks(locking.LEVEL_INSTANCE)
9557
      assert list(owned_instances) == [self.instance_name], \
9558
          "Instance '%s' not locked" % self.instance_name
9559

    
9560
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9561
          "Should not own any node group lock at this point"
9562

    
9563
    if not self.disks:
9564
      feedback_fn("No disks need replacement")
9565
      return
9566

    
9567
    feedback_fn("Replacing disk(s) %s for %s" %
9568
                (utils.CommaJoin(self.disks), self.instance.name))
9569

    
9570
    activate_disks = (not self.instance.admin_up)
9571

    
9572
    # Activate the instance disks if we're replacing them on a down instance
9573
    if activate_disks:
9574
      _StartInstanceDisks(self.lu, self.instance, True)
9575

    
9576
    try:
9577
      # Should we replace the secondary node?
9578
      if self.new_node is not None:
9579
        fn = self._ExecDrbd8Secondary
9580
      else:
9581
        fn = self._ExecDrbd8DiskOnly
9582

    
9583
      result = fn(feedback_fn)
9584
    finally:
9585
      # Deactivate the instance disks if we're replacing them on a
9586
      # down instance
9587
      if activate_disks:
9588
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9589

    
9590
    if __debug__:
9591
      # Verify owned locks
9592
      owned_nodes = self.lu.owned_locks(locking.LEVEL_NODE)
9593
      nodes = frozenset(self.node_secondary_ip)
9594
      assert ((self.early_release and not owned_nodes) or
9595
              (not self.early_release and not (set(owned_nodes) - nodes))), \
9596
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9597
         " nodes=%r" % (self.early_release, owned_nodes, nodes))
9598

    
9599
    return result
9600

    
9601
  def _CheckVolumeGroup(self, nodes):
9602
    self.lu.LogInfo("Checking volume groups")
9603

    
9604
    vgname = self.cfg.GetVGName()
9605

    
9606
    # Make sure volume group exists on all involved nodes
9607
    results = self.rpc.call_vg_list(nodes)
9608
    if not results:
9609
      raise errors.OpExecError("Can't list volume groups on the nodes")
9610

    
9611
    for node in nodes:
9612
      res = results[node]
9613
      res.Raise("Error checking node %s" % node)
9614
      if vgname not in res.payload:
9615
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9616
                                 (vgname, node))
9617

    
9618
  def _CheckDisksExistence(self, nodes):
9619
    # Check disk existence
9620
    for idx, dev in enumerate(self.instance.disks):
9621
      if idx not in self.disks:
9622
        continue
9623

    
9624
      for node in nodes:
9625
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9626
        self.cfg.SetDiskID(dev, node)
9627

    
9628
        result = self.rpc.call_blockdev_find(node, dev)
9629

    
9630
        msg = result.fail_msg
9631
        if msg or not result.payload:
9632
          if not msg:
9633
            msg = "disk not found"
9634
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9635
                                   (idx, node, msg))
9636

    
9637
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9638
    for idx, dev in enumerate(self.instance.disks):
9639
      if idx not in self.disks:
9640
        continue
9641

    
9642
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9643
                      (idx, node_name))
9644

    
9645
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9646
                                   ldisk=ldisk):
9647
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9648
                                 " replace disks for instance %s" %
9649
                                 (node_name, self.instance.name))
9650

    
9651
  def _CreateNewStorage(self, node_name):
9652
    """Create new storage on the primary or secondary node.
9653

9654
    This is only used for same-node replaces, not for changing the
9655
    secondary node, hence we don't want to modify the existing disk.
9656

9657
    """
9658
    iv_names = {}
9659

    
9660
    for idx, dev in enumerate(self.instance.disks):
9661
      if idx not in self.disks:
9662
        continue
9663

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

    
9666
      self.cfg.SetDiskID(dev, node_name)
9667

    
9668
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9669
      names = _GenerateUniqueNames(self.lu, lv_names)
9670

    
9671
      vg_data = dev.children[0].logical_id[0]
9672
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9673
                             logical_id=(vg_data, names[0]))
9674
      vg_meta = dev.children[1].logical_id[0]
9675
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9676
                             logical_id=(vg_meta, names[1]))
9677

    
9678
      new_lvs = [lv_data, lv_meta]
9679
      old_lvs = [child.Copy() for child in dev.children]
9680
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9681

    
9682
      # we pass force_create=True to force the LVM creation
9683
      for new_lv in new_lvs:
9684
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9685
                        _GetInstanceInfoText(self.instance), False)
9686

    
9687
    return iv_names
9688

    
9689
  def _CheckDevices(self, node_name, iv_names):
9690
    for name, (dev, _, _) in iv_names.iteritems():
9691
      self.cfg.SetDiskID(dev, node_name)
9692

    
9693
      result = self.rpc.call_blockdev_find(node_name, dev)
9694

    
9695
      msg = result.fail_msg
9696
      if msg or not result.payload:
9697
        if not msg:
9698
          msg = "disk not found"
9699
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9700
                                 (name, msg))
9701

    
9702
      if result.payload.is_degraded:
9703
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9704

    
9705
  def _RemoveOldStorage(self, node_name, iv_names):
9706
    for name, (_, old_lvs, _) in iv_names.iteritems():
9707
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9708

    
9709
      for lv in old_lvs:
9710
        self.cfg.SetDiskID(lv, node_name)
9711

    
9712
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9713
        if msg:
9714
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9715
                             hint="remove unused LVs manually")
9716

    
9717
  def _ExecDrbd8DiskOnly(self, feedback_fn): # pylint: disable=W0613
9718
    """Replace a disk on the primary or secondary for DRBD 8.
9719

9720
    The algorithm for replace is quite complicated:
9721

9722
      1. for each disk to be replaced:
9723

9724
        1. create new LVs on the target node with unique names
9725
        1. detach old LVs from the drbd device
9726
        1. rename old LVs to name_replaced.<time_t>
9727
        1. rename new LVs to old LVs
9728
        1. attach the new LVs (with the old names now) to the drbd device
9729

9730
      1. wait for sync across all devices
9731

9732
      1. for each modified disk:
9733

9734
        1. remove old LVs (which have the name name_replaces.<time_t>)
9735

9736
    Failures are not very well handled.
9737

9738
    """
9739
    steps_total = 6
9740

    
9741
    # Step: check device activation
9742
    self.lu.LogStep(1, steps_total, "Check device existence")
9743
    self._CheckDisksExistence([self.other_node, self.target_node])
9744
    self._CheckVolumeGroup([self.target_node, self.other_node])
9745

    
9746
    # Step: check other node consistency
9747
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9748
    self._CheckDisksConsistency(self.other_node,
9749
                                self.other_node == self.instance.primary_node,
9750
                                False)
9751

    
9752
    # Step: create new storage
9753
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9754
    iv_names = self._CreateNewStorage(self.target_node)
9755

    
9756
    # Step: for each lv, detach+rename*2+attach
9757
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9758
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9759
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9760

    
9761
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9762
                                                     old_lvs)
9763
      result.Raise("Can't detach drbd from local storage on node"
9764
                   " %s for device %s" % (self.target_node, dev.iv_name))
9765
      #dev.children = []
9766
      #cfg.Update(instance)
9767

    
9768
      # ok, we created the new LVs, so now we know we have the needed
9769
      # storage; as such, we proceed on the target node to rename
9770
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9771
      # using the assumption that logical_id == physical_id (which in
9772
      # turn is the unique_id on that node)
9773

    
9774
      # FIXME(iustin): use a better name for the replaced LVs
9775
      temp_suffix = int(time.time())
9776
      ren_fn = lambda d, suff: (d.physical_id[0],
9777
                                d.physical_id[1] + "_replaced-%s" % suff)
9778

    
9779
      # Build the rename list based on what LVs exist on the node
9780
      rename_old_to_new = []
9781
      for to_ren in old_lvs:
9782
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9783
        if not result.fail_msg and result.payload:
9784
          # device exists
9785
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9786

    
9787
      self.lu.LogInfo("Renaming the old LVs on the target node")
9788
      result = self.rpc.call_blockdev_rename(self.target_node,
9789
                                             rename_old_to_new)
9790
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9791

    
9792
      # Now we rename the new LVs to the old LVs
9793
      self.lu.LogInfo("Renaming the new LVs on the target node")
9794
      rename_new_to_old = [(new, old.physical_id)
9795
                           for old, new in zip(old_lvs, new_lvs)]
9796
      result = self.rpc.call_blockdev_rename(self.target_node,
9797
                                             rename_new_to_old)
9798
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9799

    
9800
      # Intermediate steps of in memory modifications
9801
      for old, new in zip(old_lvs, new_lvs):
9802
        new.logical_id = old.logical_id
9803
        self.cfg.SetDiskID(new, self.target_node)
9804

    
9805
      # We need to modify old_lvs so that removal later removes the
9806
      # right LVs, not the newly added ones; note that old_lvs is a
9807
      # copy here
9808
      for disk in old_lvs:
9809
        disk.logical_id = ren_fn(disk, temp_suffix)
9810
        self.cfg.SetDiskID(disk, self.target_node)
9811

    
9812
      # Now that the new lvs have the old name, we can add them to the device
9813
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9814
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9815
                                                  new_lvs)
9816
      msg = result.fail_msg
9817
      if msg:
9818
        for new_lv in new_lvs:
9819
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9820
                                               new_lv).fail_msg
9821
          if msg2:
9822
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9823
                               hint=("cleanup manually the unused logical"
9824
                                     "volumes"))
9825
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9826

    
9827
    cstep = 5
9828
    if self.early_release:
9829
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9830
      cstep += 1
9831
      self._RemoveOldStorage(self.target_node, iv_names)
9832
      # WARNING: we release both node locks here, do not do other RPCs
9833
      # than WaitForSync to the primary node
9834
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9835
                    names=[self.target_node, self.other_node])
9836

    
9837
    # Wait for sync
9838
    # This can fail as the old devices are degraded and _WaitForSync
9839
    # does a combined result over all disks, so we don't check its return value
9840
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9841
    cstep += 1
9842
    _WaitForSync(self.lu, self.instance)
9843

    
9844
    # Check all devices manually
9845
    self._CheckDevices(self.instance.primary_node, iv_names)
9846

    
9847
    # Step: remove old storage
9848
    if not self.early_release:
9849
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9850
      cstep += 1
9851
      self._RemoveOldStorage(self.target_node, iv_names)
9852

    
9853
  def _ExecDrbd8Secondary(self, feedback_fn):
9854
    """Replace the secondary node for DRBD 8.
9855

9856
    The algorithm for replace is quite complicated:
9857
      - for all disks of the instance:
9858
        - create new LVs on the new node with same names
9859
        - shutdown the drbd device on the old secondary
9860
        - disconnect the drbd network on the primary
9861
        - create the drbd device on the new secondary
9862
        - network attach the drbd on the primary, using an artifice:
9863
          the drbd code for Attach() will connect to the network if it
9864
          finds a device which is connected to the good local disks but
9865
          not network enabled
9866
      - wait for sync across all devices
9867
      - remove all disks from the old secondary
9868

9869
    Failures are not very well handled.
9870

9871
    """
9872
    steps_total = 6
9873

    
9874
    pnode = self.instance.primary_node
9875

    
9876
    # Step: check device activation
9877
    self.lu.LogStep(1, steps_total, "Check device existence")
9878
    self._CheckDisksExistence([self.instance.primary_node])
9879
    self._CheckVolumeGroup([self.instance.primary_node])
9880

    
9881
    # Step: check other node consistency
9882
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9883
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9884

    
9885
    # Step: create new storage
9886
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9887
    for idx, dev in enumerate(self.instance.disks):
9888
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9889
                      (self.new_node, idx))
9890
      # we pass force_create=True to force LVM creation
9891
      for new_lv in dev.children:
9892
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9893
                        _GetInstanceInfoText(self.instance), False)
9894

    
9895
    # Step 4: dbrd minors and drbd setups changes
9896
    # after this, we must manually remove the drbd minors on both the
9897
    # error and the success paths
9898
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9899
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9900
                                         for dev in self.instance.disks],
9901
                                        self.instance.name)
9902
    logging.debug("Allocated minors %r", minors)
9903

    
9904
    iv_names = {}
9905
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9906
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9907
                      (self.new_node, idx))
9908
      # create new devices on new_node; note that we create two IDs:
9909
      # one without port, so the drbd will be activated without
9910
      # networking information on the new node at this stage, and one
9911
      # with network, for the latter activation in step 4
9912
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9913
      if self.instance.primary_node == o_node1:
9914
        p_minor = o_minor1
9915
      else:
9916
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9917
        p_minor = o_minor2
9918

    
9919
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9920
                      p_minor, new_minor, o_secret)
9921
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9922
                    p_minor, new_minor, o_secret)
9923

    
9924
      iv_names[idx] = (dev, dev.children, new_net_id)
9925
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9926
                    new_net_id)
9927
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9928
                              logical_id=new_alone_id,
9929
                              children=dev.children,
9930
                              size=dev.size)
9931
      try:
9932
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9933
                              _GetInstanceInfoText(self.instance), False)
9934
      except errors.GenericError:
9935
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9936
        raise
9937

    
9938
    # We have new devices, shutdown the drbd on the old secondary
9939
    for idx, dev in enumerate(self.instance.disks):
9940
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9941
      self.cfg.SetDiskID(dev, self.target_node)
9942
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9943
      if msg:
9944
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9945
                           "node: %s" % (idx, msg),
9946
                           hint=("Please cleanup this device manually as"
9947
                                 " soon as possible"))
9948

    
9949
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9950
    result = self.rpc.call_drbd_disconnect_net([pnode], self.node_secondary_ip,
9951
                                               self.instance.disks)[pnode]
9952

    
9953
    msg = result.fail_msg
9954
    if msg:
9955
      # detaches didn't succeed (unlikely)
9956
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9957
      raise errors.OpExecError("Can't detach the disks from the network on"
9958
                               " old node: %s" % (msg,))
9959

    
9960
    # if we managed to detach at least one, we update all the disks of
9961
    # the instance to point to the new secondary
9962
    self.lu.LogInfo("Updating instance configuration")
9963
    for dev, _, new_logical_id in iv_names.itervalues():
9964
      dev.logical_id = new_logical_id
9965
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9966

    
9967
    self.cfg.Update(self.instance, feedback_fn)
9968

    
9969
    # and now perform the drbd attach
9970
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9971
                    " (standalone => connected)")
9972
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9973
                                            self.new_node],
9974
                                           self.node_secondary_ip,
9975
                                           self.instance.disks,
9976
                                           self.instance.name,
9977
                                           False)
9978
    for to_node, to_result in result.items():
9979
      msg = to_result.fail_msg
9980
      if msg:
9981
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9982
                           to_node, msg,
9983
                           hint=("please do a gnt-instance info to see the"
9984
                                 " status of disks"))
9985
    cstep = 5
9986
    if self.early_release:
9987
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9988
      cstep += 1
9989
      self._RemoveOldStorage(self.target_node, iv_names)
9990
      # WARNING: we release all node locks here, do not do other RPCs
9991
      # than WaitForSync to the primary node
9992
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9993
                    names=[self.instance.primary_node,
9994
                           self.target_node,
9995
                           self.new_node])
9996

    
9997
    # Wait for sync
9998
    # This can fail as the old devices are degraded and _WaitForSync
9999
    # does a combined result over all disks, so we don't check its return value
10000
    self.lu.LogStep(cstep, steps_total, "Sync devices")
10001
    cstep += 1
10002
    _WaitForSync(self.lu, self.instance)
10003

    
10004
    # Check all devices manually
10005
    self._CheckDevices(self.instance.primary_node, iv_names)
10006

    
10007
    # Step: remove old storage
10008
    if not self.early_release:
10009
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
10010
      self._RemoveOldStorage(self.target_node, iv_names)
10011

    
10012

    
10013
class LURepairNodeStorage(NoHooksLU):
10014
  """Repairs the volume group on a node.
10015

10016
  """
10017
  REQ_BGL = False
10018

    
10019
  def CheckArguments(self):
10020
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
10021

    
10022
    storage_type = self.op.storage_type
10023

    
10024
    if (constants.SO_FIX_CONSISTENCY not in
10025
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
10026
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
10027
                                 " repaired" % storage_type,
10028
                                 errors.ECODE_INVAL)
10029

    
10030
  def ExpandNames(self):
10031
    self.needed_locks = {
10032
      locking.LEVEL_NODE: [self.op.node_name],
10033
      }
10034

    
10035
  def _CheckFaultyDisks(self, instance, node_name):
10036
    """Ensure faulty disks abort the opcode or at least warn."""
10037
    try:
10038
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
10039
                                  node_name, True):
10040
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
10041
                                   " node '%s'" % (instance.name, node_name),
10042
                                   errors.ECODE_STATE)
10043
    except errors.OpPrereqError, err:
10044
      if self.op.ignore_consistency:
10045
        self.proc.LogWarning(str(err.args[0]))
10046
      else:
10047
        raise
10048

    
10049
  def CheckPrereq(self):
10050
    """Check prerequisites.
10051

10052
    """
10053
    # Check whether any instance on this node has faulty disks
10054
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
10055
      if not inst.admin_up:
10056
        continue
10057
      check_nodes = set(inst.all_nodes)
10058
      check_nodes.discard(self.op.node_name)
10059
      for inst_node_name in check_nodes:
10060
        self._CheckFaultyDisks(inst, inst_node_name)
10061

    
10062
  def Exec(self, feedback_fn):
10063
    feedback_fn("Repairing storage unit '%s' on %s ..." %
10064
                (self.op.name, self.op.node_name))
10065

    
10066
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
10067
    result = self.rpc.call_storage_execute(self.op.node_name,
10068
                                           self.op.storage_type, st_args,
10069
                                           self.op.name,
10070
                                           constants.SO_FIX_CONSISTENCY)
10071
    result.Raise("Failed to repair storage unit '%s' on %s" %
10072
                 (self.op.name, self.op.node_name))
10073

    
10074

    
10075
class LUNodeEvacuate(NoHooksLU):
10076
  """Evacuates instances off a list of nodes.
10077

10078
  """
10079
  REQ_BGL = False
10080

    
10081
  def CheckArguments(self):
10082
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
10083

    
10084
  def ExpandNames(self):
10085
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
10086

    
10087
    if self.op.remote_node is not None:
10088
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10089
      assert self.op.remote_node
10090

    
10091
      if self.op.remote_node == self.op.node_name:
10092
        raise errors.OpPrereqError("Can not use evacuated node as a new"
10093
                                   " secondary node", errors.ECODE_INVAL)
10094

    
10095
      if self.op.mode != constants.IALLOCATOR_NEVAC_SEC:
10096
        raise errors.OpPrereqError("Without the use of an iallocator only"
10097
                                   " secondary instances can be evacuated",
10098
                                   errors.ECODE_INVAL)
10099

    
10100
    # Declare locks
10101
    self.share_locks = _ShareAll()
10102
    self.needed_locks = {
10103
      locking.LEVEL_INSTANCE: [],
10104
      locking.LEVEL_NODEGROUP: [],
10105
      locking.LEVEL_NODE: [],
10106
      }
10107

    
10108
    if self.op.remote_node is None:
10109
      # Iallocator will choose any node(s) in the same group
10110
      group_nodes = self.cfg.GetNodeGroupMembersByNodes([self.op.node_name])
10111
    else:
10112
      group_nodes = frozenset([self.op.remote_node])
10113

    
10114
    # Determine nodes to be locked
10115
    self.lock_nodes = set([self.op.node_name]) | group_nodes
10116

    
10117
  def _DetermineInstances(self):
10118
    """Builds list of instances to operate on.
10119

10120
    """
10121
    assert self.op.mode in constants.IALLOCATOR_NEVAC_MODES
10122

    
10123
    if self.op.mode == constants.IALLOCATOR_NEVAC_PRI:
10124
      # Primary instances only
10125
      inst_fn = _GetNodePrimaryInstances
10126
      assert self.op.remote_node is None, \
10127
        "Evacuating primary instances requires iallocator"
10128
    elif self.op.mode == constants.IALLOCATOR_NEVAC_SEC:
10129
      # Secondary instances only
10130
      inst_fn = _GetNodeSecondaryInstances
10131
    else:
10132
      # All instances
10133
      assert self.op.mode == constants.IALLOCATOR_NEVAC_ALL
10134
      inst_fn = _GetNodeInstances
10135

    
10136
    return inst_fn(self.cfg, self.op.node_name)
10137

    
10138
  def DeclareLocks(self, level):
10139
    if level == locking.LEVEL_INSTANCE:
10140
      # Lock instances optimistically, needs verification once node and group
10141
      # locks have been acquired
10142
      self.needed_locks[locking.LEVEL_INSTANCE] = \
10143
        set(i.name for i in self._DetermineInstances())
10144

    
10145
    elif level == locking.LEVEL_NODEGROUP:
10146
      # Lock node groups optimistically, needs verification once nodes have
10147
      # been acquired
10148
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
10149
        self.cfg.GetNodeGroupsFromNodes(self.lock_nodes)
10150

    
10151
    elif level == locking.LEVEL_NODE:
10152
      self.needed_locks[locking.LEVEL_NODE] = self.lock_nodes
10153

    
10154
  def CheckPrereq(self):
10155
    # Verify locks
10156
    owned_instances = self.owned_locks(locking.LEVEL_INSTANCE)
10157
    owned_nodes = self.owned_locks(locking.LEVEL_NODE)
10158
    owned_groups = self.owned_locks(locking.LEVEL_NODEGROUP)
10159

    
10160
    assert owned_nodes == self.lock_nodes
10161

    
10162
    wanted_groups = self.cfg.GetNodeGroupsFromNodes(owned_nodes)
10163
    if owned_groups != wanted_groups:
10164
      raise errors.OpExecError("Node groups changed since locks were acquired,"
10165
                               " current groups are '%s', used to be '%s'" %
10166
                               (utils.CommaJoin(wanted_groups),
10167
                                utils.CommaJoin(owned_groups)))
10168

    
10169
    # Determine affected instances
10170
    self.instances = self._DetermineInstances()
10171
    self.instance_names = [i.name for i in self.instances]
10172

    
10173
    if set(self.instance_names) != owned_instances:
10174
      raise errors.OpExecError("Instances on node '%s' changed since locks"
10175
                               " were acquired, current instances are '%s',"
10176
                               " used to be '%s'" %
10177
                               (self.op.node_name,
10178
                                utils.CommaJoin(self.instance_names),
10179
                                utils.CommaJoin(owned_instances)))
10180

    
10181
    if self.instance_names:
10182
      self.LogInfo("Evacuating instances from node '%s': %s",
10183
                   self.op.node_name,
10184
                   utils.CommaJoin(utils.NiceSort(self.instance_names)))
10185
    else:
10186
      self.LogInfo("No instances to evacuate from node '%s'",
10187
                   self.op.node_name)
10188

    
10189
    if self.op.remote_node is not None:
10190
      for i in self.instances:
10191
        if i.primary_node == self.op.remote_node:
10192
          raise errors.OpPrereqError("Node %s is the primary node of"
10193
                                     " instance %s, cannot use it as"
10194
                                     " secondary" %
10195
                                     (self.op.remote_node, i.name),
10196
                                     errors.ECODE_INVAL)
10197

    
10198
  def Exec(self, feedback_fn):
10199
    assert (self.op.iallocator is not None) ^ (self.op.remote_node is not None)
10200

    
10201
    if not self.instance_names:
10202
      # No instances to evacuate
10203
      jobs = []
10204

    
10205
    elif self.op.iallocator is not None:
10206
      # TODO: Implement relocation to other group
10207
      ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_NODE_EVAC,
10208
                       evac_mode=self.op.mode,
10209
                       instances=list(self.instance_names))
10210

    
10211
      ial.Run(self.op.iallocator)
10212

    
10213
      if not ial.success:
10214
        raise errors.OpPrereqError("Can't compute node evacuation using"
10215
                                   " iallocator '%s': %s" %
10216
                                   (self.op.iallocator, ial.info),
10217
                                   errors.ECODE_NORES)
10218

    
10219
      jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, True)
10220

    
10221
    elif self.op.remote_node is not None:
10222
      assert self.op.mode == constants.IALLOCATOR_NEVAC_SEC
10223
      jobs = [
10224
        [opcodes.OpInstanceReplaceDisks(instance_name=instance_name,
10225
                                        remote_node=self.op.remote_node,
10226
                                        disks=[],
10227
                                        mode=constants.REPLACE_DISK_CHG,
10228
                                        early_release=self.op.early_release)]
10229
        for instance_name in self.instance_names
10230
        ]
10231

    
10232
    else:
10233
      raise errors.ProgrammerError("No iallocator or remote node")
10234

    
10235
    return ResultWithJobs(jobs)
10236

    
10237

    
10238
def _SetOpEarlyRelease(early_release, op):
10239
  """Sets C{early_release} flag on opcodes if available.
10240

10241
  """
10242
  try:
10243
    op.early_release = early_release
10244
  except AttributeError:
10245
    assert not isinstance(op, opcodes.OpInstanceReplaceDisks)
10246

    
10247
  return op
10248

    
10249

    
10250
def _NodeEvacDest(use_nodes, group, nodes):
10251
  """Returns group or nodes depending on caller's choice.
10252

10253
  """
10254
  if use_nodes:
10255
    return utils.CommaJoin(nodes)
10256
  else:
10257
    return group
10258

    
10259

    
10260
def _LoadNodeEvacResult(lu, alloc_result, early_release, use_nodes):
10261
  """Unpacks the result of change-group and node-evacuate iallocator requests.
10262

10263
  Iallocator modes L{constants.IALLOCATOR_MODE_NODE_EVAC} and
10264
  L{constants.IALLOCATOR_MODE_CHG_GROUP}.
10265

10266
  @type lu: L{LogicalUnit}
10267
  @param lu: Logical unit instance
10268
  @type alloc_result: tuple/list
10269
  @param alloc_result: Result from iallocator
10270
  @type early_release: bool
10271
  @param early_release: Whether to release locks early if possible
10272
  @type use_nodes: bool
10273
  @param use_nodes: Whether to display node names instead of groups
10274

10275
  """
10276
  (moved, failed, jobs) = alloc_result
10277

    
10278
  if failed:
10279
    lu.LogWarning("Unable to evacuate instances %s",
10280
                  utils.CommaJoin("%s (%s)" % (name, reason)
10281
                                  for (name, reason) in failed))
10282

    
10283
  if moved:
10284
    lu.LogInfo("Instances to be moved: %s",
10285
               utils.CommaJoin("%s (to %s)" %
10286
                               (name, _NodeEvacDest(use_nodes, group, nodes))
10287
                               for (name, group, nodes) in moved))
10288

    
10289
  return [map(compat.partial(_SetOpEarlyRelease, early_release),
10290
              map(opcodes.OpCode.LoadOpCode, ops))
10291
          for ops in jobs]
10292

    
10293

    
10294
class LUInstanceGrowDisk(LogicalUnit):
10295
  """Grow a disk of an instance.
10296

10297
  """
10298
  HPATH = "disk-grow"
10299
  HTYPE = constants.HTYPE_INSTANCE
10300
  REQ_BGL = False
10301

    
10302
  def ExpandNames(self):
10303
    self._ExpandAndLockInstance()
10304
    self.needed_locks[locking.LEVEL_NODE] = []
10305
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10306

    
10307
  def DeclareLocks(self, level):
10308
    if level == locking.LEVEL_NODE:
10309
      self._LockInstancesNodes()
10310

    
10311
  def BuildHooksEnv(self):
10312
    """Build hooks env.
10313

10314
    This runs on the master, the primary and all the secondaries.
10315

10316
    """
10317
    env = {
10318
      "DISK": self.op.disk,
10319
      "AMOUNT": self.op.amount,
10320
      }
10321
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10322
    return env
10323

    
10324
  def BuildHooksNodes(self):
10325
    """Build hooks nodes.
10326

10327
    """
10328
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10329
    return (nl, nl)
10330

    
10331
  def CheckPrereq(self):
10332
    """Check prerequisites.
10333

10334
    This checks that the instance is in the cluster.
10335

10336
    """
10337
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10338
    assert instance is not None, \
10339
      "Cannot retrieve locked instance %s" % self.op.instance_name
10340
    nodenames = list(instance.all_nodes)
10341
    for node in nodenames:
10342
      _CheckNodeOnline(self, node)
10343

    
10344
    self.instance = instance
10345

    
10346
    if instance.disk_template not in constants.DTS_GROWABLE:
10347
      raise errors.OpPrereqError("Instance's disk layout does not support"
10348
                                 " growing", errors.ECODE_INVAL)
10349

    
10350
    self.disk = instance.FindDisk(self.op.disk)
10351

    
10352
    if instance.disk_template not in (constants.DT_FILE,
10353
                                      constants.DT_SHARED_FILE):
10354
      # TODO: check the free disk space for file, when that feature will be
10355
      # supported
10356
      _CheckNodesFreeDiskPerVG(self, nodenames,
10357
                               self.disk.ComputeGrowth(self.op.amount))
10358

    
10359
  def Exec(self, feedback_fn):
10360
    """Execute disk grow.
10361

10362
    """
10363
    instance = self.instance
10364
    disk = self.disk
10365

    
10366
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
10367
    if not disks_ok:
10368
      raise errors.OpExecError("Cannot activate block device to grow")
10369

    
10370
    # First run all grow ops in dry-run mode
10371
    for node in instance.all_nodes:
10372
      self.cfg.SetDiskID(disk, node)
10373
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
10374
      result.Raise("Grow request failed to node %s" % node)
10375

    
10376
    # We know that (as far as we can test) operations across different
10377
    # nodes will succeed, time to run it for real
10378
    for node in instance.all_nodes:
10379
      self.cfg.SetDiskID(disk, node)
10380
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
10381
      result.Raise("Grow request failed to node %s" % node)
10382

    
10383
      # TODO: Rewrite code to work properly
10384
      # DRBD goes into sync mode for a short amount of time after executing the
10385
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
10386
      # calling "resize" in sync mode fails. Sleeping for a short amount of
10387
      # time is a work-around.
10388
      time.sleep(5)
10389

    
10390
    disk.RecordGrow(self.op.amount)
10391
    self.cfg.Update(instance, feedback_fn)
10392
    if self.op.wait_for_sync:
10393
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
10394
      if disk_abort:
10395
        self.proc.LogWarning("Disk sync-ing has not returned a good"
10396
                             " status; please check the instance")
10397
      if not instance.admin_up:
10398
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
10399
    elif not instance.admin_up:
10400
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
10401
                           " not supposed to be running because no wait for"
10402
                           " sync mode was requested")
10403

    
10404

    
10405
class LUInstanceQueryData(NoHooksLU):
10406
  """Query runtime instance data.
10407

10408
  """
10409
  REQ_BGL = False
10410

    
10411
  def ExpandNames(self):
10412
    self.needed_locks = {}
10413

    
10414
    # Use locking if requested or when non-static information is wanted
10415
    if not (self.op.static or self.op.use_locking):
10416
      self.LogWarning("Non-static data requested, locks need to be acquired")
10417
      self.op.use_locking = True
10418

    
10419
    if self.op.instances or not self.op.use_locking:
10420
      # Expand instance names right here
10421
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
10422
    else:
10423
      # Will use acquired locks
10424
      self.wanted_names = None
10425

    
10426
    if self.op.use_locking:
10427
      self.share_locks = _ShareAll()
10428

    
10429
      if self.wanted_names is None:
10430
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
10431
      else:
10432
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
10433

    
10434
      self.needed_locks[locking.LEVEL_NODE] = []
10435
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10436

    
10437
  def DeclareLocks(self, level):
10438
    if self.op.use_locking and level == locking.LEVEL_NODE:
10439
      self._LockInstancesNodes()
10440

    
10441
  def CheckPrereq(self):
10442
    """Check prerequisites.
10443

10444
    This only checks the optional instance list against the existing names.
10445

10446
    """
10447
    if self.wanted_names is None:
10448
      assert self.op.use_locking, "Locking was not used"
10449
      self.wanted_names = self.owned_locks(locking.LEVEL_INSTANCE)
10450

    
10451
    self.wanted_instances = \
10452
        map(compat.snd, self.cfg.GetMultiInstanceInfo(self.wanted_names))
10453

    
10454
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
10455
    """Returns the status of a block device
10456

10457
    """
10458
    if self.op.static or not node:
10459
      return None
10460

    
10461
    self.cfg.SetDiskID(dev, node)
10462

    
10463
    result = self.rpc.call_blockdev_find(node, dev)
10464
    if result.offline:
10465
      return None
10466

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

    
10469
    status = result.payload
10470
    if status is None:
10471
      return None
10472

    
10473
    return (status.dev_path, status.major, status.minor,
10474
            status.sync_percent, status.estimated_time,
10475
            status.is_degraded, status.ldisk_status)
10476

    
10477
  def _ComputeDiskStatus(self, instance, snode, dev):
10478
    """Compute block device status.
10479

10480
    """
10481
    if dev.dev_type in constants.LDS_DRBD:
10482
      # we change the snode then (otherwise we use the one passed in)
10483
      if dev.logical_id[0] == instance.primary_node:
10484
        snode = dev.logical_id[1]
10485
      else:
10486
        snode = dev.logical_id[0]
10487

    
10488
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
10489
                                              instance.name, dev)
10490
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
10491

    
10492
    if dev.children:
10493
      dev_children = map(compat.partial(self._ComputeDiskStatus,
10494
                                        instance, snode),
10495
                         dev.children)
10496
    else:
10497
      dev_children = []
10498

    
10499
    return {
10500
      "iv_name": dev.iv_name,
10501
      "dev_type": dev.dev_type,
10502
      "logical_id": dev.logical_id,
10503
      "physical_id": dev.physical_id,
10504
      "pstatus": dev_pstatus,
10505
      "sstatus": dev_sstatus,
10506
      "children": dev_children,
10507
      "mode": dev.mode,
10508
      "size": dev.size,
10509
      }
10510

    
10511
  def Exec(self, feedback_fn):
10512
    """Gather and return data"""
10513
    result = {}
10514

    
10515
    cluster = self.cfg.GetClusterInfo()
10516

    
10517
    pri_nodes = self.cfg.GetMultiNodeInfo(i.primary_node
10518
                                          for i in self.wanted_instances)
10519
    for instance, (_, pnode) in zip(self.wanted_instances, pri_nodes):
10520
      if self.op.static or pnode.offline:
10521
        remote_state = None
10522
        if pnode.offline:
10523
          self.LogWarning("Primary node %s is marked offline, returning static"
10524
                          " information only for instance %s" %
10525
                          (pnode.name, instance.name))
10526
      else:
10527
        remote_info = self.rpc.call_instance_info(instance.primary_node,
10528
                                                  instance.name,
10529
                                                  instance.hypervisor)
10530
        remote_info.Raise("Error checking node %s" % instance.primary_node)
10531
        remote_info = remote_info.payload
10532
        if remote_info and "state" in remote_info:
10533
          remote_state = "up"
10534
        else:
10535
          remote_state = "down"
10536

    
10537
      if instance.admin_up:
10538
        config_state = "up"
10539
      else:
10540
        config_state = "down"
10541

    
10542
      disks = map(compat.partial(self._ComputeDiskStatus, instance, None),
10543
                  instance.disks)
10544

    
10545
      result[instance.name] = {
10546
        "name": instance.name,
10547
        "config_state": config_state,
10548
        "run_state": remote_state,
10549
        "pnode": instance.primary_node,
10550
        "snodes": instance.secondary_nodes,
10551
        "os": instance.os,
10552
        # this happens to be the same format used for hooks
10553
        "nics": _NICListToTuple(self, instance.nics),
10554
        "disk_template": instance.disk_template,
10555
        "disks": disks,
10556
        "hypervisor": instance.hypervisor,
10557
        "network_port": instance.network_port,
10558
        "hv_instance": instance.hvparams,
10559
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
10560
        "be_instance": instance.beparams,
10561
        "be_actual": cluster.FillBE(instance),
10562
        "os_instance": instance.osparams,
10563
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
10564
        "serial_no": instance.serial_no,
10565
        "mtime": instance.mtime,
10566
        "ctime": instance.ctime,
10567
        "uuid": instance.uuid,
10568
        }
10569

    
10570
    return result
10571

    
10572

    
10573
class LUInstanceSetParams(LogicalUnit):
10574
  """Modifies an instances's parameters.
10575

10576
  """
10577
  HPATH = "instance-modify"
10578
  HTYPE = constants.HTYPE_INSTANCE
10579
  REQ_BGL = False
10580

    
10581
  def CheckArguments(self):
10582
    if not (self.op.nics or self.op.disks or self.op.disk_template or
10583
            self.op.hvparams or self.op.beparams or self.op.os_name):
10584
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
10585

    
10586
    if self.op.hvparams:
10587
      _CheckGlobalHvParams(self.op.hvparams)
10588

    
10589
    # Disk validation
10590
    disk_addremove = 0
10591
    for disk_op, disk_dict in self.op.disks:
10592
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
10593
      if disk_op == constants.DDM_REMOVE:
10594
        disk_addremove += 1
10595
        continue
10596
      elif disk_op == constants.DDM_ADD:
10597
        disk_addremove += 1
10598
      else:
10599
        if not isinstance(disk_op, int):
10600
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
10601
        if not isinstance(disk_dict, dict):
10602
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
10603
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10604

    
10605
      if disk_op == constants.DDM_ADD:
10606
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
10607
        if mode not in constants.DISK_ACCESS_SET:
10608
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
10609
                                     errors.ECODE_INVAL)
10610
        size = disk_dict.get(constants.IDISK_SIZE, None)
10611
        if size is None:
10612
          raise errors.OpPrereqError("Required disk parameter size missing",
10613
                                     errors.ECODE_INVAL)
10614
        try:
10615
          size = int(size)
10616
        except (TypeError, ValueError), err:
10617
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10618
                                     str(err), errors.ECODE_INVAL)
10619
        disk_dict[constants.IDISK_SIZE] = size
10620
      else:
10621
        # modification of disk
10622
        if constants.IDISK_SIZE in disk_dict:
10623
          raise errors.OpPrereqError("Disk size change not possible, use"
10624
                                     " grow-disk", errors.ECODE_INVAL)
10625

    
10626
    if disk_addremove > 1:
10627
      raise errors.OpPrereqError("Only one disk add or remove operation"
10628
                                 " supported at a time", errors.ECODE_INVAL)
10629

    
10630
    if self.op.disks and self.op.disk_template is not None:
10631
      raise errors.OpPrereqError("Disk template conversion and other disk"
10632
                                 " changes not supported at the same time",
10633
                                 errors.ECODE_INVAL)
10634

    
10635
    if (self.op.disk_template and
10636
        self.op.disk_template in constants.DTS_INT_MIRROR and
10637
        self.op.remote_node is None):
10638
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
10639
                                 " one requires specifying a secondary node",
10640
                                 errors.ECODE_INVAL)
10641

    
10642
    # NIC validation
10643
    nic_addremove = 0
10644
    for nic_op, nic_dict in self.op.nics:
10645
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10646
      if nic_op == constants.DDM_REMOVE:
10647
        nic_addremove += 1
10648
        continue
10649
      elif nic_op == constants.DDM_ADD:
10650
        nic_addremove += 1
10651
      else:
10652
        if not isinstance(nic_op, int):
10653
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10654
        if not isinstance(nic_dict, dict):
10655
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10656
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10657

    
10658
      # nic_dict should be a dict
10659
      nic_ip = nic_dict.get(constants.INIC_IP, None)
10660
      if nic_ip is not None:
10661
        if nic_ip.lower() == constants.VALUE_NONE:
10662
          nic_dict[constants.INIC_IP] = None
10663
        else:
10664
          if not netutils.IPAddress.IsValid(nic_ip):
10665
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10666
                                       errors.ECODE_INVAL)
10667

    
10668
      nic_bridge = nic_dict.get("bridge", None)
10669
      nic_link = nic_dict.get(constants.INIC_LINK, None)
10670
      if nic_bridge and nic_link:
10671
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10672
                                   " at the same time", errors.ECODE_INVAL)
10673
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10674
        nic_dict["bridge"] = None
10675
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10676
        nic_dict[constants.INIC_LINK] = None
10677

    
10678
      if nic_op == constants.DDM_ADD:
10679
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
10680
        if nic_mac is None:
10681
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10682

    
10683
      if constants.INIC_MAC in nic_dict:
10684
        nic_mac = nic_dict[constants.INIC_MAC]
10685
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10686
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10687

    
10688
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10689
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10690
                                     " modifying an existing nic",
10691
                                     errors.ECODE_INVAL)
10692

    
10693
    if nic_addremove > 1:
10694
      raise errors.OpPrereqError("Only one NIC add or remove operation"
10695
                                 " supported at a time", errors.ECODE_INVAL)
10696

    
10697
  def ExpandNames(self):
10698
    self._ExpandAndLockInstance()
10699
    self.needed_locks[locking.LEVEL_NODE] = []
10700
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10701

    
10702
  def DeclareLocks(self, level):
10703
    if level == locking.LEVEL_NODE:
10704
      self._LockInstancesNodes()
10705
      if self.op.disk_template and self.op.remote_node:
10706
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10707
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10708

    
10709
  def BuildHooksEnv(self):
10710
    """Build hooks env.
10711

10712
    This runs on the master, primary and secondaries.
10713

10714
    """
10715
    args = dict()
10716
    if constants.BE_MEMORY in self.be_new:
10717
      args["memory"] = self.be_new[constants.BE_MEMORY]
10718
    if constants.BE_VCPUS in self.be_new:
10719
      args["vcpus"] = self.be_new[constants.BE_VCPUS]
10720
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10721
    # information at all.
10722
    if self.op.nics:
10723
      args["nics"] = []
10724
      nic_override = dict(self.op.nics)
10725
      for idx, nic in enumerate(self.instance.nics):
10726
        if idx in nic_override:
10727
          this_nic_override = nic_override[idx]
10728
        else:
10729
          this_nic_override = {}
10730
        if constants.INIC_IP in this_nic_override:
10731
          ip = this_nic_override[constants.INIC_IP]
10732
        else:
10733
          ip = nic.ip
10734
        if constants.INIC_MAC in this_nic_override:
10735
          mac = this_nic_override[constants.INIC_MAC]
10736
        else:
10737
          mac = nic.mac
10738
        if idx in self.nic_pnew:
10739
          nicparams = self.nic_pnew[idx]
10740
        else:
10741
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10742
        mode = nicparams[constants.NIC_MODE]
10743
        link = nicparams[constants.NIC_LINK]
10744
        args["nics"].append((ip, mac, mode, link))
10745
      if constants.DDM_ADD in nic_override:
10746
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10747
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10748
        nicparams = self.nic_pnew[constants.DDM_ADD]
10749
        mode = nicparams[constants.NIC_MODE]
10750
        link = nicparams[constants.NIC_LINK]
10751
        args["nics"].append((ip, mac, mode, link))
10752
      elif constants.DDM_REMOVE in nic_override:
10753
        del args["nics"][-1]
10754

    
10755
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10756
    if self.op.disk_template:
10757
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10758

    
10759
    return env
10760

    
10761
  def BuildHooksNodes(self):
10762
    """Build hooks nodes.
10763

10764
    """
10765
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10766
    return (nl, nl)
10767

    
10768
  def CheckPrereq(self):
10769
    """Check prerequisites.
10770

10771
    This only checks the instance list against the existing names.
10772

10773
    """
10774
    # checking the new params on the primary/secondary nodes
10775

    
10776
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10777
    cluster = self.cluster = self.cfg.GetClusterInfo()
10778
    assert self.instance is not None, \
10779
      "Cannot retrieve locked instance %s" % self.op.instance_name
10780
    pnode = instance.primary_node
10781
    nodelist = list(instance.all_nodes)
10782

    
10783
    # OS change
10784
    if self.op.os_name and not self.op.force:
10785
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10786
                      self.op.force_variant)
10787
      instance_os = self.op.os_name
10788
    else:
10789
      instance_os = instance.os
10790

    
10791
    if self.op.disk_template:
10792
      if instance.disk_template == self.op.disk_template:
10793
        raise errors.OpPrereqError("Instance already has disk template %s" %
10794
                                   instance.disk_template, errors.ECODE_INVAL)
10795

    
10796
      if (instance.disk_template,
10797
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10798
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10799
                                   " %s to %s" % (instance.disk_template,
10800
                                                  self.op.disk_template),
10801
                                   errors.ECODE_INVAL)
10802
      _CheckInstanceDown(self, instance, "cannot change disk template")
10803
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10804
        if self.op.remote_node == pnode:
10805
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10806
                                     " as the primary node of the instance" %
10807
                                     self.op.remote_node, errors.ECODE_STATE)
10808
        _CheckNodeOnline(self, self.op.remote_node)
10809
        _CheckNodeNotDrained(self, self.op.remote_node)
10810
        # FIXME: here we assume that the old instance type is DT_PLAIN
10811
        assert instance.disk_template == constants.DT_PLAIN
10812
        disks = [{constants.IDISK_SIZE: d.size,
10813
                  constants.IDISK_VG: d.logical_id[0]}
10814
                 for d in instance.disks]
10815
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10816
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10817

    
10818
    # hvparams processing
10819
    if self.op.hvparams:
10820
      hv_type = instance.hypervisor
10821
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10822
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10823
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10824

    
10825
      # local check
10826
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10827
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10828
      self.hv_new = hv_new # the new actual values
10829
      self.hv_inst = i_hvdict # the new dict (without defaults)
10830
    else:
10831
      self.hv_new = self.hv_inst = {}
10832

    
10833
    # beparams processing
10834
    if self.op.beparams:
10835
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10836
                                   use_none=True)
10837
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10838
      be_new = cluster.SimpleFillBE(i_bedict)
10839
      self.be_new = be_new # the new actual values
10840
      self.be_inst = i_bedict # the new dict (without defaults)
10841
    else:
10842
      self.be_new = self.be_inst = {}
10843
    be_old = cluster.FillBE(instance)
10844

    
10845
    # osparams processing
10846
    if self.op.osparams:
10847
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10848
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10849
      self.os_inst = i_osdict # the new dict (without defaults)
10850
    else:
10851
      self.os_inst = {}
10852

    
10853
    self.warn = []
10854

    
10855
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10856
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10857
      mem_check_list = [pnode]
10858
      if be_new[constants.BE_AUTO_BALANCE]:
10859
        # either we changed auto_balance to yes or it was from before
10860
        mem_check_list.extend(instance.secondary_nodes)
10861
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10862
                                                  instance.hypervisor)
10863
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10864
                                         instance.hypervisor)
10865
      pninfo = nodeinfo[pnode]
10866
      msg = pninfo.fail_msg
10867
      if msg:
10868
        # Assume the primary node is unreachable and go ahead
10869
        self.warn.append("Can't get info from primary node %s: %s" %
10870
                         (pnode, msg))
10871
      elif not isinstance(pninfo.payload.get("memory_free", None), int):
10872
        self.warn.append("Node data from primary node %s doesn't contain"
10873
                         " free memory information" % pnode)
10874
      elif instance_info.fail_msg:
10875
        self.warn.append("Can't get instance runtime information: %s" %
10876
                        instance_info.fail_msg)
10877
      else:
10878
        if instance_info.payload:
10879
          current_mem = int(instance_info.payload["memory"])
10880
        else:
10881
          # Assume instance not running
10882
          # (there is a slight race condition here, but it's not very probable,
10883
          # and we have no other way to check)
10884
          current_mem = 0
10885
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10886
                    pninfo.payload["memory_free"])
10887
        if miss_mem > 0:
10888
          raise errors.OpPrereqError("This change will prevent the instance"
10889
                                     " from starting, due to %d MB of memory"
10890
                                     " missing on its primary node" % miss_mem,
10891
                                     errors.ECODE_NORES)
10892

    
10893
      if be_new[constants.BE_AUTO_BALANCE]:
10894
        for node, nres in nodeinfo.items():
10895
          if node not in instance.secondary_nodes:
10896
            continue
10897
          nres.Raise("Can't get info from secondary node %s" % node,
10898
                     prereq=True, ecode=errors.ECODE_STATE)
10899
          if not isinstance(nres.payload.get("memory_free", None), int):
10900
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10901
                                       " memory information" % node,
10902
                                       errors.ECODE_STATE)
10903
          elif be_new[constants.BE_MEMORY] > nres.payload["memory_free"]:
10904
            raise errors.OpPrereqError("This change will prevent the instance"
10905
                                       " from failover to its secondary node"
10906
                                       " %s, due to not enough memory" % node,
10907
                                       errors.ECODE_STATE)
10908

    
10909
    # NIC processing
10910
    self.nic_pnew = {}
10911
    self.nic_pinst = {}
10912
    for nic_op, nic_dict in self.op.nics:
10913
      if nic_op == constants.DDM_REMOVE:
10914
        if not instance.nics:
10915
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10916
                                     errors.ECODE_INVAL)
10917
        continue
10918
      if nic_op != constants.DDM_ADD:
10919
        # an existing nic
10920
        if not instance.nics:
10921
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10922
                                     " no NICs" % nic_op,
10923
                                     errors.ECODE_INVAL)
10924
        if nic_op < 0 or nic_op >= len(instance.nics):
10925
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10926
                                     " are 0 to %d" %
10927
                                     (nic_op, len(instance.nics) - 1),
10928
                                     errors.ECODE_INVAL)
10929
        old_nic_params = instance.nics[nic_op].nicparams
10930
        old_nic_ip = instance.nics[nic_op].ip
10931
      else:
10932
        old_nic_params = {}
10933
        old_nic_ip = None
10934

    
10935
      update_params_dict = dict([(key, nic_dict[key])
10936
                                 for key in constants.NICS_PARAMETERS
10937
                                 if key in nic_dict])
10938

    
10939
      if "bridge" in nic_dict:
10940
        update_params_dict[constants.NIC_LINK] = nic_dict["bridge"]
10941

    
10942
      new_nic_params = _GetUpdatedParams(old_nic_params,
10943
                                         update_params_dict)
10944
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10945
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10946
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10947
      self.nic_pinst[nic_op] = new_nic_params
10948
      self.nic_pnew[nic_op] = new_filled_nic_params
10949
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10950

    
10951
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10952
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10953
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10954
        if msg:
10955
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10956
          if self.op.force:
10957
            self.warn.append(msg)
10958
          else:
10959
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10960
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10961
        if constants.INIC_IP in nic_dict:
10962
          nic_ip = nic_dict[constants.INIC_IP]
10963
        else:
10964
          nic_ip = old_nic_ip
10965
        if nic_ip is None:
10966
          raise errors.OpPrereqError("Cannot set the nic ip to None"
10967
                                     " on a routed nic", errors.ECODE_INVAL)
10968
      if constants.INIC_MAC in nic_dict:
10969
        nic_mac = nic_dict[constants.INIC_MAC]
10970
        if nic_mac is None:
10971
          raise errors.OpPrereqError("Cannot set the nic mac to None",
10972
                                     errors.ECODE_INVAL)
10973
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10974
          # otherwise generate the mac
10975
          nic_dict[constants.INIC_MAC] = \
10976
            self.cfg.GenerateMAC(self.proc.GetECId())
10977
        else:
10978
          # or validate/reserve the current one
10979
          try:
10980
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10981
          except errors.ReservationError:
10982
            raise errors.OpPrereqError("MAC address %s already in use"
10983
                                       " in cluster" % nic_mac,
10984
                                       errors.ECODE_NOTUNIQUE)
10985

    
10986
    # DISK processing
10987
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10988
      raise errors.OpPrereqError("Disk operations not supported for"
10989
                                 " diskless instances",
10990
                                 errors.ECODE_INVAL)
10991
    for disk_op, _ in self.op.disks:
10992
      if disk_op == constants.DDM_REMOVE:
10993
        if len(instance.disks) == 1:
10994
          raise errors.OpPrereqError("Cannot remove the last disk of"
10995
                                     " an instance", errors.ECODE_INVAL)
10996
        _CheckInstanceDown(self, instance, "cannot remove disks")
10997

    
10998
      if (disk_op == constants.DDM_ADD and
10999
          len(instance.disks) >= constants.MAX_DISKS):
11000
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
11001
                                   " add more" % constants.MAX_DISKS,
11002
                                   errors.ECODE_STATE)
11003
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
11004
        # an existing disk
11005
        if disk_op < 0 or disk_op >= len(instance.disks):
11006
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
11007
                                     " are 0 to %d" %
11008
                                     (disk_op, len(instance.disks)),
11009
                                     errors.ECODE_INVAL)
11010

    
11011
    return
11012

    
11013
  def _ConvertPlainToDrbd(self, feedback_fn):
11014
    """Converts an instance from plain to drbd.
11015

11016
    """
11017
    feedback_fn("Converting template to drbd")
11018
    instance = self.instance
11019
    pnode = instance.primary_node
11020
    snode = self.op.remote_node
11021

    
11022
    # create a fake disk info for _GenerateDiskTemplate
11023
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
11024
                  constants.IDISK_VG: d.logical_id[0]}
11025
                 for d in instance.disks]
11026
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
11027
                                      instance.name, pnode, [snode],
11028
                                      disk_info, None, None, 0, feedback_fn)
11029
    info = _GetInstanceInfoText(instance)
11030
    feedback_fn("Creating aditional volumes...")
11031
    # first, create the missing data and meta devices
11032
    for disk in new_disks:
11033
      # unfortunately this is... not too nice
11034
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
11035
                            info, True)
11036
      for child in disk.children:
11037
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
11038
    # at this stage, all new LVs have been created, we can rename the
11039
    # old ones
11040
    feedback_fn("Renaming original volumes...")
11041
    rename_list = [(o, n.children[0].logical_id)
11042
                   for (o, n) in zip(instance.disks, new_disks)]
11043
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
11044
    result.Raise("Failed to rename original LVs")
11045

    
11046
    feedback_fn("Initializing DRBD devices...")
11047
    # all child devices are in place, we can now create the DRBD devices
11048
    for disk in new_disks:
11049
      for node in [pnode, snode]:
11050
        f_create = node == pnode
11051
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
11052

    
11053
    # at this point, the instance has been modified
11054
    instance.disk_template = constants.DT_DRBD8
11055
    instance.disks = new_disks
11056
    self.cfg.Update(instance, feedback_fn)
11057

    
11058
    # disks are created, waiting for sync
11059
    disk_abort = not _WaitForSync(self, instance,
11060
                                  oneshot=not self.op.wait_for_sync)
11061
    if disk_abort:
11062
      raise errors.OpExecError("There are some degraded disks for"
11063
                               " this instance, please cleanup manually")
11064

    
11065
  def _ConvertDrbdToPlain(self, feedback_fn):
11066
    """Converts an instance from drbd to plain.
11067

11068
    """
11069
    instance = self.instance
11070
    assert len(instance.secondary_nodes) == 1
11071
    pnode = instance.primary_node
11072
    snode = instance.secondary_nodes[0]
11073
    feedback_fn("Converting template to plain")
11074

    
11075
    old_disks = instance.disks
11076
    new_disks = [d.children[0] for d in old_disks]
11077

    
11078
    # copy over size and mode
11079
    for parent, child in zip(old_disks, new_disks):
11080
      child.size = parent.size
11081
      child.mode = parent.mode
11082

    
11083
    # update instance structure
11084
    instance.disks = new_disks
11085
    instance.disk_template = constants.DT_PLAIN
11086
    self.cfg.Update(instance, feedback_fn)
11087

    
11088
    feedback_fn("Removing volumes on the secondary node...")
11089
    for disk in old_disks:
11090
      self.cfg.SetDiskID(disk, snode)
11091
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
11092
      if msg:
11093
        self.LogWarning("Could not remove block device %s on node %s,"
11094
                        " continuing anyway: %s", disk.iv_name, snode, msg)
11095

    
11096
    feedback_fn("Removing unneeded volumes on the primary node...")
11097
    for idx, disk in enumerate(old_disks):
11098
      meta = disk.children[1]
11099
      self.cfg.SetDiskID(meta, pnode)
11100
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
11101
      if msg:
11102
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
11103
                        " continuing anyway: %s", idx, pnode, msg)
11104

    
11105
  def Exec(self, feedback_fn):
11106
    """Modifies an instance.
11107

11108
    All parameters take effect only at the next restart of the instance.
11109

11110
    """
11111
    # Process here the warnings from CheckPrereq, as we don't have a
11112
    # feedback_fn there.
11113
    for warn in self.warn:
11114
      feedback_fn("WARNING: %s" % warn)
11115

    
11116
    result = []
11117
    instance = self.instance
11118
    # disk changes
11119
    for disk_op, disk_dict in self.op.disks:
11120
      if disk_op == constants.DDM_REMOVE:
11121
        # remove the last disk
11122
        device = instance.disks.pop()
11123
        device_idx = len(instance.disks)
11124
        for node, disk in device.ComputeNodeTree(instance.primary_node):
11125
          self.cfg.SetDiskID(disk, node)
11126
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
11127
          if msg:
11128
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
11129
                            " continuing anyway", device_idx, node, msg)
11130
        result.append(("disk/%d" % device_idx, "remove"))
11131
      elif disk_op == constants.DDM_ADD:
11132
        # add a new disk
11133
        if instance.disk_template in (constants.DT_FILE,
11134
                                        constants.DT_SHARED_FILE):
11135
          file_driver, file_path = instance.disks[0].logical_id
11136
          file_path = os.path.dirname(file_path)
11137
        else:
11138
          file_driver = file_path = None
11139
        disk_idx_base = len(instance.disks)
11140
        new_disk = _GenerateDiskTemplate(self,
11141
                                         instance.disk_template,
11142
                                         instance.name, instance.primary_node,
11143
                                         instance.secondary_nodes,
11144
                                         [disk_dict],
11145
                                         file_path,
11146
                                         file_driver,
11147
                                         disk_idx_base, feedback_fn)[0]
11148
        instance.disks.append(new_disk)
11149
        info = _GetInstanceInfoText(instance)
11150

    
11151
        logging.info("Creating volume %s for instance %s",
11152
                     new_disk.iv_name, instance.name)
11153
        # Note: this needs to be kept in sync with _CreateDisks
11154
        #HARDCODE
11155
        for node in instance.all_nodes:
11156
          f_create = node == instance.primary_node
11157
          try:
11158
            _CreateBlockDev(self, node, instance, new_disk,
11159
                            f_create, info, f_create)
11160
          except errors.OpExecError, err:
11161
            self.LogWarning("Failed to create volume %s (%s) on"
11162
                            " node %s: %s",
11163
                            new_disk.iv_name, new_disk, node, err)
11164
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
11165
                       (new_disk.size, new_disk.mode)))
11166
      else:
11167
        # change a given disk
11168
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
11169
        result.append(("disk.mode/%d" % disk_op,
11170
                       disk_dict[constants.IDISK_MODE]))
11171

    
11172
    if self.op.disk_template:
11173
      r_shut = _ShutdownInstanceDisks(self, instance)
11174
      if not r_shut:
11175
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
11176
                                 " proceed with disk template conversion")
11177
      mode = (instance.disk_template, self.op.disk_template)
11178
      try:
11179
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
11180
      except:
11181
        self.cfg.ReleaseDRBDMinors(instance.name)
11182
        raise
11183
      result.append(("disk_template", self.op.disk_template))
11184

    
11185
    # NIC changes
11186
    for nic_op, nic_dict in self.op.nics:
11187
      if nic_op == constants.DDM_REMOVE:
11188
        # remove the last nic
11189
        del instance.nics[-1]
11190
        result.append(("nic.%d" % len(instance.nics), "remove"))
11191
      elif nic_op == constants.DDM_ADD:
11192
        # mac and bridge should be set, by now
11193
        mac = nic_dict[constants.INIC_MAC]
11194
        ip = nic_dict.get(constants.INIC_IP, None)
11195
        nicparams = self.nic_pinst[constants.DDM_ADD]
11196
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
11197
        instance.nics.append(new_nic)
11198
        result.append(("nic.%d" % (len(instance.nics) - 1),
11199
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
11200
                       (new_nic.mac, new_nic.ip,
11201
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
11202
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
11203
                       )))
11204
      else:
11205
        for key in (constants.INIC_MAC, constants.INIC_IP):
11206
          if key in nic_dict:
11207
            setattr(instance.nics[nic_op], key, nic_dict[key])
11208
        if nic_op in self.nic_pinst:
11209
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
11210
        for key, val in nic_dict.iteritems():
11211
          result.append(("nic.%s/%d" % (key, nic_op), val))
11212

    
11213
    # hvparams changes
11214
    if self.op.hvparams:
11215
      instance.hvparams = self.hv_inst
11216
      for key, val in self.op.hvparams.iteritems():
11217
        result.append(("hv/%s" % key, val))
11218

    
11219
    # beparams changes
11220
    if self.op.beparams:
11221
      instance.beparams = self.be_inst
11222
      for key, val in self.op.beparams.iteritems():
11223
        result.append(("be/%s" % key, val))
11224

    
11225
    # OS change
11226
    if self.op.os_name:
11227
      instance.os = self.op.os_name
11228

    
11229
    # osparams changes
11230
    if self.op.osparams:
11231
      instance.osparams = self.os_inst
11232
      for key, val in self.op.osparams.iteritems():
11233
        result.append(("os/%s" % key, val))
11234

    
11235
    self.cfg.Update(instance, feedback_fn)
11236

    
11237
    return result
11238

    
11239
  _DISK_CONVERSIONS = {
11240
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
11241
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
11242
    }
11243

    
11244

    
11245
class LUInstanceChangeGroup(LogicalUnit):
11246
  HPATH = "instance-change-group"
11247
  HTYPE = constants.HTYPE_INSTANCE
11248
  REQ_BGL = False
11249

    
11250
  def ExpandNames(self):
11251
    self.share_locks = _ShareAll()
11252
    self.needed_locks = {
11253
      locking.LEVEL_NODEGROUP: [],
11254
      locking.LEVEL_NODE: [],
11255
      }
11256

    
11257
    self._ExpandAndLockInstance()
11258

    
11259
    if self.op.target_groups:
11260
      self.req_target_uuids = map(self.cfg.LookupNodeGroup,
11261
                                  self.op.target_groups)
11262
    else:
11263
      self.req_target_uuids = None
11264

    
11265
    self.op.iallocator = _GetDefaultIAllocator(self.cfg, self.op.iallocator)
11266

    
11267
  def DeclareLocks(self, level):
11268
    if level == locking.LEVEL_NODEGROUP:
11269
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
11270

    
11271
      if self.req_target_uuids:
11272
        lock_groups = set(self.req_target_uuids)
11273

    
11274
        # Lock all groups used by instance optimistically; this requires going
11275
        # via the node before it's locked, requiring verification later on
11276
        instance_groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
11277
        lock_groups.update(instance_groups)
11278
      else:
11279
        # No target groups, need to lock all of them
11280
        lock_groups = locking.ALL_SET
11281

    
11282
      self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
11283

    
11284
    elif level == locking.LEVEL_NODE:
11285
      if self.req_target_uuids:
11286
        # Lock all nodes used by instances
11287
        self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
11288
        self._LockInstancesNodes()
11289

    
11290
        # Lock all nodes in all potential target groups
11291
        lock_groups = (frozenset(self.owned_locks(locking.LEVEL_NODEGROUP)) -
11292
                       self.cfg.GetInstanceNodeGroups(self.op.instance_name))
11293
        member_nodes = [node_name
11294
                        for group in lock_groups
11295
                        for node_name in self.cfg.GetNodeGroup(group).members]
11296
        self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
11297
      else:
11298
        # Lock all nodes as all groups are potential targets
11299
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11300

    
11301
  def CheckPrereq(self):
11302
    owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
11303
    owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
11304
    owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
11305

    
11306
    assert (self.req_target_uuids is None or
11307
            owned_groups.issuperset(self.req_target_uuids))
11308
    assert owned_instances == set([self.op.instance_name])
11309

    
11310
    # Get instance information
11311
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
11312

    
11313
    # Check if node groups for locked instance are still correct
11314
    assert owned_nodes.issuperset(self.instance.all_nodes), \
11315
      ("Instance %s's nodes changed while we kept the lock" %
11316
       self.op.instance_name)
11317

    
11318
    inst_groups = _CheckInstanceNodeGroups(self.cfg, self.op.instance_name,
11319
                                           owned_groups)
11320

    
11321
    if self.req_target_uuids:
11322
      # User requested specific target groups
11323
      self.target_uuids = self.req_target_uuids
11324
    else:
11325
      # All groups except those used by the instance are potential targets
11326
      self.target_uuids = owned_groups - inst_groups
11327

    
11328
    conflicting_groups = self.target_uuids & inst_groups
11329
    if conflicting_groups:
11330
      raise errors.OpPrereqError("Can't use group(s) '%s' as targets, they are"
11331
                                 " used by the instance '%s'" %
11332
                                 (utils.CommaJoin(conflicting_groups),
11333
                                  self.op.instance_name),
11334
                                 errors.ECODE_INVAL)
11335

    
11336
    if not self.target_uuids:
11337
      raise errors.OpPrereqError("There are no possible target groups",
11338
                                 errors.ECODE_INVAL)
11339

    
11340
  def BuildHooksEnv(self):
11341
    """Build hooks env.
11342

11343
    """
11344
    assert self.target_uuids
11345

    
11346
    env = {
11347
      "TARGET_GROUPS": " ".join(self.target_uuids),
11348
      }
11349

    
11350
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
11351

    
11352
    return env
11353

    
11354
  def BuildHooksNodes(self):
11355
    """Build hooks nodes.
11356

11357
    """
11358
    mn = self.cfg.GetMasterNode()
11359
    return ([mn], [mn])
11360

    
11361
  def Exec(self, feedback_fn):
11362
    instances = list(self.owned_locks(locking.LEVEL_INSTANCE))
11363

    
11364
    assert instances == [self.op.instance_name], "Instance not locked"
11365

    
11366
    ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
11367
                     instances=instances, target_groups=list(self.target_uuids))
11368

    
11369
    ial.Run(self.op.iallocator)
11370

    
11371
    if not ial.success:
11372
      raise errors.OpPrereqError("Can't compute solution for changing group of"
11373
                                 " instance '%s' using iallocator '%s': %s" %
11374
                                 (self.op.instance_name, self.op.iallocator,
11375
                                  ial.info),
11376
                                 errors.ECODE_NORES)
11377

    
11378
    jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
11379

    
11380
    self.LogInfo("Iallocator returned %s job(s) for changing group of"
11381
                 " instance '%s'", len(jobs), self.op.instance_name)
11382

    
11383
    return ResultWithJobs(jobs)
11384

    
11385

    
11386
class LUBackupQuery(NoHooksLU):
11387
  """Query the exports list
11388

11389
  """
11390
  REQ_BGL = False
11391

    
11392
  def ExpandNames(self):
11393
    self.needed_locks = {}
11394
    self.share_locks[locking.LEVEL_NODE] = 1
11395
    if not self.op.nodes:
11396
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11397
    else:
11398
      self.needed_locks[locking.LEVEL_NODE] = \
11399
        _GetWantedNodes(self, self.op.nodes)
11400

    
11401
  def Exec(self, feedback_fn):
11402
    """Compute the list of all the exported system images.
11403

11404
    @rtype: dict
11405
    @return: a dictionary with the structure node->(export-list)
11406
        where export-list is a list of the instances exported on
11407
        that node.
11408

11409
    """
11410
    self.nodes = self.owned_locks(locking.LEVEL_NODE)
11411
    rpcresult = self.rpc.call_export_list(self.nodes)
11412
    result = {}
11413
    for node in rpcresult:
11414
      if rpcresult[node].fail_msg:
11415
        result[node] = False
11416
      else:
11417
        result[node] = rpcresult[node].payload
11418

    
11419
    return result
11420

    
11421

    
11422
class LUBackupPrepare(NoHooksLU):
11423
  """Prepares an instance for an export and returns useful information.
11424

11425
  """
11426
  REQ_BGL = False
11427

    
11428
  def ExpandNames(self):
11429
    self._ExpandAndLockInstance()
11430

    
11431
  def CheckPrereq(self):
11432
    """Check prerequisites.
11433

11434
    """
11435
    instance_name = self.op.instance_name
11436

    
11437
    self.instance = self.cfg.GetInstanceInfo(instance_name)
11438
    assert self.instance is not None, \
11439
          "Cannot retrieve locked instance %s" % self.op.instance_name
11440
    _CheckNodeOnline(self, self.instance.primary_node)
11441

    
11442
    self._cds = _GetClusterDomainSecret()
11443

    
11444
  def Exec(self, feedback_fn):
11445
    """Prepares an instance for an export.
11446

11447
    """
11448
    instance = self.instance
11449

    
11450
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
11451
      salt = utils.GenerateSecret(8)
11452

    
11453
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
11454
      result = self.rpc.call_x509_cert_create(instance.primary_node,
11455
                                              constants.RIE_CERT_VALIDITY)
11456
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
11457

    
11458
      (name, cert_pem) = result.payload
11459

    
11460
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
11461
                                             cert_pem)
11462

    
11463
      return {
11464
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
11465
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
11466
                          salt),
11467
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
11468
        }
11469

    
11470
    return None
11471

    
11472

    
11473
class LUBackupExport(LogicalUnit):
11474
  """Export an instance to an image in the cluster.
11475

11476
  """
11477
  HPATH = "instance-export"
11478
  HTYPE = constants.HTYPE_INSTANCE
11479
  REQ_BGL = False
11480

    
11481
  def CheckArguments(self):
11482
    """Check the arguments.
11483

11484
    """
11485
    self.x509_key_name = self.op.x509_key_name
11486
    self.dest_x509_ca_pem = self.op.destination_x509_ca
11487

    
11488
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
11489
      if not self.x509_key_name:
11490
        raise errors.OpPrereqError("Missing X509 key name for encryption",
11491
                                   errors.ECODE_INVAL)
11492

    
11493
      if not self.dest_x509_ca_pem:
11494
        raise errors.OpPrereqError("Missing destination X509 CA",
11495
                                   errors.ECODE_INVAL)
11496

    
11497
  def ExpandNames(self):
11498
    self._ExpandAndLockInstance()
11499

    
11500
    # Lock all nodes for local exports
11501
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11502
      # FIXME: lock only instance primary and destination node
11503
      #
11504
      # Sad but true, for now we have do lock all nodes, as we don't know where
11505
      # the previous export might be, and in this LU we search for it and
11506
      # remove it from its current node. In the future we could fix this by:
11507
      #  - making a tasklet to search (share-lock all), then create the
11508
      #    new one, then one to remove, after
11509
      #  - removing the removal operation altogether
11510
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11511

    
11512
  def DeclareLocks(self, level):
11513
    """Last minute lock declaration."""
11514
    # All nodes are locked anyway, so nothing to do here.
11515

    
11516
  def BuildHooksEnv(self):
11517
    """Build hooks env.
11518

11519
    This will run on the master, primary node and target node.
11520

11521
    """
11522
    env = {
11523
      "EXPORT_MODE": self.op.mode,
11524
      "EXPORT_NODE": self.op.target_node,
11525
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
11526
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
11527
      # TODO: Generic function for boolean env variables
11528
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
11529
      }
11530

    
11531
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
11532

    
11533
    return env
11534

    
11535
  def BuildHooksNodes(self):
11536
    """Build hooks nodes.
11537

11538
    """
11539
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
11540

    
11541
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11542
      nl.append(self.op.target_node)
11543

    
11544
    return (nl, nl)
11545

    
11546
  def CheckPrereq(self):
11547
    """Check prerequisites.
11548

11549
    This checks that the instance and node names are valid.
11550

11551
    """
11552
    instance_name = self.op.instance_name
11553

    
11554
    self.instance = self.cfg.GetInstanceInfo(instance_name)
11555
    assert self.instance is not None, \
11556
          "Cannot retrieve locked instance %s" % self.op.instance_name
11557
    _CheckNodeOnline(self, self.instance.primary_node)
11558

    
11559
    if (self.op.remove_instance and self.instance.admin_up and
11560
        not self.op.shutdown):
11561
      raise errors.OpPrereqError("Can not remove instance without shutting it"
11562
                                 " down before")
11563

    
11564
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11565
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
11566
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
11567
      assert self.dst_node is not None
11568

    
11569
      _CheckNodeOnline(self, self.dst_node.name)
11570
      _CheckNodeNotDrained(self, self.dst_node.name)
11571

    
11572
      self._cds = None
11573
      self.dest_disk_info = None
11574
      self.dest_x509_ca = None
11575

    
11576
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11577
      self.dst_node = None
11578

    
11579
      if len(self.op.target_node) != len(self.instance.disks):
11580
        raise errors.OpPrereqError(("Received destination information for %s"
11581
                                    " disks, but instance %s has %s disks") %
11582
                                   (len(self.op.target_node), instance_name,
11583
                                    len(self.instance.disks)),
11584
                                   errors.ECODE_INVAL)
11585

    
11586
      cds = _GetClusterDomainSecret()
11587

    
11588
      # Check X509 key name
11589
      try:
11590
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
11591
      except (TypeError, ValueError), err:
11592
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
11593

    
11594
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
11595
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
11596
                                   errors.ECODE_INVAL)
11597

    
11598
      # Load and verify CA
11599
      try:
11600
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
11601
      except OpenSSL.crypto.Error, err:
11602
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
11603
                                   (err, ), errors.ECODE_INVAL)
11604

    
11605
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
11606
      if errcode is not None:
11607
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
11608
                                   (msg, ), errors.ECODE_INVAL)
11609

    
11610
      self.dest_x509_ca = cert
11611

    
11612
      # Verify target information
11613
      disk_info = []
11614
      for idx, disk_data in enumerate(self.op.target_node):
11615
        try:
11616
          (host, port, magic) = \
11617
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
11618
        except errors.GenericError, err:
11619
          raise errors.OpPrereqError("Target info for disk %s: %s" %
11620
                                     (idx, err), errors.ECODE_INVAL)
11621

    
11622
        disk_info.append((host, port, magic))
11623

    
11624
      assert len(disk_info) == len(self.op.target_node)
11625
      self.dest_disk_info = disk_info
11626

    
11627
    else:
11628
      raise errors.ProgrammerError("Unhandled export mode %r" %
11629
                                   self.op.mode)
11630

    
11631
    # instance disk type verification
11632
    # TODO: Implement export support for file-based disks
11633
    for disk in self.instance.disks:
11634
      if disk.dev_type == constants.LD_FILE:
11635
        raise errors.OpPrereqError("Export not supported for instances with"
11636
                                   " file-based disks", errors.ECODE_INVAL)
11637

    
11638
  def _CleanupExports(self, feedback_fn):
11639
    """Removes exports of current instance from all other nodes.
11640

11641
    If an instance in a cluster with nodes A..D was exported to node C, its
11642
    exports will be removed from the nodes A, B and D.
11643

11644
    """
11645
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
11646

    
11647
    nodelist = self.cfg.GetNodeList()
11648
    nodelist.remove(self.dst_node.name)
11649

    
11650
    # on one-node clusters nodelist will be empty after the removal
11651
    # if we proceed the backup would be removed because OpBackupQuery
11652
    # substitutes an empty list with the full cluster node list.
11653
    iname = self.instance.name
11654
    if nodelist:
11655
      feedback_fn("Removing old exports for instance %s" % iname)
11656
      exportlist = self.rpc.call_export_list(nodelist)
11657
      for node in exportlist:
11658
        if exportlist[node].fail_msg:
11659
          continue
11660
        if iname in exportlist[node].payload:
11661
          msg = self.rpc.call_export_remove(node, iname).fail_msg
11662
          if msg:
11663
            self.LogWarning("Could not remove older export for instance %s"
11664
                            " on node %s: %s", iname, node, msg)
11665

    
11666
  def Exec(self, feedback_fn):
11667
    """Export an instance to an image in the cluster.
11668

11669
    """
11670
    assert self.op.mode in constants.EXPORT_MODES
11671

    
11672
    instance = self.instance
11673
    src_node = instance.primary_node
11674

    
11675
    if self.op.shutdown:
11676
      # shutdown the instance, but not the disks
11677
      feedback_fn("Shutting down instance %s" % instance.name)
11678
      result = self.rpc.call_instance_shutdown(src_node, instance,
11679
                                               self.op.shutdown_timeout)
11680
      # TODO: Maybe ignore failures if ignore_remove_failures is set
11681
      result.Raise("Could not shutdown instance %s on"
11682
                   " node %s" % (instance.name, src_node))
11683

    
11684
    # set the disks ID correctly since call_instance_start needs the
11685
    # correct drbd minor to create the symlinks
11686
    for disk in instance.disks:
11687
      self.cfg.SetDiskID(disk, src_node)
11688

    
11689
    activate_disks = (not instance.admin_up)
11690

    
11691
    if activate_disks:
11692
      # Activate the instance disks if we'exporting a stopped instance
11693
      feedback_fn("Activating disks for %s" % instance.name)
11694
      _StartInstanceDisks(self, instance, None)
11695

    
11696
    try:
11697
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
11698
                                                     instance)
11699

    
11700
      helper.CreateSnapshots()
11701
      try:
11702
        if (self.op.shutdown and instance.admin_up and
11703
            not self.op.remove_instance):
11704
          assert not activate_disks
11705
          feedback_fn("Starting instance %s" % instance.name)
11706
          result = self.rpc.call_instance_start(src_node, instance,
11707
                                                None, None, False)
11708
          msg = result.fail_msg
11709
          if msg:
11710
            feedback_fn("Failed to start instance: %s" % msg)
11711
            _ShutdownInstanceDisks(self, instance)
11712
            raise errors.OpExecError("Could not start instance: %s" % msg)
11713

    
11714
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
11715
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
11716
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11717
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
11718
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
11719

    
11720
          (key_name, _, _) = self.x509_key_name
11721

    
11722
          dest_ca_pem = \
11723
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
11724
                                            self.dest_x509_ca)
11725

    
11726
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
11727
                                                     key_name, dest_ca_pem,
11728
                                                     timeouts)
11729
      finally:
11730
        helper.Cleanup()
11731

    
11732
      # Check for backwards compatibility
11733
      assert len(dresults) == len(instance.disks)
11734
      assert compat.all(isinstance(i, bool) for i in dresults), \
11735
             "Not all results are boolean: %r" % dresults
11736

    
11737
    finally:
11738
      if activate_disks:
11739
        feedback_fn("Deactivating disks for %s" % instance.name)
11740
        _ShutdownInstanceDisks(self, instance)
11741

    
11742
    if not (compat.all(dresults) and fin_resu):
11743
      failures = []
11744
      if not fin_resu:
11745
        failures.append("export finalization")
11746
      if not compat.all(dresults):
11747
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
11748
                               if not dsk)
11749
        failures.append("disk export: disk(s) %s" % fdsk)
11750

    
11751
      raise errors.OpExecError("Export failed, errors in %s" %
11752
                               utils.CommaJoin(failures))
11753

    
11754
    # At this point, the export was successful, we can cleanup/finish
11755

    
11756
    # Remove instance if requested
11757
    if self.op.remove_instance:
11758
      feedback_fn("Removing instance %s" % instance.name)
11759
      _RemoveInstance(self, feedback_fn, instance,
11760
                      self.op.ignore_remove_failures)
11761

    
11762
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11763
      self._CleanupExports(feedback_fn)
11764

    
11765
    return fin_resu, dresults
11766

    
11767

    
11768
class LUBackupRemove(NoHooksLU):
11769
  """Remove exports related to the named instance.
11770

11771
  """
11772
  REQ_BGL = False
11773

    
11774
  def ExpandNames(self):
11775
    self.needed_locks = {}
11776
    # We need all nodes to be locked in order for RemoveExport to work, but we
11777
    # don't need to lock the instance itself, as nothing will happen to it (and
11778
    # we can remove exports also for a removed instance)
11779
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11780

    
11781
  def Exec(self, feedback_fn):
11782
    """Remove any export.
11783

11784
    """
11785
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11786
    # If the instance was not found we'll try with the name that was passed in.
11787
    # This will only work if it was an FQDN, though.
11788
    fqdn_warn = False
11789
    if not instance_name:
11790
      fqdn_warn = True
11791
      instance_name = self.op.instance_name
11792

    
11793
    locked_nodes = self.owned_locks(locking.LEVEL_NODE)
11794
    exportlist = self.rpc.call_export_list(locked_nodes)
11795
    found = False
11796
    for node in exportlist:
11797
      msg = exportlist[node].fail_msg
11798
      if msg:
11799
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11800
        continue
11801
      if instance_name in exportlist[node].payload:
11802
        found = True
11803
        result = self.rpc.call_export_remove(node, instance_name)
11804
        msg = result.fail_msg
11805
        if msg:
11806
          logging.error("Could not remove export for instance %s"
11807
                        " on node %s: %s", instance_name, node, msg)
11808

    
11809
    if fqdn_warn and not found:
11810
      feedback_fn("Export not found. If trying to remove an export belonging"
11811
                  " to a deleted instance please use its Fully Qualified"
11812
                  " Domain Name.")
11813

    
11814

    
11815
class LUGroupAdd(LogicalUnit):
11816
  """Logical unit for creating node groups.
11817

11818
  """
11819
  HPATH = "group-add"
11820
  HTYPE = constants.HTYPE_GROUP
11821
  REQ_BGL = False
11822

    
11823
  def ExpandNames(self):
11824
    # We need the new group's UUID here so that we can create and acquire the
11825
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11826
    # that it should not check whether the UUID exists in the configuration.
11827
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11828
    self.needed_locks = {}
11829
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11830

    
11831
  def CheckPrereq(self):
11832
    """Check prerequisites.
11833

11834
    This checks that the given group name is not an existing node group
11835
    already.
11836

11837
    """
11838
    try:
11839
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11840
    except errors.OpPrereqError:
11841
      pass
11842
    else:
11843
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11844
                                 " node group (UUID: %s)" %
11845
                                 (self.op.group_name, existing_uuid),
11846
                                 errors.ECODE_EXISTS)
11847

    
11848
    if self.op.ndparams:
11849
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11850

    
11851
  def BuildHooksEnv(self):
11852
    """Build hooks env.
11853

11854
    """
11855
    return {
11856
      "GROUP_NAME": self.op.group_name,
11857
      }
11858

    
11859
  def BuildHooksNodes(self):
11860
    """Build hooks nodes.
11861

11862
    """
11863
    mn = self.cfg.GetMasterNode()
11864
    return ([mn], [mn])
11865

    
11866
  def Exec(self, feedback_fn):
11867
    """Add the node group to the cluster.
11868

11869
    """
11870
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11871
                                  uuid=self.group_uuid,
11872
                                  alloc_policy=self.op.alloc_policy,
11873
                                  ndparams=self.op.ndparams)
11874

    
11875
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11876
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11877

    
11878

    
11879
class LUGroupAssignNodes(NoHooksLU):
11880
  """Logical unit for assigning nodes to groups.
11881

11882
  """
11883
  REQ_BGL = False
11884

    
11885
  def ExpandNames(self):
11886
    # These raise errors.OpPrereqError on their own:
11887
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11888
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11889

    
11890
    # We want to lock all the affected nodes and groups. We have readily
11891
    # available the list of nodes, and the *destination* group. To gather the
11892
    # list of "source" groups, we need to fetch node information later on.
11893
    self.needed_locks = {
11894
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11895
      locking.LEVEL_NODE: self.op.nodes,
11896
      }
11897

    
11898
  def DeclareLocks(self, level):
11899
    if level == locking.LEVEL_NODEGROUP:
11900
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11901

    
11902
      # Try to get all affected nodes' groups without having the group or node
11903
      # lock yet. Needs verification later in the code flow.
11904
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11905

    
11906
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11907

    
11908
  def CheckPrereq(self):
11909
    """Check prerequisites.
11910

11911
    """
11912
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11913
    assert (frozenset(self.owned_locks(locking.LEVEL_NODE)) ==
11914
            frozenset(self.op.nodes))
11915

    
11916
    expected_locks = (set([self.group_uuid]) |
11917
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11918
    actual_locks = self.owned_locks(locking.LEVEL_NODEGROUP)
11919
    if actual_locks != expected_locks:
11920
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11921
                               " current groups are '%s', used to be '%s'" %
11922
                               (utils.CommaJoin(expected_locks),
11923
                                utils.CommaJoin(actual_locks)))
11924

    
11925
    self.node_data = self.cfg.GetAllNodesInfo()
11926
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11927
    instance_data = self.cfg.GetAllInstancesInfo()
11928

    
11929
    if self.group is None:
11930
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11931
                               (self.op.group_name, self.group_uuid))
11932

    
11933
    (new_splits, previous_splits) = \
11934
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11935
                                             for node in self.op.nodes],
11936
                                            self.node_data, instance_data)
11937

    
11938
    if new_splits:
11939
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11940

    
11941
      if not self.op.force:
11942
        raise errors.OpExecError("The following instances get split by this"
11943
                                 " change and --force was not given: %s" %
11944
                                 fmt_new_splits)
11945
      else:
11946
        self.LogWarning("This operation will split the following instances: %s",
11947
                        fmt_new_splits)
11948

    
11949
        if previous_splits:
11950
          self.LogWarning("In addition, these already-split instances continue"
11951
                          " to be split across groups: %s",
11952
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11953

    
11954
  def Exec(self, feedback_fn):
11955
    """Assign nodes to a new group.
11956

11957
    """
11958
    for node in self.op.nodes:
11959
      self.node_data[node].group = self.group_uuid
11960

    
11961
    # FIXME: Depends on side-effects of modifying the result of
11962
    # C{cfg.GetAllNodesInfo}
11963

    
11964
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11965

    
11966
  @staticmethod
11967
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11968
    """Check for split instances after a node assignment.
11969

11970
    This method considers a series of node assignments as an atomic operation,
11971
    and returns information about split instances after applying the set of
11972
    changes.
11973

11974
    In particular, it returns information about newly split instances, and
11975
    instances that were already split, and remain so after the change.
11976

11977
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11978
    considered.
11979

11980
    @type changes: list of (node_name, new_group_uuid) pairs.
11981
    @param changes: list of node assignments to consider.
11982
    @param node_data: a dict with data for all nodes
11983
    @param instance_data: a dict with all instances to consider
11984
    @rtype: a two-tuple
11985
    @return: a list of instances that were previously okay and result split as a
11986
      consequence of this change, and a list of instances that were previously
11987
      split and this change does not fix.
11988

11989
    """
11990
    changed_nodes = dict((node, group) for node, group in changes
11991
                         if node_data[node].group != group)
11992

    
11993
    all_split_instances = set()
11994
    previously_split_instances = set()
11995

    
11996
    def InstanceNodes(instance):
11997
      return [instance.primary_node] + list(instance.secondary_nodes)
11998

    
11999
    for inst in instance_data.values():
12000
      if inst.disk_template not in constants.DTS_INT_MIRROR:
12001
        continue
12002

    
12003
      instance_nodes = InstanceNodes(inst)
12004

    
12005
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
12006
        previously_split_instances.add(inst.name)
12007

    
12008
      if len(set(changed_nodes.get(node, node_data[node].group)
12009
                 for node in instance_nodes)) > 1:
12010
        all_split_instances.add(inst.name)
12011

    
12012
    return (list(all_split_instances - previously_split_instances),
12013
            list(previously_split_instances & all_split_instances))
12014

    
12015

    
12016
class _GroupQuery(_QueryBase):
12017
  FIELDS = query.GROUP_FIELDS
12018

    
12019
  def ExpandNames(self, lu):
12020
    lu.needed_locks = {}
12021

    
12022
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
12023
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
12024

    
12025
    if not self.names:
12026
      self.wanted = [name_to_uuid[name]
12027
                     for name in utils.NiceSort(name_to_uuid.keys())]
12028
    else:
12029
      # Accept names to be either names or UUIDs.
12030
      missing = []
12031
      self.wanted = []
12032
      all_uuid = frozenset(self._all_groups.keys())
12033

    
12034
      for name in self.names:
12035
        if name in all_uuid:
12036
          self.wanted.append(name)
12037
        elif name in name_to_uuid:
12038
          self.wanted.append(name_to_uuid[name])
12039
        else:
12040
          missing.append(name)
12041

    
12042
      if missing:
12043
        raise errors.OpPrereqError("Some groups do not exist: %s" %
12044
                                   utils.CommaJoin(missing),
12045
                                   errors.ECODE_NOENT)
12046

    
12047
  def DeclareLocks(self, lu, level):
12048
    pass
12049

    
12050
  def _GetQueryData(self, lu):
12051
    """Computes the list of node groups and their attributes.
12052

12053
    """
12054
    do_nodes = query.GQ_NODE in self.requested_data
12055
    do_instances = query.GQ_INST in self.requested_data
12056

    
12057
    group_to_nodes = None
12058
    group_to_instances = None
12059

    
12060
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
12061
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
12062
    # latter GetAllInstancesInfo() is not enough, for we have to go through
12063
    # instance->node. Hence, we will need to process nodes even if we only need
12064
    # instance information.
12065
    if do_nodes or do_instances:
12066
      all_nodes = lu.cfg.GetAllNodesInfo()
12067
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
12068
      node_to_group = {}
12069

    
12070
      for node in all_nodes.values():
12071
        if node.group in group_to_nodes:
12072
          group_to_nodes[node.group].append(node.name)
12073
          node_to_group[node.name] = node.group
12074

    
12075
      if do_instances:
12076
        all_instances = lu.cfg.GetAllInstancesInfo()
12077
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
12078

    
12079
        for instance in all_instances.values():
12080
          node = instance.primary_node
12081
          if node in node_to_group:
12082
            group_to_instances[node_to_group[node]].append(instance.name)
12083

    
12084
        if not do_nodes:
12085
          # Do not pass on node information if it was not requested.
12086
          group_to_nodes = None
12087

    
12088
    return query.GroupQueryData([self._all_groups[uuid]
12089
                                 for uuid in self.wanted],
12090
                                group_to_nodes, group_to_instances)
12091

    
12092

    
12093
class LUGroupQuery(NoHooksLU):
12094
  """Logical unit for querying node groups.
12095

12096
  """
12097
  REQ_BGL = False
12098

    
12099
  def CheckArguments(self):
12100
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
12101
                          self.op.output_fields, False)
12102

    
12103
  def ExpandNames(self):
12104
    self.gq.ExpandNames(self)
12105

    
12106
  def DeclareLocks(self, level):
12107
    self.gq.DeclareLocks(self, level)
12108

    
12109
  def Exec(self, feedback_fn):
12110
    return self.gq.OldStyleQuery(self)
12111

    
12112

    
12113
class LUGroupSetParams(LogicalUnit):
12114
  """Modifies the parameters of a node group.
12115

12116
  """
12117
  HPATH = "group-modify"
12118
  HTYPE = constants.HTYPE_GROUP
12119
  REQ_BGL = False
12120

    
12121
  def CheckArguments(self):
12122
    all_changes = [
12123
      self.op.ndparams,
12124
      self.op.alloc_policy,
12125
      ]
12126

    
12127
    if all_changes.count(None) == len(all_changes):
12128
      raise errors.OpPrereqError("Please pass at least one modification",
12129
                                 errors.ECODE_INVAL)
12130

    
12131
  def ExpandNames(self):
12132
    # This raises errors.OpPrereqError on its own:
12133
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12134

    
12135
    self.needed_locks = {
12136
      locking.LEVEL_NODEGROUP: [self.group_uuid],
12137
      }
12138

    
12139
  def CheckPrereq(self):
12140
    """Check prerequisites.
12141

12142
    """
12143
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
12144

    
12145
    if self.group is None:
12146
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
12147
                               (self.op.group_name, self.group_uuid))
12148

    
12149
    if self.op.ndparams:
12150
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
12151
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
12152
      self.new_ndparams = new_ndparams
12153

    
12154
  def BuildHooksEnv(self):
12155
    """Build hooks env.
12156

12157
    """
12158
    return {
12159
      "GROUP_NAME": self.op.group_name,
12160
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
12161
      }
12162

    
12163
  def BuildHooksNodes(self):
12164
    """Build hooks nodes.
12165

12166
    """
12167
    mn = self.cfg.GetMasterNode()
12168
    return ([mn], [mn])
12169

    
12170
  def Exec(self, feedback_fn):
12171
    """Modifies the node group.
12172

12173
    """
12174
    result = []
12175

    
12176
    if self.op.ndparams:
12177
      self.group.ndparams = self.new_ndparams
12178
      result.append(("ndparams", str(self.group.ndparams)))
12179

    
12180
    if self.op.alloc_policy:
12181
      self.group.alloc_policy = self.op.alloc_policy
12182

    
12183
    self.cfg.Update(self.group, feedback_fn)
12184
    return result
12185

    
12186

    
12187
class LUGroupRemove(LogicalUnit):
12188
  HPATH = "group-remove"
12189
  HTYPE = constants.HTYPE_GROUP
12190
  REQ_BGL = False
12191

    
12192
  def ExpandNames(self):
12193
    # This will raises errors.OpPrereqError on its own:
12194
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12195
    self.needed_locks = {
12196
      locking.LEVEL_NODEGROUP: [self.group_uuid],
12197
      }
12198

    
12199
  def CheckPrereq(self):
12200
    """Check prerequisites.
12201

12202
    This checks that the given group name exists as a node group, that is
12203
    empty (i.e., contains no nodes), and that is not the last group of the
12204
    cluster.
12205

12206
    """
12207
    # Verify that the group is empty.
12208
    group_nodes = [node.name
12209
                   for node in self.cfg.GetAllNodesInfo().values()
12210
                   if node.group == self.group_uuid]
12211

    
12212
    if group_nodes:
12213
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
12214
                                 " nodes: %s" %
12215
                                 (self.op.group_name,
12216
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
12217
                                 errors.ECODE_STATE)
12218

    
12219
    # Verify the cluster would not be left group-less.
12220
    if len(self.cfg.GetNodeGroupList()) == 1:
12221
      raise errors.OpPrereqError("Group '%s' is the only group,"
12222
                                 " cannot be removed" %
12223
                                 self.op.group_name,
12224
                                 errors.ECODE_STATE)
12225

    
12226
  def BuildHooksEnv(self):
12227
    """Build hooks env.
12228

12229
    """
12230
    return {
12231
      "GROUP_NAME": self.op.group_name,
12232
      }
12233

    
12234
  def BuildHooksNodes(self):
12235
    """Build hooks nodes.
12236

12237
    """
12238
    mn = self.cfg.GetMasterNode()
12239
    return ([mn], [mn])
12240

    
12241
  def Exec(self, feedback_fn):
12242
    """Remove the node group.
12243

12244
    """
12245
    try:
12246
      self.cfg.RemoveNodeGroup(self.group_uuid)
12247
    except errors.ConfigurationError:
12248
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
12249
                               (self.op.group_name, self.group_uuid))
12250

    
12251
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
12252

    
12253

    
12254
class LUGroupRename(LogicalUnit):
12255
  HPATH = "group-rename"
12256
  HTYPE = constants.HTYPE_GROUP
12257
  REQ_BGL = False
12258

    
12259
  def ExpandNames(self):
12260
    # This raises errors.OpPrereqError on its own:
12261
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12262

    
12263
    self.needed_locks = {
12264
      locking.LEVEL_NODEGROUP: [self.group_uuid],
12265
      }
12266

    
12267
  def CheckPrereq(self):
12268
    """Check prerequisites.
12269

12270
    Ensures requested new name is not yet used.
12271

12272
    """
12273
    try:
12274
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
12275
    except errors.OpPrereqError:
12276
      pass
12277
    else:
12278
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
12279
                                 " node group (UUID: %s)" %
12280
                                 (self.op.new_name, new_name_uuid),
12281
                                 errors.ECODE_EXISTS)
12282

    
12283
  def BuildHooksEnv(self):
12284
    """Build hooks env.
12285

12286
    """
12287
    return {
12288
      "OLD_NAME": self.op.group_name,
12289
      "NEW_NAME": self.op.new_name,
12290
      }
12291

    
12292
  def BuildHooksNodes(self):
12293
    """Build hooks nodes.
12294

12295
    """
12296
    mn = self.cfg.GetMasterNode()
12297

    
12298
    all_nodes = self.cfg.GetAllNodesInfo()
12299
    all_nodes.pop(mn, None)
12300

    
12301
    run_nodes = [mn]
12302
    run_nodes.extend(node.name for node in all_nodes.values()
12303
                     if node.group == self.group_uuid)
12304

    
12305
    return (run_nodes, run_nodes)
12306

    
12307
  def Exec(self, feedback_fn):
12308
    """Rename the node group.
12309

12310
    """
12311
    group = self.cfg.GetNodeGroup(self.group_uuid)
12312

    
12313
    if group is None:
12314
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
12315
                               (self.op.group_name, self.group_uuid))
12316

    
12317
    group.name = self.op.new_name
12318
    self.cfg.Update(group, feedback_fn)
12319

    
12320
    return self.op.new_name
12321

    
12322

    
12323
class LUGroupEvacuate(LogicalUnit):
12324
  HPATH = "group-evacuate"
12325
  HTYPE = constants.HTYPE_GROUP
12326
  REQ_BGL = False
12327

    
12328
  def ExpandNames(self):
12329
    # This raises errors.OpPrereqError on its own:
12330
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12331

    
12332
    if self.op.target_groups:
12333
      self.req_target_uuids = map(self.cfg.LookupNodeGroup,
12334
                                  self.op.target_groups)
12335
    else:
12336
      self.req_target_uuids = []
12337

    
12338
    if self.group_uuid in self.req_target_uuids:
12339
      raise errors.OpPrereqError("Group to be evacuated (%s) can not be used"
12340
                                 " as a target group (targets are %s)" %
12341
                                 (self.group_uuid,
12342
                                  utils.CommaJoin(self.req_target_uuids)),
12343
                                 errors.ECODE_INVAL)
12344

    
12345
    self.op.iallocator = _GetDefaultIAllocator(self.cfg, self.op.iallocator)
12346

    
12347
    self.share_locks = _ShareAll()
12348
    self.needed_locks = {
12349
      locking.LEVEL_INSTANCE: [],
12350
      locking.LEVEL_NODEGROUP: [],
12351
      locking.LEVEL_NODE: [],
12352
      }
12353

    
12354
  def DeclareLocks(self, level):
12355
    if level == locking.LEVEL_INSTANCE:
12356
      assert not self.needed_locks[locking.LEVEL_INSTANCE]
12357

    
12358
      # Lock instances optimistically, needs verification once node and group
12359
      # locks have been acquired
12360
      self.needed_locks[locking.LEVEL_INSTANCE] = \
12361
        self.cfg.GetNodeGroupInstances(self.group_uuid)
12362

    
12363
    elif level == locking.LEVEL_NODEGROUP:
12364
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
12365

    
12366
      if self.req_target_uuids:
12367
        lock_groups = set([self.group_uuid] + self.req_target_uuids)
12368

    
12369
        # Lock all groups used by instances optimistically; this requires going
12370
        # via the node before it's locked, requiring verification later on
12371
        lock_groups.update(group_uuid
12372
                           for instance_name in
12373
                             self.owned_locks(locking.LEVEL_INSTANCE)
12374
                           for group_uuid in
12375
                             self.cfg.GetInstanceNodeGroups(instance_name))
12376
      else:
12377
        # No target groups, need to lock all of them
12378
        lock_groups = locking.ALL_SET
12379

    
12380
      self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
12381

    
12382
    elif level == locking.LEVEL_NODE:
12383
      # This will only lock the nodes in the group to be evacuated which
12384
      # contain actual instances
12385
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
12386
      self._LockInstancesNodes()
12387

    
12388
      # Lock all nodes in group to be evacuated and target groups
12389
      owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
12390
      assert self.group_uuid in owned_groups
12391
      member_nodes = [node_name
12392
                      for group in owned_groups
12393
                      for node_name in self.cfg.GetNodeGroup(group).members]
12394
      self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
12395

    
12396
  def CheckPrereq(self):
12397
    owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
12398
    owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
12399
    owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
12400

    
12401
    assert owned_groups.issuperset(self.req_target_uuids)
12402
    assert self.group_uuid in owned_groups
12403

    
12404
    # Check if locked instances are still correct
12405
    _CheckNodeGroupInstances(self.cfg, self.group_uuid, owned_instances)
12406

    
12407
    # Get instance information
12408
    self.instances = dict(self.cfg.GetMultiInstanceInfo(owned_instances))
12409

    
12410
    # Check if node groups for locked instances are still correct
12411
    for instance_name in owned_instances:
12412
      inst = self.instances[instance_name]
12413
      assert owned_nodes.issuperset(inst.all_nodes), \
12414
        "Instance %s's nodes changed while we kept the lock" % instance_name
12415

    
12416
      inst_groups = _CheckInstanceNodeGroups(self.cfg, instance_name,
12417
                                             owned_groups)
12418

    
12419
      assert self.group_uuid in inst_groups, \
12420
        "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
12421

    
12422
    if self.req_target_uuids:
12423
      # User requested specific target groups
12424
      self.target_uuids = self.req_target_uuids
12425
    else:
12426
      # All groups except the one to be evacuated are potential targets
12427
      self.target_uuids = [group_uuid for group_uuid in owned_groups
12428
                           if group_uuid != self.group_uuid]
12429

    
12430
      if not self.target_uuids:
12431
        raise errors.OpPrereqError("There are no possible target groups",
12432
                                   errors.ECODE_INVAL)
12433

    
12434
  def BuildHooksEnv(self):
12435
    """Build hooks env.
12436

12437
    """
12438
    return {
12439
      "GROUP_NAME": self.op.group_name,
12440
      "TARGET_GROUPS": " ".join(self.target_uuids),
12441
      }
12442

    
12443
  def BuildHooksNodes(self):
12444
    """Build hooks nodes.
12445

12446
    """
12447
    mn = self.cfg.GetMasterNode()
12448

    
12449
    assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
12450

    
12451
    run_nodes = [mn] + self.cfg.GetNodeGroup(self.group_uuid).members
12452

    
12453
    return (run_nodes, run_nodes)
12454

    
12455
  def Exec(self, feedback_fn):
12456
    instances = list(self.owned_locks(locking.LEVEL_INSTANCE))
12457

    
12458
    assert self.group_uuid not in self.target_uuids
12459

    
12460
    ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
12461
                     instances=instances, target_groups=self.target_uuids)
12462

    
12463
    ial.Run(self.op.iallocator)
12464

    
12465
    if not ial.success:
12466
      raise errors.OpPrereqError("Can't compute group evacuation using"
12467
                                 " iallocator '%s': %s" %
12468
                                 (self.op.iallocator, ial.info),
12469
                                 errors.ECODE_NORES)
12470

    
12471
    jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
12472

    
12473
    self.LogInfo("Iallocator returned %s job(s) for evacuating node group %s",
12474
                 len(jobs), self.op.group_name)
12475

    
12476
    return ResultWithJobs(jobs)
12477

    
12478

    
12479
class TagsLU(NoHooksLU): # pylint: disable=W0223
12480
  """Generic tags LU.
12481

12482
  This is an abstract class which is the parent of all the other tags LUs.
12483

12484
  """
12485
  def ExpandNames(self):
12486
    self.group_uuid = None
12487
    self.needed_locks = {}
12488
    if self.op.kind == constants.TAG_NODE:
12489
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
12490
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
12491
    elif self.op.kind == constants.TAG_INSTANCE:
12492
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
12493
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
12494
    elif self.op.kind == constants.TAG_NODEGROUP:
12495
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
12496

    
12497
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
12498
    # not possible to acquire the BGL based on opcode parameters)
12499

    
12500
  def CheckPrereq(self):
12501
    """Check prerequisites.
12502

12503
    """
12504
    if self.op.kind == constants.TAG_CLUSTER:
12505
      self.target = self.cfg.GetClusterInfo()
12506
    elif self.op.kind == constants.TAG_NODE:
12507
      self.target = self.cfg.GetNodeInfo(self.op.name)
12508
    elif self.op.kind == constants.TAG_INSTANCE:
12509
      self.target = self.cfg.GetInstanceInfo(self.op.name)
12510
    elif self.op.kind == constants.TAG_NODEGROUP:
12511
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
12512
    else:
12513
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
12514
                                 str(self.op.kind), errors.ECODE_INVAL)
12515

    
12516

    
12517
class LUTagsGet(TagsLU):
12518
  """Returns the tags of a given object.
12519

12520
  """
12521
  REQ_BGL = False
12522

    
12523
  def ExpandNames(self):
12524
    TagsLU.ExpandNames(self)
12525

    
12526
    # Share locks as this is only a read operation
12527
    self.share_locks = _ShareAll()
12528

    
12529
  def Exec(self, feedback_fn):
12530
    """Returns the tag list.
12531

12532
    """
12533
    return list(self.target.GetTags())
12534

    
12535

    
12536
class LUTagsSearch(NoHooksLU):
12537
  """Searches the tags for a given pattern.
12538

12539
  """
12540
  REQ_BGL = False
12541

    
12542
  def ExpandNames(self):
12543
    self.needed_locks = {}
12544

    
12545
  def CheckPrereq(self):
12546
    """Check prerequisites.
12547

12548
    This checks the pattern passed for validity by compiling it.
12549

12550
    """
12551
    try:
12552
      self.re = re.compile(self.op.pattern)
12553
    except re.error, err:
12554
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
12555
                                 (self.op.pattern, err), errors.ECODE_INVAL)
12556

    
12557
  def Exec(self, feedback_fn):
12558
    """Returns the tag list.
12559

12560
    """
12561
    cfg = self.cfg
12562
    tgts = [("/cluster", cfg.GetClusterInfo())]
12563
    ilist = cfg.GetAllInstancesInfo().values()
12564
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
12565
    nlist = cfg.GetAllNodesInfo().values()
12566
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
12567
    tgts.extend(("/nodegroup/%s" % n.name, n)
12568
                for n in cfg.GetAllNodeGroupsInfo().values())
12569
    results = []
12570
    for path, target in tgts:
12571
      for tag in target.GetTags():
12572
        if self.re.search(tag):
12573
          results.append((path, tag))
12574
    return results
12575

    
12576

    
12577
class LUTagsSet(TagsLU):
12578
  """Sets a tag on a given object.
12579

12580
  """
12581
  REQ_BGL = False
12582

    
12583
  def CheckPrereq(self):
12584
    """Check prerequisites.
12585

12586
    This checks the type and length of the tag name and value.
12587

12588
    """
12589
    TagsLU.CheckPrereq(self)
12590
    for tag in self.op.tags:
12591
      objects.TaggableObject.ValidateTag(tag)
12592

    
12593
  def Exec(self, feedback_fn):
12594
    """Sets the tag.
12595

12596
    """
12597
    try:
12598
      for tag in self.op.tags:
12599
        self.target.AddTag(tag)
12600
    except errors.TagError, err:
12601
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
12602
    self.cfg.Update(self.target, feedback_fn)
12603

    
12604

    
12605
class LUTagsDel(TagsLU):
12606
  """Delete a list of tags from a given object.
12607

12608
  """
12609
  REQ_BGL = False
12610

    
12611
  def CheckPrereq(self):
12612
    """Check prerequisites.
12613

12614
    This checks that we have the given tag.
12615

12616
    """
12617
    TagsLU.CheckPrereq(self)
12618
    for tag in self.op.tags:
12619
      objects.TaggableObject.ValidateTag(tag)
12620
    del_tags = frozenset(self.op.tags)
12621
    cur_tags = self.target.GetTags()
12622

    
12623
    diff_tags = del_tags - cur_tags
12624
    if diff_tags:
12625
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
12626
      raise errors.OpPrereqError("Tag(s) %s not found" %
12627
                                 (utils.CommaJoin(diff_names), ),
12628
                                 errors.ECODE_NOENT)
12629

    
12630
  def Exec(self, feedback_fn):
12631
    """Remove the tag from the object.
12632

12633
    """
12634
    for tag in self.op.tags:
12635
      self.target.RemoveTag(tag)
12636
    self.cfg.Update(self.target, feedback_fn)
12637

    
12638

    
12639
class LUTestDelay(NoHooksLU):
12640
  """Sleep for a specified amount of time.
12641

12642
  This LU sleeps on the master and/or nodes for a specified amount of
12643
  time.
12644

12645
  """
12646
  REQ_BGL = False
12647

    
12648
  def ExpandNames(self):
12649
    """Expand names and set required locks.
12650

12651
    This expands the node list, if any.
12652

12653
    """
12654
    self.needed_locks = {}
12655
    if self.op.on_nodes:
12656
      # _GetWantedNodes can be used here, but is not always appropriate to use
12657
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
12658
      # more information.
12659
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
12660
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
12661

    
12662
  def _TestDelay(self):
12663
    """Do the actual sleep.
12664

12665
    """
12666
    if self.op.on_master:
12667
      if not utils.TestDelay(self.op.duration):
12668
        raise errors.OpExecError("Error during master delay test")
12669
    if self.op.on_nodes:
12670
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
12671
      for node, node_result in result.items():
12672
        node_result.Raise("Failure during rpc call to node %s" % node)
12673

    
12674
  def Exec(self, feedback_fn):
12675
    """Execute the test delay opcode, with the wanted repetitions.
12676

12677
    """
12678
    if self.op.repeat == 0:
12679
      self._TestDelay()
12680
    else:
12681
      top_value = self.op.repeat - 1
12682
      for i in range(self.op.repeat):
12683
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
12684
        self._TestDelay()
12685

    
12686

    
12687
class LUTestJqueue(NoHooksLU):
12688
  """Utility LU to test some aspects of the job queue.
12689

12690
  """
12691
  REQ_BGL = False
12692

    
12693
  # Must be lower than default timeout for WaitForJobChange to see whether it
12694
  # notices changed jobs
12695
  _CLIENT_CONNECT_TIMEOUT = 20.0
12696
  _CLIENT_CONFIRM_TIMEOUT = 60.0
12697

    
12698
  @classmethod
12699
  def _NotifyUsingSocket(cls, cb, errcls):
12700
    """Opens a Unix socket and waits for another program to connect.
12701

12702
    @type cb: callable
12703
    @param cb: Callback to send socket name to client
12704
    @type errcls: class
12705
    @param errcls: Exception class to use for errors
12706

12707
    """
12708
    # Using a temporary directory as there's no easy way to create temporary
12709
    # sockets without writing a custom loop around tempfile.mktemp and
12710
    # socket.bind
12711
    tmpdir = tempfile.mkdtemp()
12712
    try:
12713
      tmpsock = utils.PathJoin(tmpdir, "sock")
12714

    
12715
      logging.debug("Creating temporary socket at %s", tmpsock)
12716
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
12717
      try:
12718
        sock.bind(tmpsock)
12719
        sock.listen(1)
12720

    
12721
        # Send details to client
12722
        cb(tmpsock)
12723

    
12724
        # Wait for client to connect before continuing
12725
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
12726
        try:
12727
          (conn, _) = sock.accept()
12728
        except socket.error, err:
12729
          raise errcls("Client didn't connect in time (%s)" % err)
12730
      finally:
12731
        sock.close()
12732
    finally:
12733
      # Remove as soon as client is connected
12734
      shutil.rmtree(tmpdir)
12735

    
12736
    # Wait for client to close
12737
    try:
12738
      try:
12739
        # pylint: disable=E1101
12740
        # Instance of '_socketobject' has no ... member
12741
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
12742
        conn.recv(1)
12743
      except socket.error, err:
12744
        raise errcls("Client failed to confirm notification (%s)" % err)
12745
    finally:
12746
      conn.close()
12747

    
12748
  def _SendNotification(self, test, arg, sockname):
12749
    """Sends a notification to the client.
12750

12751
    @type test: string
12752
    @param test: Test name
12753
    @param arg: Test argument (depends on test)
12754
    @type sockname: string
12755
    @param sockname: Socket path
12756

12757
    """
12758
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
12759

    
12760
  def _Notify(self, prereq, test, arg):
12761
    """Notifies the client of a test.
12762

12763
    @type prereq: bool
12764
    @param prereq: Whether this is a prereq-phase test
12765
    @type test: string
12766
    @param test: Test name
12767
    @param arg: Test argument (depends on test)
12768

12769
    """
12770
    if prereq:
12771
      errcls = errors.OpPrereqError
12772
    else:
12773
      errcls = errors.OpExecError
12774

    
12775
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
12776
                                                  test, arg),
12777
                                   errcls)
12778

    
12779
  def CheckArguments(self):
12780
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
12781
    self.expandnames_calls = 0
12782

    
12783
  def ExpandNames(self):
12784
    checkargs_calls = getattr(self, "checkargs_calls", 0)
12785
    if checkargs_calls < 1:
12786
      raise errors.ProgrammerError("CheckArguments was not called")
12787

    
12788
    self.expandnames_calls += 1
12789

    
12790
    if self.op.notify_waitlock:
12791
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
12792

    
12793
    self.LogInfo("Expanding names")
12794

    
12795
    # Get lock on master node (just to get a lock, not for a particular reason)
12796
    self.needed_locks = {
12797
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
12798
      }
12799

    
12800
  def Exec(self, feedback_fn):
12801
    if self.expandnames_calls < 1:
12802
      raise errors.ProgrammerError("ExpandNames was not called")
12803

    
12804
    if self.op.notify_exec:
12805
      self._Notify(False, constants.JQT_EXEC, None)
12806

    
12807
    self.LogInfo("Executing")
12808

    
12809
    if self.op.log_messages:
12810
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
12811
      for idx, msg in enumerate(self.op.log_messages):
12812
        self.LogInfo("Sending log message %s", idx + 1)
12813
        feedback_fn(constants.JQT_MSGPREFIX + msg)
12814
        # Report how many test messages have been sent
12815
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
12816

    
12817
    if self.op.fail:
12818
      raise errors.OpExecError("Opcode failure was requested")
12819

    
12820
    return True
12821

    
12822

    
12823
class IAllocator(object):
12824
  """IAllocator framework.
12825

12826
  An IAllocator instance has three sets of attributes:
12827
    - cfg that is needed to query the cluster
12828
    - input data (all members of the _KEYS class attribute are required)
12829
    - four buffer attributes (in|out_data|text), that represent the
12830
      input (to the external script) in text and data structure format,
12831
      and the output from it, again in two formats
12832
    - the result variables from the script (success, info, nodes) for
12833
      easy usage
12834

12835
  """
12836
  # pylint: disable=R0902
12837
  # lots of instance attributes
12838

    
12839
  def __init__(self, cfg, rpc, mode, **kwargs):
12840
    self.cfg = cfg
12841
    self.rpc = rpc
12842
    # init buffer variables
12843
    self.in_text = self.out_text = self.in_data = self.out_data = None
12844
    # init all input fields so that pylint is happy
12845
    self.mode = mode
12846
    self.memory = self.disks = self.disk_template = None
12847
    self.os = self.tags = self.nics = self.vcpus = None
12848
    self.hypervisor = None
12849
    self.relocate_from = None
12850
    self.name = None
12851
    self.instances = None
12852
    self.evac_mode = None
12853
    self.target_groups = []
12854
    # computed fields
12855
    self.required_nodes = None
12856
    # init result fields
12857
    self.success = self.info = self.result = None
12858

    
12859
    try:
12860
      (fn, keydata, self._result_check) = self._MODE_DATA[self.mode]
12861
    except KeyError:
12862
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
12863
                                   " IAllocator" % self.mode)
12864

    
12865
    keyset = [n for (n, _) in keydata]
12866

    
12867
    for key in kwargs:
12868
      if key not in keyset:
12869
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
12870
                                     " IAllocator" % key)
12871
      setattr(self, key, kwargs[key])
12872

    
12873
    for key in keyset:
12874
      if key not in kwargs:
12875
        raise errors.ProgrammerError("Missing input parameter '%s' to"
12876
                                     " IAllocator" % key)
12877
    self._BuildInputData(compat.partial(fn, self), keydata)
12878

    
12879
  def _ComputeClusterData(self):
12880
    """Compute the generic allocator input data.
12881

12882
    This is the data that is independent of the actual operation.
12883

12884
    """
12885
    cfg = self.cfg
12886
    cluster_info = cfg.GetClusterInfo()
12887
    # cluster data
12888
    data = {
12889
      "version": constants.IALLOCATOR_VERSION,
12890
      "cluster_name": cfg.GetClusterName(),
12891
      "cluster_tags": list(cluster_info.GetTags()),
12892
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
12893
      # we don't have job IDs
12894
      }
12895
    ninfo = cfg.GetAllNodesInfo()
12896
    iinfo = cfg.GetAllInstancesInfo().values()
12897
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
12898

    
12899
    # node data
12900
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
12901

    
12902
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
12903
      hypervisor_name = self.hypervisor
12904
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
12905
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
12906
    else:
12907
      hypervisor_name = cluster_info.enabled_hypervisors[0]
12908

    
12909
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
12910
                                        hypervisor_name)
12911
    node_iinfo = \
12912
      self.rpc.call_all_instances_info(node_list,
12913
                                       cluster_info.enabled_hypervisors)
12914

    
12915
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
12916

    
12917
    config_ndata = self._ComputeBasicNodeData(ninfo)
12918
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12919
                                                 i_list, config_ndata)
12920
    assert len(data["nodes"]) == len(ninfo), \
12921
        "Incomplete node data computed"
12922

    
12923
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12924

    
12925
    self.in_data = data
12926

    
12927
  @staticmethod
12928
  def _ComputeNodeGroupData(cfg):
12929
    """Compute node groups data.
12930

12931
    """
12932
    ng = dict((guuid, {
12933
      "name": gdata.name,
12934
      "alloc_policy": gdata.alloc_policy,
12935
      })
12936
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12937

    
12938
    return ng
12939

    
12940
  @staticmethod
12941
  def _ComputeBasicNodeData(node_cfg):
12942
    """Compute global node data.
12943

12944
    @rtype: dict
12945
    @returns: a dict of name: (node dict, node config)
12946

12947
    """
12948
    # fill in static (config-based) values
12949
    node_results = dict((ninfo.name, {
12950
      "tags": list(ninfo.GetTags()),
12951
      "primary_ip": ninfo.primary_ip,
12952
      "secondary_ip": ninfo.secondary_ip,
12953
      "offline": ninfo.offline,
12954
      "drained": ninfo.drained,
12955
      "master_candidate": ninfo.master_candidate,
12956
      "group": ninfo.group,
12957
      "master_capable": ninfo.master_capable,
12958
      "vm_capable": ninfo.vm_capable,
12959
      })
12960
      for ninfo in node_cfg.values())
12961

    
12962
    return node_results
12963

    
12964
  @staticmethod
12965
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
12966
                              node_results):
12967
    """Compute global node data.
12968

12969
    @param node_results: the basic node structures as filled from the config
12970

12971
    """
12972
    # make a copy of the current dict
12973
    node_results = dict(node_results)
12974
    for nname, nresult in node_data.items():
12975
      assert nname in node_results, "Missing basic data for node %s" % nname
12976
      ninfo = node_cfg[nname]
12977

    
12978
      if not (ninfo.offline or ninfo.drained):
12979
        nresult.Raise("Can't get data for node %s" % nname)
12980
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
12981
                                nname)
12982
        remote_info = nresult.payload
12983

    
12984
        for attr in ["memory_total", "memory_free", "memory_dom0",
12985
                     "vg_size", "vg_free", "cpu_total"]:
12986
          if attr not in remote_info:
12987
            raise errors.OpExecError("Node '%s' didn't return attribute"
12988
                                     " '%s'" % (nname, attr))
12989
          if not isinstance(remote_info[attr], int):
12990
            raise errors.OpExecError("Node '%s' returned invalid value"
12991
                                     " for '%s': %s" %
12992
                                     (nname, attr, remote_info[attr]))
12993
        # compute memory used by primary instances
12994
        i_p_mem = i_p_up_mem = 0
12995
        for iinfo, beinfo in i_list:
12996
          if iinfo.primary_node == nname:
12997
            i_p_mem += beinfo[constants.BE_MEMORY]
12998
            if iinfo.name not in node_iinfo[nname].payload:
12999
              i_used_mem = 0
13000
            else:
13001
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]["memory"])
13002
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
13003
            remote_info["memory_free"] -= max(0, i_mem_diff)
13004

    
13005
            if iinfo.admin_up:
13006
              i_p_up_mem += beinfo[constants.BE_MEMORY]
13007

    
13008
        # compute memory used by instances
13009
        pnr_dyn = {
13010
          "total_memory": remote_info["memory_total"],
13011
          "reserved_memory": remote_info["memory_dom0"],
13012
          "free_memory": remote_info["memory_free"],
13013
          "total_disk": remote_info["vg_size"],
13014
          "free_disk": remote_info["vg_free"],
13015
          "total_cpus": remote_info["cpu_total"],
13016
          "i_pri_memory": i_p_mem,
13017
          "i_pri_up_memory": i_p_up_mem,
13018
          }
13019
        pnr_dyn.update(node_results[nname])
13020
        node_results[nname] = pnr_dyn
13021

    
13022
    return node_results
13023

    
13024
  @staticmethod
13025
  def _ComputeInstanceData(cluster_info, i_list):
13026
    """Compute global instance data.
13027

13028
    """
13029
    instance_data = {}
13030
    for iinfo, beinfo in i_list:
13031
      nic_data = []
13032
      for nic in iinfo.nics:
13033
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
13034
        nic_dict = {
13035
          "mac": nic.mac,
13036
          "ip": nic.ip,
13037
          "mode": filled_params[constants.NIC_MODE],
13038
          "link": filled_params[constants.NIC_LINK],
13039
          }
13040
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
13041
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
13042
        nic_data.append(nic_dict)
13043
      pir = {
13044
        "tags": list(iinfo.GetTags()),
13045
        "admin_up": iinfo.admin_up,
13046
        "vcpus": beinfo[constants.BE_VCPUS],
13047
        "memory": beinfo[constants.BE_MEMORY],
13048
        "os": iinfo.os,
13049
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
13050
        "nics": nic_data,
13051
        "disks": [{constants.IDISK_SIZE: dsk.size,
13052
                   constants.IDISK_MODE: dsk.mode}
13053
                  for dsk in iinfo.disks],
13054
        "disk_template": iinfo.disk_template,
13055
        "hypervisor": iinfo.hypervisor,
13056
        }
13057
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
13058
                                                 pir["disks"])
13059
      instance_data[iinfo.name] = pir
13060

    
13061
    return instance_data
13062

    
13063
  def _AddNewInstance(self):
13064
    """Add new instance data to allocator structure.
13065

13066
    This in combination with _AllocatorGetClusterData will create the
13067
    correct structure needed as input for the allocator.
13068

13069
    The checks for the completeness of the opcode must have already been
13070
    done.
13071

13072
    """
13073
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
13074

    
13075
    if self.disk_template in constants.DTS_INT_MIRROR:
13076
      self.required_nodes = 2
13077
    else:
13078
      self.required_nodes = 1
13079

    
13080
    request = {
13081
      "name": self.name,
13082
      "disk_template": self.disk_template,
13083
      "tags": self.tags,
13084
      "os": self.os,
13085
      "vcpus": self.vcpus,
13086
      "memory": self.memory,
13087
      "disks": self.disks,
13088
      "disk_space_total": disk_space,
13089
      "nics": self.nics,
13090
      "required_nodes": self.required_nodes,
13091
      "hypervisor": self.hypervisor,
13092
      }
13093

    
13094
    return request
13095

    
13096
  def _AddRelocateInstance(self):
13097
    """Add relocate instance data to allocator structure.
13098

13099
    This in combination with _IAllocatorGetClusterData will create the
13100
    correct structure needed as input for the allocator.
13101

13102
    The checks for the completeness of the opcode must have already been
13103
    done.
13104

13105
    """
13106
    instance = self.cfg.GetInstanceInfo(self.name)
13107
    if instance is None:
13108
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
13109
                                   " IAllocator" % self.name)
13110

    
13111
    if instance.disk_template not in constants.DTS_MIRRORED:
13112
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
13113
                                 errors.ECODE_INVAL)
13114

    
13115
    if instance.disk_template in constants.DTS_INT_MIRROR and \
13116
        len(instance.secondary_nodes) != 1:
13117
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
13118
                                 errors.ECODE_STATE)
13119

    
13120
    self.required_nodes = 1
13121
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
13122
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
13123

    
13124
    request = {
13125
      "name": self.name,
13126
      "disk_space_total": disk_space,
13127
      "required_nodes": self.required_nodes,
13128
      "relocate_from": self.relocate_from,
13129
      }
13130
    return request
13131

    
13132
  def _AddNodeEvacuate(self):
13133
    """Get data for node-evacuate requests.
13134

13135
    """
13136
    return {
13137
      "instances": self.instances,
13138
      "evac_mode": self.evac_mode,
13139
      }
13140

    
13141
  def _AddChangeGroup(self):
13142
    """Get data for node-evacuate requests.
13143

13144
    """
13145
    return {
13146
      "instances": self.instances,
13147
      "target_groups": self.target_groups,
13148
      }
13149

    
13150
  def _BuildInputData(self, fn, keydata):
13151
    """Build input data structures.
13152

13153
    """
13154
    self._ComputeClusterData()
13155

    
13156
    request = fn()
13157
    request["type"] = self.mode
13158
    for keyname, keytype in keydata:
13159
      if keyname not in request:
13160
        raise errors.ProgrammerError("Request parameter %s is missing" %
13161
                                     keyname)
13162
      val = request[keyname]
13163
      if not keytype(val):
13164
        raise errors.ProgrammerError("Request parameter %s doesn't pass"
13165
                                     " validation, value %s, expected"
13166
                                     " type %s" % (keyname, val, keytype))
13167
    self.in_data["request"] = request
13168

    
13169
    self.in_text = serializer.Dump(self.in_data)
13170

    
13171
  _STRING_LIST = ht.TListOf(ht.TString)
13172
  _JOB_LIST = ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
13173
     # pylint: disable=E1101
13174
     # Class '...' has no 'OP_ID' member
13175
     "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
13176
                          opcodes.OpInstanceMigrate.OP_ID,
13177
                          opcodes.OpInstanceReplaceDisks.OP_ID])
13178
     })))
13179

    
13180
  _NEVAC_MOVED = \
13181
    ht.TListOf(ht.TAnd(ht.TIsLength(3),
13182
                       ht.TItems([ht.TNonEmptyString,
13183
                                  ht.TNonEmptyString,
13184
                                  ht.TListOf(ht.TNonEmptyString),
13185
                                 ])))
13186
  _NEVAC_FAILED = \
13187
    ht.TListOf(ht.TAnd(ht.TIsLength(2),
13188
                       ht.TItems([ht.TNonEmptyString,
13189
                                  ht.TMaybeString,
13190
                                 ])))
13191
  _NEVAC_RESULT = ht.TAnd(ht.TIsLength(3),
13192
                          ht.TItems([_NEVAC_MOVED, _NEVAC_FAILED, _JOB_LIST]))
13193

    
13194
  _MODE_DATA = {
13195
    constants.IALLOCATOR_MODE_ALLOC:
13196
      (_AddNewInstance,
13197
       [
13198
        ("name", ht.TString),
13199
        ("memory", ht.TInt),
13200
        ("disks", ht.TListOf(ht.TDict)),
13201
        ("disk_template", ht.TString),
13202
        ("os", ht.TString),
13203
        ("tags", _STRING_LIST),
13204
        ("nics", ht.TListOf(ht.TDict)),
13205
        ("vcpus", ht.TInt),
13206
        ("hypervisor", ht.TString),
13207
        ], ht.TList),
13208
    constants.IALLOCATOR_MODE_RELOC:
13209
      (_AddRelocateInstance,
13210
       [("name", ht.TString), ("relocate_from", _STRING_LIST)],
13211
       ht.TList),
13212
     constants.IALLOCATOR_MODE_NODE_EVAC:
13213
      (_AddNodeEvacuate, [
13214
        ("instances", _STRING_LIST),
13215
        ("evac_mode", ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)),
13216
        ], _NEVAC_RESULT),
13217
     constants.IALLOCATOR_MODE_CHG_GROUP:
13218
      (_AddChangeGroup, [
13219
        ("instances", _STRING_LIST),
13220
        ("target_groups", _STRING_LIST),
13221
        ], _NEVAC_RESULT),
13222
    }
13223

    
13224
  def Run(self, name, validate=True, call_fn=None):
13225
    """Run an instance allocator and return the results.
13226

13227
    """
13228
    if call_fn is None:
13229
      call_fn = self.rpc.call_iallocator_runner
13230

    
13231
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
13232
    result.Raise("Failure while running the iallocator script")
13233

    
13234
    self.out_text = result.payload
13235
    if validate:
13236
      self._ValidateResult()
13237

    
13238
  def _ValidateResult(self):
13239
    """Process the allocator results.
13240

13241
    This will process and if successful save the result in
13242
    self.out_data and the other parameters.
13243

13244
    """
13245
    try:
13246
      rdict = serializer.Load(self.out_text)
13247
    except Exception, err:
13248
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
13249

    
13250
    if not isinstance(rdict, dict):
13251
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
13252

    
13253
    # TODO: remove backwards compatiblity in later versions
13254
    if "nodes" in rdict and "result" not in rdict:
13255
      rdict["result"] = rdict["nodes"]
13256
      del rdict["nodes"]
13257

    
13258
    for key in "success", "info", "result":
13259
      if key not in rdict:
13260
        raise errors.OpExecError("Can't parse iallocator results:"
13261
                                 " missing key '%s'" % key)
13262
      setattr(self, key, rdict[key])
13263

    
13264
    if not self._result_check(self.result):
13265
      raise errors.OpExecError("Iallocator returned invalid result,"
13266
                               " expected %s, got %s" %
13267
                               (self._result_check, self.result),
13268
                               errors.ECODE_INVAL)
13269

    
13270
    if self.mode == constants.IALLOCATOR_MODE_RELOC:
13271
      assert self.relocate_from is not None
13272
      assert self.required_nodes == 1
13273

    
13274
      node2group = dict((name, ndata["group"])
13275
                        for (name, ndata) in self.in_data["nodes"].items())
13276

    
13277
      fn = compat.partial(self._NodesToGroups, node2group,
13278
                          self.in_data["nodegroups"])
13279

    
13280
      instance = self.cfg.GetInstanceInfo(self.name)
13281
      request_groups = fn(self.relocate_from + [instance.primary_node])
13282
      result_groups = fn(rdict["result"] + [instance.primary_node])
13283

    
13284
      if self.success and not set(result_groups).issubset(request_groups):
13285
        raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
13286
                                 " differ from original groups (%s)" %
13287
                                 (utils.CommaJoin(result_groups),
13288
                                  utils.CommaJoin(request_groups)))
13289

    
13290
    elif self.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
13291
      assert self.evac_mode in constants.IALLOCATOR_NEVAC_MODES
13292

    
13293
    self.out_data = rdict
13294

    
13295
  @staticmethod
13296
  def _NodesToGroups(node2group, groups, nodes):
13297
    """Returns a list of unique group names for a list of nodes.
13298

13299
    @type node2group: dict
13300
    @param node2group: Map from node name to group UUID
13301
    @type groups: dict
13302
    @param groups: Group information
13303
    @type nodes: list
13304
    @param nodes: Node names
13305

13306
    """
13307
    result = set()
13308

    
13309
    for node in nodes:
13310
      try:
13311
        group_uuid = node2group[node]
13312
      except KeyError:
13313
        # Ignore unknown node
13314
        pass
13315
      else:
13316
        try:
13317
          group = groups[group_uuid]
13318
        except KeyError:
13319
          # Can't find group, let's use UUID
13320
          group_name = group_uuid
13321
        else:
13322
          group_name = group["name"]
13323

    
13324
        result.add(group_name)
13325

    
13326
    return sorted(result)
13327

    
13328

    
13329
class LUTestAllocator(NoHooksLU):
13330
  """Run allocator tests.
13331

13332
  This LU runs the allocator tests
13333

13334
  """
13335
  def CheckPrereq(self):
13336
    """Check prerequisites.
13337

13338
    This checks the opcode parameters depending on the director and mode test.
13339

13340
    """
13341
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
13342
      for attr in ["memory", "disks", "disk_template",
13343
                   "os", "tags", "nics", "vcpus"]:
13344
        if not hasattr(self.op, attr):
13345
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
13346
                                     attr, errors.ECODE_INVAL)
13347
      iname = self.cfg.ExpandInstanceName(self.op.name)
13348
      if iname is not None:
13349
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
13350
                                   iname, errors.ECODE_EXISTS)
13351
      if not isinstance(self.op.nics, list):
13352
        raise errors.OpPrereqError("Invalid parameter 'nics'",
13353
                                   errors.ECODE_INVAL)
13354
      if not isinstance(self.op.disks, list):
13355
        raise errors.OpPrereqError("Invalid parameter 'disks'",
13356
                                   errors.ECODE_INVAL)
13357
      for row in self.op.disks:
13358
        if (not isinstance(row, dict) or
13359
            constants.IDISK_SIZE not in row or
13360
            not isinstance(row[constants.IDISK_SIZE], int) or
13361
            constants.IDISK_MODE not in row or
13362
            row[constants.IDISK_MODE] not in constants.DISK_ACCESS_SET):
13363
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
13364
                                     " parameter", errors.ECODE_INVAL)
13365
      if self.op.hypervisor is None:
13366
        self.op.hypervisor = self.cfg.GetHypervisorType()
13367
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
13368
      fname = _ExpandInstanceName(self.cfg, self.op.name)
13369
      self.op.name = fname
13370
      self.relocate_from = \
13371
          list(self.cfg.GetInstanceInfo(fname).secondary_nodes)
13372
    elif self.op.mode in (constants.IALLOCATOR_MODE_CHG_GROUP,
13373
                          constants.IALLOCATOR_MODE_NODE_EVAC):
13374
      if not self.op.instances:
13375
        raise errors.OpPrereqError("Missing instances", errors.ECODE_INVAL)
13376
      self.op.instances = _GetWantedInstances(self, self.op.instances)
13377
    else:
13378
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
13379
                                 self.op.mode, errors.ECODE_INVAL)
13380

    
13381
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
13382
      if self.op.allocator is None:
13383
        raise errors.OpPrereqError("Missing allocator name",
13384
                                   errors.ECODE_INVAL)
13385
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
13386
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
13387
                                 self.op.direction, errors.ECODE_INVAL)
13388

    
13389
  def Exec(self, feedback_fn):
13390
    """Run the allocator test.
13391

13392
    """
13393
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
13394
      ial = IAllocator(self.cfg, self.rpc,
13395
                       mode=self.op.mode,
13396
                       name=self.op.name,
13397
                       memory=self.op.memory,
13398
                       disks=self.op.disks,
13399
                       disk_template=self.op.disk_template,
13400
                       os=self.op.os,
13401
                       tags=self.op.tags,
13402
                       nics=self.op.nics,
13403
                       vcpus=self.op.vcpus,
13404
                       hypervisor=self.op.hypervisor,
13405
                       )
13406
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
13407
      ial = IAllocator(self.cfg, self.rpc,
13408
                       mode=self.op.mode,
13409
                       name=self.op.name,
13410
                       relocate_from=list(self.relocate_from),
13411
                       )
13412
    elif self.op.mode == constants.IALLOCATOR_MODE_CHG_GROUP:
13413
      ial = IAllocator(self.cfg, self.rpc,
13414
                       mode=self.op.mode,
13415
                       instances=self.op.instances,
13416
                       target_groups=self.op.target_groups)
13417
    elif self.op.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
13418
      ial = IAllocator(self.cfg, self.rpc,
13419
                       mode=self.op.mode,
13420
                       instances=self.op.instances,
13421
                       evac_mode=self.op.evac_mode)
13422
    else:
13423
      raise errors.ProgrammerError("Uncatched mode %s in"
13424
                                   " LUTestAllocator.Exec", self.op.mode)
13425

    
13426
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
13427
      result = ial.in_text
13428
    else:
13429
      ial.Run(self.op.allocator, validate=False)
13430
      result = ial.out_text
13431
    return result
13432

    
13433

    
13434
#: Query type implementations
13435
_QUERY_IMPL = {
13436
  constants.QR_INSTANCE: _InstanceQuery,
13437
  constants.QR_NODE: _NodeQuery,
13438
  constants.QR_GROUP: _GroupQuery,
13439
  constants.QR_OS: _OsQuery,
13440
  }
13441

    
13442
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
13443

    
13444

    
13445
def _GetQueryImplementation(name):
13446
  """Returns the implemtnation for a query type.
13447

13448
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
13449

13450
  """
13451
  try:
13452
    return _QUERY_IMPL[name]
13453
  except KeyError:
13454
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
13455
                               errors.ECODE_INVAL)