Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 0ba177e2

History | View | Annotate | Download (507.7 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 too 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
from ganeti import rpc
63

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

    
66

    
67
#: Size of DRBD meta block device
68
DRBD_META_SIZE = 128
69

    
70
# States of instance
71
INSTANCE_UP = [constants.ADMINST_UP]
72
INSTANCE_DOWN = [constants.ADMINST_DOWN]
73
INSTANCE_OFFLINE = [constants.ADMINST_OFFLINE]
74
INSTANCE_ONLINE = [constants.ADMINST_DOWN, constants.ADMINST_UP]
75
INSTANCE_NOT_RUNNING = [constants.ADMINST_DOWN, constants.ADMINST_OFFLINE]
76

    
77

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

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

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

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

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

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

    
99

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

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

113
  Note that all commands require root permissions.
114

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

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

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

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

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

    
157
    # Tasklets
158
    self.tasklets = None
159

    
160
    # Validate opcode parameters and set defaults
161
    self.op.Validate(True)
162

    
163
    self.CheckArguments()
164

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

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

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

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

180
    """
181
    pass
182

    
183
  def ExpandNames(self):
184
    """Expand names for this LU.
185

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

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

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

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

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

208
    Examples::
209

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

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

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

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

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

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

247
    """
248

    
249
  def CheckPrereq(self):
250
    """Check prerequisites for this LU.
251

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

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

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

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

    
272
  def Exec(self, feedback_fn):
273
    """Execute the LU.
274

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

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

    
287
  def BuildHooksEnv(self):
288
    """Build hooks environment for this LU.
289

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

299
    """
300
    raise NotImplementedError
301

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

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

313
    """
314
    raise NotImplementedError
315

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

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

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

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

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

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

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

    
359
  def _LockInstancesNodes(self, primary_only=False,
360
                          level=locking.LEVEL_NODE):
361
    """Helper function to declare instances' nodes for locking.
362

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

368
    It should be called from DeclareLocks, and for safety only works if
369
    self.recalculate_locks[locking.LEVEL_NODE] is set.
370

371
    In the future it may grow parameters to just lock some instance's nodes, or
372
    to just lock primaries or secondary nodes, if needed.
373

374
    If should be called in DeclareLocks in a way similar to::
375

376
      if level == locking.LEVEL_NODE:
377
        self._LockInstancesNodes()
378

379
    @type primary_only: boolean
380
    @param primary_only: only lock primary nodes of locked instances
381
    @param level: Which lock level to use for locking nodes
382

383
    """
384
    assert level in self.recalculate_locks, \
385
      "_LockInstancesNodes helper function called with no nodes to recalculate"
386

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

    
389
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
390
    # future we might want to have different behaviors depending on the value
391
    # of self.recalculate_locks[locking.LEVEL_NODE]
392
    wanted_nodes = []
393
    locked_i = self.owned_locks(locking.LEVEL_INSTANCE)
394
    for _, instance in self.cfg.GetMultiInstanceInfo(locked_i):
395
      wanted_nodes.append(instance.primary_node)
396
      if not primary_only:
397
        wanted_nodes.extend(instance.secondary_nodes)
398

    
399
    if self.recalculate_locks[level] == constants.LOCKS_REPLACE:
400
      self.needed_locks[level] = wanted_nodes
401
    elif self.recalculate_locks[level] == constants.LOCKS_APPEND:
402
      self.needed_locks[level].extend(wanted_nodes)
403
    else:
404
      raise errors.ProgrammerError("Unknown recalculation mode")
405

    
406
    del self.recalculate_locks[level]
407

    
408

    
409
class NoHooksLU(LogicalUnit): # pylint: disable=W0223
410
  """Simple LU which runs no hooks.
411

412
  This LU is intended as a parent for other LogicalUnits which will
413
  run no hooks, in order to reduce duplicate code.
414

415
  """
416
  HPATH = None
417
  HTYPE = None
418

    
419
  def BuildHooksEnv(self):
420
    """Empty BuildHooksEnv for NoHooksLu.
421

422
    This just raises an error.
423

424
    """
425
    raise AssertionError("BuildHooksEnv called for NoHooksLUs")
426

    
427
  def BuildHooksNodes(self):
428
    """Empty BuildHooksNodes for NoHooksLU.
429

430
    """
431
    raise AssertionError("BuildHooksNodes called for NoHooksLU")
432

    
433

    
434
class Tasklet:
435
  """Tasklet base class.
436

437
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
438
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
439
  tasklets know nothing about locks.
440

441
  Subclasses must follow these rules:
442
    - Implement CheckPrereq
443
    - Implement Exec
444

445
  """
446
  def __init__(self, lu):
447
    self.lu = lu
448

    
449
    # Shortcuts
450
    self.cfg = lu.cfg
451
    self.rpc = lu.rpc
452

    
453
  def CheckPrereq(self):
454
    """Check prerequisites for this tasklets.
455

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

460
    The method should raise errors.OpPrereqError in case something is not
461
    fulfilled. Its return value is ignored.
462

463
    This method should also update all parameters to their canonical form if it
464
    hasn't been done before.
465

466
    """
467
    pass
468

    
469
  def Exec(self, feedback_fn):
470
    """Execute the tasklet.
471

472
    This method should implement the actual work. It should raise
473
    errors.OpExecError for failures that are somewhat dealt with in code, or
474
    expected.
475

476
    """
477
    raise NotImplementedError
478

    
479

    
480
class _QueryBase:
481
  """Base for query utility classes.
482

483
  """
484
  #: Attribute holding field definitions
485
  FIELDS = None
486

    
487
  def __init__(self, qfilter, fields, use_locking):
488
    """Initializes this class.
489

490
    """
491
    self.use_locking = use_locking
492

    
493
    self.query = query.Query(self.FIELDS, fields, qfilter=qfilter,
494
                             namefield="name")
495
    self.requested_data = self.query.RequestedData()
496
    self.names = self.query.RequestedNames()
497

    
498
    # Sort only if no names were requested
499
    self.sort_by_name = not self.names
500

    
501
    self.do_locking = None
502
    self.wanted = None
503

    
504
  def _GetNames(self, lu, all_names, lock_level):
505
    """Helper function to determine names asked for in the query.
506

507
    """
508
    if self.do_locking:
509
      names = lu.owned_locks(lock_level)
510
    else:
511
      names = all_names
512

    
513
    if self.wanted == locking.ALL_SET:
514
      assert not self.names
515
      # caller didn't specify names, so ordering is not important
516
      return utils.NiceSort(names)
517

    
518
    # caller specified names and we must keep the same order
519
    assert self.names
520
    assert not self.do_locking or lu.glm.is_owned(lock_level)
521

    
522
    missing = set(self.wanted).difference(names)
523
    if missing:
524
      raise errors.OpExecError("Some items were removed before retrieving"
525
                               " their data: %s" % missing)
526

    
527
    # Return expanded names
528
    return self.wanted
529

    
530
  def ExpandNames(self, lu):
531
    """Expand names for this query.
532

533
    See L{LogicalUnit.ExpandNames}.
534

535
    """
536
    raise NotImplementedError()
537

    
538
  def DeclareLocks(self, lu, level):
539
    """Declare locks for this query.
540

541
    See L{LogicalUnit.DeclareLocks}.
542

543
    """
544
    raise NotImplementedError()
545

    
546
  def _GetQueryData(self, lu):
547
    """Collects all data for this query.
548

549
    @return: Query data object
550

551
    """
552
    raise NotImplementedError()
553

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

557
    """
558
    return query.GetQueryResponse(self.query, self._GetQueryData(lu),
559
                                  sort_by_name=self.sort_by_name)
560

    
561
  def OldStyleQuery(self, lu):
562
    """Collect data and execute query.
563

564
    """
565
    return self.query.OldStyleQuery(self._GetQueryData(lu),
566
                                    sort_by_name=self.sort_by_name)
567

    
568

    
569
def _ShareAll():
570
  """Returns a dict declaring all lock levels shared.
571

572
  """
573
  return dict.fromkeys(locking.LEVELS, 1)
574

    
575

    
576
def _MakeLegacyNodeInfo(data):
577
  """Formats the data returned by L{rpc.RpcRunner.call_node_info}.
578

579
  Converts the data into a single dictionary. This is fine for most use cases,
580
  but some require information from more than one volume group or hypervisor.
581

582
  """
583
  (bootid, (vg_info, ), (hv_info, )) = data
584

    
585
  return utils.JoinDisjointDicts(utils.JoinDisjointDicts(vg_info, hv_info), {
586
    "bootid": bootid,
587
    })
588

    
589

    
590
def _CheckInstanceNodeGroups(cfg, instance_name, owned_groups):
591
  """Checks if the owned node groups are still correct for an instance.
592

593
  @type cfg: L{config.ConfigWriter}
594
  @param cfg: The cluster configuration
595
  @type instance_name: string
596
  @param instance_name: Instance name
597
  @type owned_groups: set or frozenset
598
  @param owned_groups: List of currently owned node groups
599

600
  """
601
  inst_groups = cfg.GetInstanceNodeGroups(instance_name)
602

    
603
  if not owned_groups.issuperset(inst_groups):
604
    raise errors.OpPrereqError("Instance %s's node groups changed since"
605
                               " locks were acquired, current groups are"
606
                               " are '%s', owning groups '%s'; retry the"
607
                               " operation" %
608
                               (instance_name,
609
                                utils.CommaJoin(inst_groups),
610
                                utils.CommaJoin(owned_groups)),
611
                               errors.ECODE_STATE)
612

    
613
  return inst_groups
614

    
615

    
616
def _CheckNodeGroupInstances(cfg, group_uuid, owned_instances):
617
  """Checks if the instances in a node group are still correct.
618

619
  @type cfg: L{config.ConfigWriter}
620
  @param cfg: The cluster configuration
621
  @type group_uuid: string
622
  @param group_uuid: Node group UUID
623
  @type owned_instances: set or frozenset
624
  @param owned_instances: List of currently owned instances
625

626
  """
627
  wanted_instances = cfg.GetNodeGroupInstances(group_uuid)
628
  if owned_instances != wanted_instances:
629
    raise errors.OpPrereqError("Instances in node group '%s' changed since"
630
                               " locks were acquired, wanted '%s', have '%s';"
631
                               " retry the operation" %
632
                               (group_uuid,
633
                                utils.CommaJoin(wanted_instances),
634
                                utils.CommaJoin(owned_instances)),
635
                               errors.ECODE_STATE)
636

    
637
  return wanted_instances
638

    
639

    
640
def _SupportsOob(cfg, node):
641
  """Tells if node supports OOB.
642

643
  @type cfg: L{config.ConfigWriter}
644
  @param cfg: The cluster configuration
645
  @type node: L{objects.Node}
646
  @param node: The node
647
  @return: The OOB script if supported or an empty string otherwise
648

649
  """
650
  return cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM]
651

    
652

    
653
def _GetWantedNodes(lu, nodes):
654
  """Returns list of checked and expanded node names.
655

656
  @type lu: L{LogicalUnit}
657
  @param lu: the logical unit on whose behalf we execute
658
  @type nodes: list
659
  @param nodes: list of node names or None for all nodes
660
  @rtype: list
661
  @return: the list of nodes, sorted
662
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
663

664
  """
665
  if nodes:
666
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
667

    
668
  return utils.NiceSort(lu.cfg.GetNodeList())
669

    
670

    
671
def _GetWantedInstances(lu, instances):
672
  """Returns list of checked and expanded instance names.
673

674
  @type lu: L{LogicalUnit}
675
  @param lu: the logical unit on whose behalf we execute
676
  @type instances: list
677
  @param instances: list of instance names or None for all instances
678
  @rtype: list
679
  @return: the list of instances, sorted
680
  @raise errors.OpPrereqError: if the instances parameter is wrong type
681
  @raise errors.OpPrereqError: if any of the passed instances is not found
682

683
  """
684
  if instances:
685
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
686
  else:
687
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
688
  return wanted
689

    
690

    
691
def _GetUpdatedParams(old_params, update_dict,
692
                      use_default=True, use_none=False):
693
  """Return the new version of a parameter dictionary.
694

695
  @type old_params: dict
696
  @param old_params: old parameters
697
  @type update_dict: dict
698
  @param update_dict: dict containing new parameter values, or
699
      constants.VALUE_DEFAULT to reset the parameter to its default
700
      value
701
  @param use_default: boolean
702
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
703
      values as 'to be deleted' values
704
  @param use_none: boolean
705
  @type use_none: whether to recognise C{None} values as 'to be
706
      deleted' values
707
  @rtype: dict
708
  @return: the new parameter dictionary
709

710
  """
711
  params_copy = copy.deepcopy(old_params)
712
  for key, val in update_dict.iteritems():
713
    if ((use_default and val == constants.VALUE_DEFAULT) or
714
        (use_none and val is None)):
715
      try:
716
        del params_copy[key]
717
      except KeyError:
718
        pass
719
    else:
720
      params_copy[key] = val
721
  return params_copy
722

    
723

    
724
def _UpdateAndVerifySubDict(base, updates, type_check):
725
  """Updates and verifies a dict with sub dicts of the same type.
726

727
  @param base: The dict with the old data
728
  @param updates: The dict with the new data
729
  @param type_check: Dict suitable to ForceDictType to verify correct types
730
  @returns: A new dict with updated and verified values
731

732
  """
733
  def fn(old, value):
734
    new = _GetUpdatedParams(old, value)
735
    utils.ForceDictType(new, type_check)
736
    return new
737

    
738
  ret = copy.deepcopy(base)
739
  ret.update(dict((key, fn(base.get(key, {}), value))
740
                  for key, value in updates.items()))
741
  return ret
742

    
743

    
744
def _MergeAndVerifyHvState(op_input, obj_input):
745
  """Combines the hv state from an opcode with the one of the object
746

747
  @param op_input: The input dict from the opcode
748
  @param obj_input: The input dict from the objects
749
  @return: The verified and updated dict
750

751
  """
752
  if op_input:
753
    invalid_hvs = set(op_input) - constants.HYPER_TYPES
754
    if invalid_hvs:
755
      raise errors.OpPrereqError("Invalid hypervisor(s) in hypervisor state:"
756
                                 " %s" % utils.CommaJoin(invalid_hvs),
757
                                 errors.ECODE_INVAL)
758
    if obj_input is None:
759
      obj_input = {}
760
    type_check = constants.HVSTS_PARAMETER_TYPES
761
    return _UpdateAndVerifySubDict(obj_input, op_input, type_check)
762

    
763
  return None
764

    
765

    
766
def _MergeAndVerifyDiskState(op_input, obj_input):
767
  """Combines the disk state from an opcode with the one of the object
768

769
  @param op_input: The input dict from the opcode
770
  @param obj_input: The input dict from the objects
771
  @return: The verified and updated dict
772
  """
773
  if op_input:
774
    invalid_dst = set(op_input) - constants.DS_VALID_TYPES
775
    if invalid_dst:
776
      raise errors.OpPrereqError("Invalid storage type(s) in disk state: %s" %
777
                                 utils.CommaJoin(invalid_dst),
778
                                 errors.ECODE_INVAL)
779
    type_check = constants.DSS_PARAMETER_TYPES
780
    if obj_input is None:
781
      obj_input = {}
782
    return dict((key, _UpdateAndVerifySubDict(obj_input.get(key, {}), value,
783
                                              type_check))
784
                for key, value in op_input.items())
785

    
786
  return None
787

    
788

    
789
def _ReleaseLocks(lu, level, names=None, keep=None):
790
  """Releases locks owned by an LU.
791

792
  @type lu: L{LogicalUnit}
793
  @param level: Lock level
794
  @type names: list or None
795
  @param names: Names of locks to release
796
  @type keep: list or None
797
  @param keep: Names of locks to retain
798

799
  """
800
  assert not (keep is not None and names is not None), \
801
         "Only one of the 'names' and the 'keep' parameters can be given"
802

    
803
  if names is not None:
804
    should_release = names.__contains__
805
  elif keep:
806
    should_release = lambda name: name not in keep
807
  else:
808
    should_release = None
809

    
810
  owned = lu.owned_locks(level)
811
  if not owned:
812
    # Not owning any lock at this level, do nothing
813
    pass
814

    
815
  elif should_release:
816
    retain = []
817
    release = []
818

    
819
    # Determine which locks to release
820
    for name in owned:
821
      if should_release(name):
822
        release.append(name)
823
      else:
824
        retain.append(name)
825

    
826
    assert len(lu.owned_locks(level)) == (len(retain) + len(release))
827

    
828
    # Release just some locks
829
    lu.glm.release(level, names=release)
830

    
831
    assert frozenset(lu.owned_locks(level)) == frozenset(retain)
832
  else:
833
    # Release everything
834
    lu.glm.release(level)
835

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

    
838

    
839
def _MapInstanceDisksToNodes(instances):
840
  """Creates a map from (node, volume) to instance name.
841

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

845
  """
846
  return dict(((node, vol), inst.name)
847
              for inst in instances
848
              for (node, vols) in inst.MapLVsByNode().items()
849
              for vol in vols)
850

    
851

    
852
def _RunPostHook(lu, node_name):
853
  """Runs the post-hook for an opcode on a single node.
854

855
  """
856
  hm = lu.proc.BuildHooksManager(lu)
857
  try:
858
    hm.RunPhase(constants.HOOKS_PHASE_POST, nodes=[node_name])
859
  except:
860
    # pylint: disable=W0702
861
    lu.LogWarning("Errors occurred running hooks on %s" % node_name)
862

    
863

    
864
def _CheckOutputFields(static, dynamic, selected):
865
  """Checks whether all selected fields are valid.
866

867
  @type static: L{utils.FieldSet}
868
  @param static: static fields set
869
  @type dynamic: L{utils.FieldSet}
870
  @param dynamic: dynamic fields set
871

872
  """
873
  f = utils.FieldSet()
874
  f.Extend(static)
875
  f.Extend(dynamic)
876

    
877
  delta = f.NonMatching(selected)
878
  if delta:
879
    raise errors.OpPrereqError("Unknown output fields selected: %s"
880
                               % ",".join(delta), errors.ECODE_INVAL)
881

    
882

    
883
def _CheckGlobalHvParams(params):
884
  """Validates that given hypervisor params are not global ones.
885

886
  This will ensure that instances don't get customised versions of
887
  global params.
888

889
  """
890
  used_globals = constants.HVC_GLOBALS.intersection(params)
891
  if used_globals:
892
    msg = ("The following hypervisor parameters are global and cannot"
893
           " be customized at instance level, please modify them at"
894
           " cluster level: %s" % utils.CommaJoin(used_globals))
895
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
896

    
897

    
898
def _CheckNodeOnline(lu, node, msg=None):
899
  """Ensure that a given node is online.
900

901
  @param lu: the LU on behalf of which we make the check
902
  @param node: the node to check
903
  @param msg: if passed, should be a message to replace the default one
904
  @raise errors.OpPrereqError: if the node is offline
905

906
  """
907
  if msg is None:
908
    msg = "Can't use offline node"
909
  if lu.cfg.GetNodeInfo(node).offline:
910
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
911

    
912

    
913
def _CheckNodeNotDrained(lu, node):
914
  """Ensure that a given node is not drained.
915

916
  @param lu: the LU on behalf of which we make the check
917
  @param node: the node to check
918
  @raise errors.OpPrereqError: if the node is drained
919

920
  """
921
  if lu.cfg.GetNodeInfo(node).drained:
922
    raise errors.OpPrereqError("Can't use drained node %s" % node,
923
                               errors.ECODE_STATE)
924

    
925

    
926
def _CheckNodeVmCapable(lu, node):
927
  """Ensure that a given node is vm capable.
928

929
  @param lu: the LU on behalf of which we make the check
930
  @param node: the node to check
931
  @raise errors.OpPrereqError: if the node is not vm capable
932

933
  """
934
  if not lu.cfg.GetNodeInfo(node).vm_capable:
935
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
936
                               errors.ECODE_STATE)
937

    
938

    
939
def _CheckNodeHasOS(lu, node, os_name, force_variant):
940
  """Ensure that a node supports a given OS.
941

942
  @param lu: the LU on behalf of which we make the check
943
  @param node: the node to check
944
  @param os_name: the OS to query about
945
  @param force_variant: whether to ignore variant errors
946
  @raise errors.OpPrereqError: if the node is not supporting the OS
947

948
  """
949
  result = lu.rpc.call_os_get(node, os_name)
950
  result.Raise("OS '%s' not in supported OS list for node %s" %
951
               (os_name, node),
952
               prereq=True, ecode=errors.ECODE_INVAL)
953
  if not force_variant:
954
    _CheckOSVariant(result.payload, os_name)
955

    
956

    
957
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
958
  """Ensure that a node has the given secondary ip.
959

960
  @type lu: L{LogicalUnit}
961
  @param lu: the LU on behalf of which we make the check
962
  @type node: string
963
  @param node: the node to check
964
  @type secondary_ip: string
965
  @param secondary_ip: the ip to check
966
  @type prereq: boolean
967
  @param prereq: whether to throw a prerequisite or an execute error
968
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
969
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
970

971
  """
972
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
973
  result.Raise("Failure checking secondary ip on node %s" % node,
974
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
975
  if not result.payload:
976
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
977
           " please fix and re-run this command" % secondary_ip)
978
    if prereq:
979
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
980
    else:
981
      raise errors.OpExecError(msg)
982

    
983

    
984
def _GetClusterDomainSecret():
985
  """Reads the cluster domain secret.
986

987
  """
988
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
989
                               strict=True)
990

    
991

    
992
def _CheckInstanceState(lu, instance, req_states, msg=None):
993
  """Ensure that an instance is in one of the required states.
994

995
  @param lu: the LU on behalf of which we make the check
996
  @param instance: the instance to check
997
  @param msg: if passed, should be a message to replace the default one
998
  @raise errors.OpPrereqError: if the instance is not in the required state
999

1000
  """
1001
  if msg is None:
1002
    msg = "can't use instance from outside %s states" % ", ".join(req_states)
1003
  if instance.admin_state not in req_states:
1004
    raise errors.OpPrereqError("Instance %s is marked to be %s, %s" %
1005
                               (instance, instance.admin_state, msg),
1006
                               errors.ECODE_STATE)
1007

    
1008
  if constants.ADMINST_UP not in req_states:
1009
    pnode = instance.primary_node
1010
    ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
1011
    ins_l.Raise("Can't contact node %s for instance information" % pnode,
1012
                prereq=True, ecode=errors.ECODE_ENVIRON)
1013

    
1014
    if instance.name in ins_l.payload:
1015
      raise errors.OpPrereqError("Instance %s is running, %s" %
1016
                                 (instance.name, msg), errors.ECODE_STATE)
1017

    
1018

    
1019
def _ExpandItemName(fn, name, kind):
1020
  """Expand an item name.
1021

1022
  @param fn: the function to use for expansion
1023
  @param name: requested item name
1024
  @param kind: text description ('Node' or 'Instance')
1025
  @return: the resolved (full) name
1026
  @raise errors.OpPrereqError: if the item is not found
1027

1028
  """
1029
  full_name = fn(name)
1030
  if full_name is None:
1031
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
1032
                               errors.ECODE_NOENT)
1033
  return full_name
1034

    
1035

    
1036
def _ExpandNodeName(cfg, name):
1037
  """Wrapper over L{_ExpandItemName} for nodes."""
1038
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
1039

    
1040

    
1041
def _ExpandInstanceName(cfg, name):
1042
  """Wrapper over L{_ExpandItemName} for instance."""
1043
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
1044

    
1045

    
1046
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
1047
                          minmem, maxmem, vcpus, nics, disk_template, disks,
1048
                          bep, hvp, hypervisor_name, tags):
1049
  """Builds instance related env variables for hooks
1050

1051
  This builds the hook environment from individual variables.
1052

1053
  @type name: string
1054
  @param name: the name of the instance
1055
  @type primary_node: string
1056
  @param primary_node: the name of the instance's primary node
1057
  @type secondary_nodes: list
1058
  @param secondary_nodes: list of secondary nodes as strings
1059
  @type os_type: string
1060
  @param os_type: the name of the instance's OS
1061
  @type status: string
1062
  @param status: the desired status of the instance
1063
  @type minmem: string
1064
  @param minmem: the minimum memory size of the instance
1065
  @type maxmem: string
1066
  @param maxmem: the maximum memory size of the instance
1067
  @type vcpus: string
1068
  @param vcpus: the count of VCPUs the instance has
1069
  @type nics: list
1070
  @param nics: list of tuples (ip, mac, mode, link) representing
1071
      the NICs the instance has
1072
  @type disk_template: string
1073
  @param disk_template: the disk template of the instance
1074
  @type disks: list
1075
  @param disks: the list of (size, mode) pairs
1076
  @type bep: dict
1077
  @param bep: the backend parameters for the instance
1078
  @type hvp: dict
1079
  @param hvp: the hypervisor parameters for the instance
1080
  @type hypervisor_name: string
1081
  @param hypervisor_name: the hypervisor for the instance
1082
  @type tags: list
1083
  @param tags: list of instance tags as strings
1084
  @rtype: dict
1085
  @return: the hook environment for this instance
1086

1087
  """
1088
  env = {
1089
    "OP_TARGET": name,
1090
    "INSTANCE_NAME": name,
1091
    "INSTANCE_PRIMARY": primary_node,
1092
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
1093
    "INSTANCE_OS_TYPE": os_type,
1094
    "INSTANCE_STATUS": status,
1095
    "INSTANCE_MINMEM": minmem,
1096
    "INSTANCE_MAXMEM": maxmem,
1097
    # TODO(2.7) remove deprecated "memory" value
1098
    "INSTANCE_MEMORY": maxmem,
1099
    "INSTANCE_VCPUS": vcpus,
1100
    "INSTANCE_DISK_TEMPLATE": disk_template,
1101
    "INSTANCE_HYPERVISOR": hypervisor_name,
1102
  }
1103
  if nics:
1104
    nic_count = len(nics)
1105
    for idx, (ip, mac, mode, link) in enumerate(nics):
1106
      if ip is None:
1107
        ip = ""
1108
      env["INSTANCE_NIC%d_IP" % idx] = ip
1109
      env["INSTANCE_NIC%d_MAC" % idx] = mac
1110
      env["INSTANCE_NIC%d_MODE" % idx] = mode
1111
      env["INSTANCE_NIC%d_LINK" % idx] = link
1112
      if mode == constants.NIC_MODE_BRIDGED:
1113
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
1114
  else:
1115
    nic_count = 0
1116

    
1117
  env["INSTANCE_NIC_COUNT"] = nic_count
1118

    
1119
  if disks:
1120
    disk_count = len(disks)
1121
    for idx, (size, mode) in enumerate(disks):
1122
      env["INSTANCE_DISK%d_SIZE" % idx] = size
1123
      env["INSTANCE_DISK%d_MODE" % idx] = mode
1124
  else:
1125
    disk_count = 0
1126

    
1127
  env["INSTANCE_DISK_COUNT"] = disk_count
1128

    
1129
  if not tags:
1130
    tags = []
1131

    
1132
  env["INSTANCE_TAGS"] = " ".join(tags)
1133

    
1134
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
1135
    for key, value in source.items():
1136
      env["INSTANCE_%s_%s" % (kind, key)] = value
1137

    
1138
  return env
1139

    
1140

    
1141
def _NICListToTuple(lu, nics):
1142
  """Build a list of nic information tuples.
1143

1144
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
1145
  value in LUInstanceQueryData.
1146

1147
  @type lu:  L{LogicalUnit}
1148
  @param lu: the logical unit on whose behalf we execute
1149
  @type nics: list of L{objects.NIC}
1150
  @param nics: list of nics to convert to hooks tuples
1151

1152
  """
1153
  hooks_nics = []
1154
  cluster = lu.cfg.GetClusterInfo()
1155
  for nic in nics:
1156
    ip = nic.ip
1157
    mac = nic.mac
1158
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
1159
    mode = filled_params[constants.NIC_MODE]
1160
    link = filled_params[constants.NIC_LINK]
1161
    hooks_nics.append((ip, mac, mode, link))
1162
  return hooks_nics
1163

    
1164

    
1165
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
1166
  """Builds instance related env variables for hooks from an object.
1167

1168
  @type lu: L{LogicalUnit}
1169
  @param lu: the logical unit on whose behalf we execute
1170
  @type instance: L{objects.Instance}
1171
  @param instance: the instance for which we should build the
1172
      environment
1173
  @type override: dict
1174
  @param override: dictionary with key/values that will override
1175
      our values
1176
  @rtype: dict
1177
  @return: the hook environment dictionary
1178

1179
  """
1180
  cluster = lu.cfg.GetClusterInfo()
1181
  bep = cluster.FillBE(instance)
1182
  hvp = cluster.FillHV(instance)
1183
  args = {
1184
    "name": instance.name,
1185
    "primary_node": instance.primary_node,
1186
    "secondary_nodes": instance.secondary_nodes,
1187
    "os_type": instance.os,
1188
    "status": instance.admin_state,
1189
    "maxmem": bep[constants.BE_MAXMEM],
1190
    "minmem": bep[constants.BE_MINMEM],
1191
    "vcpus": bep[constants.BE_VCPUS],
1192
    "nics": _NICListToTuple(lu, instance.nics),
1193
    "disk_template": instance.disk_template,
1194
    "disks": [(disk.size, disk.mode) for disk in instance.disks],
1195
    "bep": bep,
1196
    "hvp": hvp,
1197
    "hypervisor_name": instance.hypervisor,
1198
    "tags": instance.tags,
1199
  }
1200
  if override:
1201
    args.update(override)
1202
  return _BuildInstanceHookEnv(**args) # pylint: disable=W0142
1203

    
1204

    
1205
def _AdjustCandidatePool(lu, exceptions):
1206
  """Adjust the candidate pool after node operations.
1207

1208
  """
1209
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1210
  if mod_list:
1211
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1212
               utils.CommaJoin(node.name for node in mod_list))
1213
    for name in mod_list:
1214
      lu.context.ReaddNode(name)
1215
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1216
  if mc_now > mc_max:
1217
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1218
               (mc_now, mc_max))
1219

    
1220

    
1221
def _DecideSelfPromotion(lu, exceptions=None):
1222
  """Decide whether I should promote myself as a master candidate.
1223

1224
  """
1225
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1226
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1227
  # the new node will increase mc_max with one, so:
1228
  mc_should = min(mc_should + 1, cp_size)
1229
  return mc_now < mc_should
1230

    
1231

    
1232
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1233
  """Check that the brigdes needed by a list of nics exist.
1234

1235
  """
1236
  cluster = lu.cfg.GetClusterInfo()
1237
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1238
  brlist = [params[constants.NIC_LINK] for params in paramslist
1239
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1240
  if brlist:
1241
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1242
    result.Raise("Error checking bridges on destination node '%s'" %
1243
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1244

    
1245

    
1246
def _CheckInstanceBridgesExist(lu, instance, node=None):
1247
  """Check that the brigdes needed by an instance exist.
1248

1249
  """
1250
  if node is None:
1251
    node = instance.primary_node
1252
  _CheckNicsBridgesExist(lu, instance.nics, node)
1253

    
1254

    
1255
def _CheckOSVariant(os_obj, name):
1256
  """Check whether an OS name conforms to the os variants specification.
1257

1258
  @type os_obj: L{objects.OS}
1259
  @param os_obj: OS object to check
1260
  @type name: string
1261
  @param name: OS name passed by the user, to check for validity
1262

1263
  """
1264
  variant = objects.OS.GetVariant(name)
1265
  if not os_obj.supported_variants:
1266
    if variant:
1267
      raise errors.OpPrereqError("OS '%s' doesn't support variants ('%s'"
1268
                                 " passed)" % (os_obj.name, variant),
1269
                                 errors.ECODE_INVAL)
1270
    return
1271
  if not variant:
1272
    raise errors.OpPrereqError("OS name must include a variant",
1273
                               errors.ECODE_INVAL)
1274

    
1275
  if variant not in os_obj.supported_variants:
1276
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1277

    
1278

    
1279
def _GetNodeInstancesInner(cfg, fn):
1280
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1281

    
1282

    
1283
def _GetNodeInstances(cfg, node_name):
1284
  """Returns a list of all primary and secondary instances on a node.
1285

1286
  """
1287

    
1288
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1289

    
1290

    
1291
def _GetNodePrimaryInstances(cfg, node_name):
1292
  """Returns primary instances on a node.
1293

1294
  """
1295
  return _GetNodeInstancesInner(cfg,
1296
                                lambda inst: node_name == inst.primary_node)
1297

    
1298

    
1299
def _GetNodeSecondaryInstances(cfg, node_name):
1300
  """Returns secondary instances on a node.
1301

1302
  """
1303
  return _GetNodeInstancesInner(cfg,
1304
                                lambda inst: node_name in inst.secondary_nodes)
1305

    
1306

    
1307
def _GetStorageTypeArgs(cfg, storage_type):
1308
  """Returns the arguments for a storage type.
1309

1310
  """
1311
  # Special case for file storage
1312
  if storage_type == constants.ST_FILE:
1313
    # storage.FileStorage wants a list of storage directories
1314
    return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1315

    
1316
  return []
1317

    
1318

    
1319
def _FindFaultyInstanceDisks(cfg, rpc_runner, instance, node_name, prereq):
1320
  faulty = []
1321

    
1322
  for dev in instance.disks:
1323
    cfg.SetDiskID(dev, node_name)
1324

    
1325
  result = rpc_runner.call_blockdev_getmirrorstatus(node_name, instance.disks)
1326
  result.Raise("Failed to get disk status from node %s" % node_name,
1327
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1328

    
1329
  for idx, bdev_status in enumerate(result.payload):
1330
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1331
      faulty.append(idx)
1332

    
1333
  return faulty
1334

    
1335

    
1336
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1337
  """Check the sanity of iallocator and node arguments and use the
1338
  cluster-wide iallocator if appropriate.
1339

1340
  Check that at most one of (iallocator, node) is specified. If none is
1341
  specified, then the LU's opcode's iallocator slot is filled with the
1342
  cluster-wide default iallocator.
1343

1344
  @type iallocator_slot: string
1345
  @param iallocator_slot: the name of the opcode iallocator slot
1346
  @type node_slot: string
1347
  @param node_slot: the name of the opcode target node slot
1348

1349
  """
1350
  node = getattr(lu.op, node_slot, None)
1351
  iallocator = getattr(lu.op, iallocator_slot, None)
1352

    
1353
  if node is not None and iallocator is not None:
1354
    raise errors.OpPrereqError("Do not specify both, iallocator and node",
1355
                               errors.ECODE_INVAL)
1356
  elif node is None and iallocator is None:
1357
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1358
    if default_iallocator:
1359
      setattr(lu.op, iallocator_slot, default_iallocator)
1360
    else:
1361
      raise errors.OpPrereqError("No iallocator or node given and no"
1362
                                 " cluster-wide default iallocator found;"
1363
                                 " please specify either an iallocator or a"
1364
                                 " node, or set a cluster-wide default"
1365
                                 " iallocator")
1366

    
1367

    
1368
def _GetDefaultIAllocator(cfg, iallocator):
1369
  """Decides on which iallocator to use.
1370

1371
  @type cfg: L{config.ConfigWriter}
1372
  @param cfg: Cluster configuration object
1373
  @type iallocator: string or None
1374
  @param iallocator: Iallocator specified in opcode
1375
  @rtype: string
1376
  @return: Iallocator name
1377

1378
  """
1379
  if not iallocator:
1380
    # Use default iallocator
1381
    iallocator = cfg.GetDefaultIAllocator()
1382

    
1383
  if not iallocator:
1384
    raise errors.OpPrereqError("No iallocator was specified, neither in the"
1385
                               " opcode nor as a cluster-wide default",
1386
                               errors.ECODE_INVAL)
1387

    
1388
  return iallocator
1389

    
1390

    
1391
class LUClusterPostInit(LogicalUnit):
1392
  """Logical unit for running hooks after cluster initialization.
1393

1394
  """
1395
  HPATH = "cluster-init"
1396
  HTYPE = constants.HTYPE_CLUSTER
1397

    
1398
  def BuildHooksEnv(self):
1399
    """Build hooks env.
1400

1401
    """
1402
    return {
1403
      "OP_TARGET": self.cfg.GetClusterName(),
1404
      }
1405

    
1406
  def BuildHooksNodes(self):
1407
    """Build hooks nodes.
1408

1409
    """
1410
    return ([], [self.cfg.GetMasterNode()])
1411

    
1412
  def Exec(self, feedback_fn):
1413
    """Nothing to do.
1414

1415
    """
1416
    return True
1417

    
1418

    
1419
class LUClusterDestroy(LogicalUnit):
1420
  """Logical unit for destroying the cluster.
1421

1422
  """
1423
  HPATH = "cluster-destroy"
1424
  HTYPE = constants.HTYPE_CLUSTER
1425

    
1426
  def BuildHooksEnv(self):
1427
    """Build hooks env.
1428

1429
    """
1430
    return {
1431
      "OP_TARGET": self.cfg.GetClusterName(),
1432
      }
1433

    
1434
  def BuildHooksNodes(self):
1435
    """Build hooks nodes.
1436

1437
    """
1438
    return ([], [])
1439

    
1440
  def CheckPrereq(self):
1441
    """Check prerequisites.
1442

1443
    This checks whether the cluster is empty.
1444

1445
    Any errors are signaled by raising errors.OpPrereqError.
1446

1447
    """
1448
    master = self.cfg.GetMasterNode()
1449

    
1450
    nodelist = self.cfg.GetNodeList()
1451
    if len(nodelist) != 1 or nodelist[0] != master:
1452
      raise errors.OpPrereqError("There are still %d node(s) in"
1453
                                 " this cluster." % (len(nodelist) - 1),
1454
                                 errors.ECODE_INVAL)
1455
    instancelist = self.cfg.GetInstanceList()
1456
    if instancelist:
1457
      raise errors.OpPrereqError("There are still %d instance(s) in"
1458
                                 " this cluster." % len(instancelist),
1459
                                 errors.ECODE_INVAL)
1460

    
1461
  def Exec(self, feedback_fn):
1462
    """Destroys the cluster.
1463

1464
    """
1465
    master_params = self.cfg.GetMasterNetworkParameters()
1466

    
1467
    # Run post hooks on master node before it's removed
1468
    _RunPostHook(self, master_params.name)
1469

    
1470
    ems = self.cfg.GetUseExternalMipScript()
1471
    result = self.rpc.call_node_deactivate_master_ip(master_params.name,
1472
                                                     master_params, ems)
1473
    result.Raise("Could not disable the master role")
1474

    
1475
    return master_params.name
1476

    
1477

    
1478
def _VerifyCertificate(filename):
1479
  """Verifies a certificate for L{LUClusterVerifyConfig}.
1480

1481
  @type filename: string
1482
  @param filename: Path to PEM file
1483

1484
  """
1485
  try:
1486
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1487
                                           utils.ReadFile(filename))
1488
  except Exception, err: # pylint: disable=W0703
1489
    return (LUClusterVerifyConfig.ETYPE_ERROR,
1490
            "Failed to load X509 certificate %s: %s" % (filename, err))
1491

    
1492
  (errcode, msg) = \
1493
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1494
                                constants.SSL_CERT_EXPIRATION_ERROR)
1495

    
1496
  if msg:
1497
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1498
  else:
1499
    fnamemsg = None
1500

    
1501
  if errcode is None:
1502
    return (None, fnamemsg)
1503
  elif errcode == utils.CERT_WARNING:
1504
    return (LUClusterVerifyConfig.ETYPE_WARNING, fnamemsg)
1505
  elif errcode == utils.CERT_ERROR:
1506
    return (LUClusterVerifyConfig.ETYPE_ERROR, fnamemsg)
1507

    
1508
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1509

    
1510

    
1511
def _GetAllHypervisorParameters(cluster, instances):
1512
  """Compute the set of all hypervisor parameters.
1513

1514
  @type cluster: L{objects.Cluster}
1515
  @param cluster: the cluster object
1516
  @param instances: list of L{objects.Instance}
1517
  @param instances: additional instances from which to obtain parameters
1518
  @rtype: list of (origin, hypervisor, parameters)
1519
  @return: a list with all parameters found, indicating the hypervisor they
1520
       apply to, and the origin (can be "cluster", "os X", or "instance Y")
1521

1522
  """
1523
  hvp_data = []
1524

    
1525
  for hv_name in cluster.enabled_hypervisors:
1526
    hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
1527

    
1528
  for os_name, os_hvp in cluster.os_hvp.items():
1529
    for hv_name, hv_params in os_hvp.items():
1530
      if hv_params:
1531
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
1532
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
1533

    
1534
  # TODO: collapse identical parameter values in a single one
1535
  for instance in instances:
1536
    if instance.hvparams:
1537
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
1538
                       cluster.FillHV(instance)))
1539

    
1540
  return hvp_data
1541

    
1542

    
1543
class _VerifyErrors(object):
1544
  """Mix-in for cluster/group verify LUs.
1545

1546
  It provides _Error and _ErrorIf, and updates the self.bad boolean. (Expects
1547
  self.op and self._feedback_fn to be available.)
1548

1549
  """
1550

    
1551
  ETYPE_FIELD = "code"
1552
  ETYPE_ERROR = "ERROR"
1553
  ETYPE_WARNING = "WARNING"
1554

    
1555
  def _Error(self, ecode, item, msg, *args, **kwargs):
1556
    """Format an error message.
1557

1558
    Based on the opcode's error_codes parameter, either format a
1559
    parseable error code, or a simpler error string.
1560

1561
    This must be called only from Exec and functions called from Exec.
1562

1563
    """
1564
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1565
    itype, etxt, _ = ecode
1566
    # first complete the msg
1567
    if args:
1568
      msg = msg % args
1569
    # then format the whole message
1570
    if self.op.error_codes: # This is a mix-in. pylint: disable=E1101
1571
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1572
    else:
1573
      if item:
1574
        item = " " + item
1575
      else:
1576
        item = ""
1577
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1578
    # and finally report it via the feedback_fn
1579
    self._feedback_fn("  - %s" % msg) # Mix-in. pylint: disable=E1101
1580

    
1581
  def _ErrorIf(self, cond, ecode, *args, **kwargs):
1582
    """Log an error message if the passed condition is True.
1583

1584
    """
1585
    cond = (bool(cond)
1586
            or self.op.debug_simulate_errors) # pylint: disable=E1101
1587

    
1588
    # If the error code is in the list of ignored errors, demote the error to a
1589
    # warning
1590
    (_, etxt, _) = ecode
1591
    if etxt in self.op.ignore_errors:     # pylint: disable=E1101
1592
      kwargs[self.ETYPE_FIELD] = self.ETYPE_WARNING
1593

    
1594
    if cond:
1595
      self._Error(ecode, *args, **kwargs)
1596

    
1597
    # do not mark the operation as failed for WARN cases only
1598
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1599
      self.bad = self.bad or cond
1600

    
1601

    
1602
class LUClusterVerify(NoHooksLU):
1603
  """Submits all jobs necessary to verify the cluster.
1604

1605
  """
1606
  REQ_BGL = False
1607

    
1608
  def ExpandNames(self):
1609
    self.needed_locks = {}
1610

    
1611
  def Exec(self, feedback_fn):
1612
    jobs = []
1613

    
1614
    if self.op.group_name:
1615
      groups = [self.op.group_name]
1616
      depends_fn = lambda: None
1617
    else:
1618
      groups = self.cfg.GetNodeGroupList()
1619

    
1620
      # Verify global configuration
1621
      jobs.append([
1622
        opcodes.OpClusterVerifyConfig(ignore_errors=self.op.ignore_errors)
1623
        ])
1624

    
1625
      # Always depend on global verification
1626
      depends_fn = lambda: [(-len(jobs), [])]
1627

    
1628
    jobs.extend([opcodes.OpClusterVerifyGroup(group_name=group,
1629
                                            ignore_errors=self.op.ignore_errors,
1630
                                            depends=depends_fn())]
1631
                for group in groups)
1632

    
1633
    # Fix up all parameters
1634
    for op in itertools.chain(*jobs): # pylint: disable=W0142
1635
      op.debug_simulate_errors = self.op.debug_simulate_errors
1636
      op.verbose = self.op.verbose
1637
      op.error_codes = self.op.error_codes
1638
      try:
1639
        op.skip_checks = self.op.skip_checks
1640
      except AttributeError:
1641
        assert not isinstance(op, opcodes.OpClusterVerifyGroup)
1642

    
1643
    return ResultWithJobs(jobs)
1644

    
1645

    
1646
class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1647
  """Verifies the cluster config.
1648

1649
  """
1650
  REQ_BGL = True
1651

    
1652
  def _VerifyHVP(self, hvp_data):
1653
    """Verifies locally the syntax of the hypervisor parameters.
1654

1655
    """
1656
    for item, hv_name, hv_params in hvp_data:
1657
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
1658
             (item, hv_name))
1659
      try:
1660
        hv_class = hypervisor.GetHypervisor(hv_name)
1661
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1662
        hv_class.CheckParameterSyntax(hv_params)
1663
      except errors.GenericError, err:
1664
        self._ErrorIf(True, constants.CV_ECLUSTERCFG, None, msg % str(err))
1665

    
1666
  def ExpandNames(self):
1667
    # Information can be safely retrieved as the BGL is acquired in exclusive
1668
    # mode
1669
    assert locking.BGL in self.owned_locks(locking.LEVEL_CLUSTER)
1670
    self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1671
    self.all_node_info = self.cfg.GetAllNodesInfo()
1672
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1673
    self.needed_locks = {}
1674

    
1675
  def Exec(self, feedback_fn):
1676
    """Verify integrity of cluster, performing various test on nodes.
1677

1678
    """
1679
    self.bad = False
1680
    self._feedback_fn = feedback_fn
1681

    
1682
    feedback_fn("* Verifying cluster config")
1683

    
1684
    for msg in self.cfg.VerifyConfig():
1685
      self._ErrorIf(True, constants.CV_ECLUSTERCFG, None, msg)
1686

    
1687
    feedback_fn("* Verifying cluster certificate files")
1688

    
1689
    for cert_filename in constants.ALL_CERT_FILES:
1690
      (errcode, msg) = _VerifyCertificate(cert_filename)
1691
      self._ErrorIf(errcode, constants.CV_ECLUSTERCERT, None, msg, code=errcode)
1692

    
1693
    feedback_fn("* Verifying hypervisor parameters")
1694

    
1695
    self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1696
                                                self.all_inst_info.values()))
1697

    
1698
    feedback_fn("* Verifying all nodes belong to an existing group")
1699

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

    
1704
    dangling_nodes = set(node.name for node in self.all_node_info.values()
1705
                         if node.group not in self.all_group_info)
1706

    
1707
    dangling_instances = {}
1708
    no_node_instances = []
1709

    
1710
    for inst in self.all_inst_info.values():
1711
      if inst.primary_node in dangling_nodes:
1712
        dangling_instances.setdefault(inst.primary_node, []).append(inst.name)
1713
      elif inst.primary_node not in self.all_node_info:
1714
        no_node_instances.append(inst.name)
1715

    
1716
    pretty_dangling = [
1717
        "%s (%s)" %
1718
        (node.name,
1719
         utils.CommaJoin(dangling_instances.get(node.name,
1720
                                                ["no instances"])))
1721
        for node in dangling_nodes]
1722

    
1723
    self._ErrorIf(bool(dangling_nodes), constants.CV_ECLUSTERDANGLINGNODES,
1724
                  None,
1725
                  "the following nodes (and their instances) belong to a non"
1726
                  " existing group: %s", utils.CommaJoin(pretty_dangling))
1727

    
1728
    self._ErrorIf(bool(no_node_instances), constants.CV_ECLUSTERDANGLINGINST,
1729
                  None,
1730
                  "the following instances have a non-existing primary-node:"
1731
                  " %s", utils.CommaJoin(no_node_instances))
1732

    
1733
    return not self.bad
1734

    
1735

    
1736
class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1737
  """Verifies the status of a node group.
1738

1739
  """
1740
  HPATH = "cluster-verify"
1741
  HTYPE = constants.HTYPE_CLUSTER
1742
  REQ_BGL = False
1743

    
1744
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1745

    
1746
  class NodeImage(object):
1747
    """A class representing the logical and physical status of a node.
1748

1749
    @type name: string
1750
    @ivar name: the node name to which this object refers
1751
    @ivar volumes: a structure as returned from
1752
        L{ganeti.backend.GetVolumeList} (runtime)
1753
    @ivar instances: a list of running instances (runtime)
1754
    @ivar pinst: list of configured primary instances (config)
1755
    @ivar sinst: list of configured secondary instances (config)
1756
    @ivar sbp: dictionary of {primary-node: list of instances} for all
1757
        instances for which this node is secondary (config)
1758
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1759
    @ivar dfree: free disk, as reported by the node (runtime)
1760
    @ivar offline: the offline status (config)
1761
    @type rpc_fail: boolean
1762
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1763
        not whether the individual keys were correct) (runtime)
1764
    @type lvm_fail: boolean
1765
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1766
    @type hyp_fail: boolean
1767
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1768
    @type ghost: boolean
1769
    @ivar ghost: whether this is a known node or not (config)
1770
    @type os_fail: boolean
1771
    @ivar os_fail: whether the RPC call didn't return valid OS data
1772
    @type oslist: list
1773
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1774
    @type vm_capable: boolean
1775
    @ivar vm_capable: whether the node can host instances
1776

1777
    """
1778
    def __init__(self, offline=False, name=None, vm_capable=True):
1779
      self.name = name
1780
      self.volumes = {}
1781
      self.instances = []
1782
      self.pinst = []
1783
      self.sinst = []
1784
      self.sbp = {}
1785
      self.mfree = 0
1786
      self.dfree = 0
1787
      self.offline = offline
1788
      self.vm_capable = vm_capable
1789
      self.rpc_fail = False
1790
      self.lvm_fail = False
1791
      self.hyp_fail = False
1792
      self.ghost = False
1793
      self.os_fail = False
1794
      self.oslist = {}
1795

    
1796
  def ExpandNames(self):
1797
    # This raises errors.OpPrereqError on its own:
1798
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1799

    
1800
    # Get instances in node group; this is unsafe and needs verification later
1801
    inst_names = self.cfg.GetNodeGroupInstances(self.group_uuid)
1802

    
1803
    self.needed_locks = {
1804
      locking.LEVEL_INSTANCE: inst_names,
1805
      locking.LEVEL_NODEGROUP: [self.group_uuid],
1806
      locking.LEVEL_NODE: [],
1807
      }
1808

    
1809
    self.share_locks = _ShareAll()
1810

    
1811
  def DeclareLocks(self, level):
1812
    if level == locking.LEVEL_NODE:
1813
      # Get members of node group; this is unsafe and needs verification later
1814
      nodes = set(self.cfg.GetNodeGroup(self.group_uuid).members)
1815

    
1816
      all_inst_info = self.cfg.GetAllInstancesInfo()
1817

    
1818
      # In Exec(), we warn about mirrored instances that have primary and
1819
      # secondary living in separate node groups. To fully verify that
1820
      # volumes for these instances are healthy, we will need to do an
1821
      # extra call to their secondaries. We ensure here those nodes will
1822
      # be locked.
1823
      for inst in self.owned_locks(locking.LEVEL_INSTANCE):
1824
        # Important: access only the instances whose lock is owned
1825
        if all_inst_info[inst].disk_template in constants.DTS_INT_MIRROR:
1826
          nodes.update(all_inst_info[inst].secondary_nodes)
1827

    
1828
      self.needed_locks[locking.LEVEL_NODE] = nodes
1829

    
1830
  def CheckPrereq(self):
1831
    assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
1832
    self.group_info = self.cfg.GetNodeGroup(self.group_uuid)
1833

    
1834
    group_nodes = set(self.group_info.members)
1835
    group_instances = self.cfg.GetNodeGroupInstances(self.group_uuid)
1836

    
1837
    unlocked_nodes = \
1838
        group_nodes.difference(self.owned_locks(locking.LEVEL_NODE))
1839

    
1840
    unlocked_instances = \
1841
        group_instances.difference(self.owned_locks(locking.LEVEL_INSTANCE))
1842

    
1843
    if unlocked_nodes:
1844
      raise errors.OpPrereqError("Missing lock for nodes: %s" %
1845
                                 utils.CommaJoin(unlocked_nodes))
1846

    
1847
    if unlocked_instances:
1848
      raise errors.OpPrereqError("Missing lock for instances: %s" %
1849
                                 utils.CommaJoin(unlocked_instances))
1850

    
1851
    self.all_node_info = self.cfg.GetAllNodesInfo()
1852
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1853

    
1854
    self.my_node_names = utils.NiceSort(group_nodes)
1855
    self.my_inst_names = utils.NiceSort(group_instances)
1856

    
1857
    self.my_node_info = dict((name, self.all_node_info[name])
1858
                             for name in self.my_node_names)
1859

    
1860
    self.my_inst_info = dict((name, self.all_inst_info[name])
1861
                             for name in self.my_inst_names)
1862

    
1863
    # We detect here the nodes that will need the extra RPC calls for verifying
1864
    # split LV volumes; they should be locked.
1865
    extra_lv_nodes = set()
1866

    
1867
    for inst in self.my_inst_info.values():
1868
      if inst.disk_template in constants.DTS_INT_MIRROR:
1869
        group = self.my_node_info[inst.primary_node].group
1870
        for nname in inst.secondary_nodes:
1871
          if self.all_node_info[nname].group != group:
1872
            extra_lv_nodes.add(nname)
1873

    
1874
    unlocked_lv_nodes = \
1875
        extra_lv_nodes.difference(self.owned_locks(locking.LEVEL_NODE))
1876

    
1877
    if unlocked_lv_nodes:
1878
      raise errors.OpPrereqError("these nodes could be locked: %s" %
1879
                                 utils.CommaJoin(unlocked_lv_nodes))
1880
    self.extra_lv_nodes = list(extra_lv_nodes)
1881

    
1882
  def _VerifyNode(self, ninfo, nresult):
1883
    """Perform some basic validation on data returned from a node.
1884

1885
      - check the result data structure is well formed and has all the
1886
        mandatory fields
1887
      - check ganeti version
1888

1889
    @type ninfo: L{objects.Node}
1890
    @param ninfo: the node to check
1891
    @param nresult: the results from the node
1892
    @rtype: boolean
1893
    @return: whether overall this call was successful (and we can expect
1894
         reasonable values in the respose)
1895

1896
    """
1897
    node = ninfo.name
1898
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
1899

    
1900
    # main result, nresult should be a non-empty dict
1901
    test = not nresult or not isinstance(nresult, dict)
1902
    _ErrorIf(test, constants.CV_ENODERPC, node,
1903
                  "unable to verify node: no data returned")
1904
    if test:
1905
      return False
1906

    
1907
    # compares ganeti version
1908
    local_version = constants.PROTOCOL_VERSION
1909
    remote_version = nresult.get("version", None)
1910
    test = not (remote_version and
1911
                isinstance(remote_version, (list, tuple)) and
1912
                len(remote_version) == 2)
1913
    _ErrorIf(test, constants.CV_ENODERPC, node,
1914
             "connection to node returned invalid data")
1915
    if test:
1916
      return False
1917

    
1918
    test = local_version != remote_version[0]
1919
    _ErrorIf(test, constants.CV_ENODEVERSION, node,
1920
             "incompatible protocol versions: master %s,"
1921
             " node %s", local_version, remote_version[0])
1922
    if test:
1923
      return False
1924

    
1925
    # node seems compatible, we can actually try to look into its results
1926

    
1927
    # full package version
1928
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1929
                  constants.CV_ENODEVERSION, node,
1930
                  "software version mismatch: master %s, node %s",
1931
                  constants.RELEASE_VERSION, remote_version[1],
1932
                  code=self.ETYPE_WARNING)
1933

    
1934
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1935
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1936
      for hv_name, hv_result in hyp_result.iteritems():
1937
        test = hv_result is not None
1938
        _ErrorIf(test, constants.CV_ENODEHV, node,
1939
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1940

    
1941
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1942
    if ninfo.vm_capable and isinstance(hvp_result, list):
1943
      for item, hv_name, hv_result in hvp_result:
1944
        _ErrorIf(True, constants.CV_ENODEHV, node,
1945
                 "hypervisor %s parameter verify failure (source %s): %s",
1946
                 hv_name, item, hv_result)
1947

    
1948
    test = nresult.get(constants.NV_NODESETUP,
1949
                       ["Missing NODESETUP results"])
1950
    _ErrorIf(test, constants.CV_ENODESETUP, node, "node setup error: %s",
1951
             "; ".join(test))
1952

    
1953
    return True
1954

    
1955
  def _VerifyNodeTime(self, ninfo, nresult,
1956
                      nvinfo_starttime, nvinfo_endtime):
1957
    """Check the node time.
1958

1959
    @type ninfo: L{objects.Node}
1960
    @param ninfo: the node to check
1961
    @param nresult: the remote results for the node
1962
    @param nvinfo_starttime: the start time of the RPC call
1963
    @param nvinfo_endtime: the end time of the RPC call
1964

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

    
1969
    ntime = nresult.get(constants.NV_TIME, None)
1970
    try:
1971
      ntime_merged = utils.MergeTime(ntime)
1972
    except (ValueError, TypeError):
1973
      _ErrorIf(True, constants.CV_ENODETIME, node, "Node returned invalid time")
1974
      return
1975

    
1976
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1977
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1978
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1979
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1980
    else:
1981
      ntime_diff = None
1982

    
1983
    _ErrorIf(ntime_diff is not None, constants.CV_ENODETIME, node,
1984
             "Node time diverges by at least %s from master node time",
1985
             ntime_diff)
1986

    
1987
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1988
    """Check the node LVM results.
1989

1990
    @type ninfo: L{objects.Node}
1991
    @param ninfo: the node to check
1992
    @param nresult: the remote results for the node
1993
    @param vg_name: the configured VG name
1994

1995
    """
1996
    if vg_name is None:
1997
      return
1998

    
1999
    node = ninfo.name
2000
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2001

    
2002
    # checks vg existence and size > 20G
2003
    vglist = nresult.get(constants.NV_VGLIST, None)
2004
    test = not vglist
2005
    _ErrorIf(test, constants.CV_ENODELVM, node, "unable to check volume groups")
2006
    if not test:
2007
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
2008
                                            constants.MIN_VG_SIZE)
2009
      _ErrorIf(vgstatus, constants.CV_ENODELVM, node, vgstatus)
2010

    
2011
    # check pv names
2012
    pvlist = nresult.get(constants.NV_PVLIST, None)
2013
    test = pvlist is None
2014
    _ErrorIf(test, constants.CV_ENODELVM, node, "Can't get PV list from node")
2015
    if not test:
2016
      # check that ':' is not present in PV names, since it's a
2017
      # special character for lvcreate (denotes the range of PEs to
2018
      # use on the PV)
2019
      for _, pvname, owner_vg in pvlist:
2020
        test = ":" in pvname
2021
        _ErrorIf(test, constants.CV_ENODELVM, node,
2022
                 "Invalid character ':' in PV '%s' of VG '%s'",
2023
                 pvname, owner_vg)
2024

    
2025
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
2026
    """Check the node bridges.
2027

2028
    @type ninfo: L{objects.Node}
2029
    @param ninfo: the node to check
2030
    @param nresult: the remote results for the node
2031
    @param bridges: the expected list of bridges
2032

2033
    """
2034
    if not bridges:
2035
      return
2036

    
2037
    node = ninfo.name
2038
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2039

    
2040
    missing = nresult.get(constants.NV_BRIDGES, None)
2041
    test = not isinstance(missing, list)
2042
    _ErrorIf(test, constants.CV_ENODENET, node,
2043
             "did not return valid bridge information")
2044
    if not test:
2045
      _ErrorIf(bool(missing), constants.CV_ENODENET, node,
2046
               "missing bridges: %s" % utils.CommaJoin(sorted(missing)))
2047

    
2048
  def _VerifyNodeUserScripts(self, ninfo, nresult):
2049
    """Check the results of user scripts presence and executability on the node
2050

2051
    @type ninfo: L{objects.Node}
2052
    @param ninfo: the node to check
2053
    @param nresult: the remote results for the node
2054

2055
    """
2056
    node = ninfo.name
2057

    
2058
    test = not constants.NV_USERSCRIPTS in nresult
2059
    self._ErrorIf(test, constants.CV_ENODEUSERSCRIPTS, node,
2060
                  "did not return user scripts information")
2061

    
2062
    broken_scripts = nresult.get(constants.NV_USERSCRIPTS, None)
2063
    if not test:
2064
      self._ErrorIf(broken_scripts, constants.CV_ENODEUSERSCRIPTS, node,
2065
                    "user scripts not present or not executable: %s" %
2066
                    utils.CommaJoin(sorted(broken_scripts)))
2067

    
2068
  def _VerifyNodeNetwork(self, ninfo, nresult):
2069
    """Check the node network connectivity results.
2070

2071
    @type ninfo: L{objects.Node}
2072
    @param ninfo: the node to check
2073
    @param nresult: the remote results for the node
2074

2075
    """
2076
    node = ninfo.name
2077
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2078

    
2079
    test = constants.NV_NODELIST not in nresult
2080
    _ErrorIf(test, constants.CV_ENODESSH, node,
2081
             "node hasn't returned node ssh connectivity data")
2082
    if not test:
2083
      if nresult[constants.NV_NODELIST]:
2084
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
2085
          _ErrorIf(True, constants.CV_ENODESSH, node,
2086
                   "ssh communication with node '%s': %s", a_node, a_msg)
2087

    
2088
    test = constants.NV_NODENETTEST not in nresult
2089
    _ErrorIf(test, constants.CV_ENODENET, node,
2090
             "node hasn't returned node tcp connectivity data")
2091
    if not test:
2092
      if nresult[constants.NV_NODENETTEST]:
2093
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
2094
        for anode in nlist:
2095
          _ErrorIf(True, constants.CV_ENODENET, node,
2096
                   "tcp communication with node '%s': %s",
2097
                   anode, nresult[constants.NV_NODENETTEST][anode])
2098

    
2099
    test = constants.NV_MASTERIP not in nresult
2100
    _ErrorIf(test, constants.CV_ENODENET, node,
2101
             "node hasn't returned node master IP reachability data")
2102
    if not test:
2103
      if not nresult[constants.NV_MASTERIP]:
2104
        if node == self.master_node:
2105
          msg = "the master node cannot reach the master IP (not configured?)"
2106
        else:
2107
          msg = "cannot reach the master IP"
2108
        _ErrorIf(True, constants.CV_ENODENET, node, msg)
2109

    
2110
  def _VerifyInstance(self, instance, instanceconfig, node_image,
2111
                      diskstatus):
2112
    """Verify an instance.
2113

2114
    This function checks to see if the required block devices are
2115
    available on the instance's node.
2116

2117
    """
2118
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2119
    node_current = instanceconfig.primary_node
2120

    
2121
    node_vol_should = {}
2122
    instanceconfig.MapLVsByNode(node_vol_should)
2123

    
2124
    for node in node_vol_should:
2125
      n_img = node_image[node]
2126
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
2127
        # ignore missing volumes on offline or broken nodes
2128
        continue
2129
      for volume in node_vol_should[node]:
2130
        test = volume not in n_img.volumes
2131
        _ErrorIf(test, constants.CV_EINSTANCEMISSINGDISK, instance,
2132
                 "volume %s missing on node %s", volume, node)
2133

    
2134
    if instanceconfig.admin_state == constants.ADMINST_UP:
2135
      pri_img = node_image[node_current]
2136
      test = instance not in pri_img.instances and not pri_img.offline
2137
      _ErrorIf(test, constants.CV_EINSTANCEDOWN, instance,
2138
               "instance not running on its primary node %s",
2139
               node_current)
2140

    
2141
    diskdata = [(nname, success, status, idx)
2142
                for (nname, disks) in diskstatus.items()
2143
                for idx, (success, status) in enumerate(disks)]
2144

    
2145
    for nname, success, bdev_status, idx in diskdata:
2146
      # the 'ghost node' construction in Exec() ensures that we have a
2147
      # node here
2148
      snode = node_image[nname]
2149
      bad_snode = snode.ghost or snode.offline
2150
      _ErrorIf(instanceconfig.admin_state == constants.ADMINST_UP and
2151
               not success and not bad_snode,
2152
               constants.CV_EINSTANCEFAULTYDISK, instance,
2153
               "couldn't retrieve status for disk/%s on %s: %s",
2154
               idx, nname, bdev_status)
2155
      _ErrorIf((instanceconfig.admin_state == constants.ADMINST_UP and
2156
                success and bdev_status.ldisk_status == constants.LDS_FAULTY),
2157
               constants.CV_EINSTANCEFAULTYDISK, instance,
2158
               "disk/%s on %s is faulty", idx, nname)
2159

    
2160
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
2161
    """Verify if there are any unknown volumes in the cluster.
2162

2163
    The .os, .swap and backup volumes are ignored. All other volumes are
2164
    reported as unknown.
2165

2166
    @type reserved: L{ganeti.utils.FieldSet}
2167
    @param reserved: a FieldSet of reserved volume names
2168

2169
    """
2170
    for node, n_img in node_image.items():
2171
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
2172
        # skip non-healthy nodes
2173
        continue
2174
      for volume in n_img.volumes:
2175
        test = ((node not in node_vol_should or
2176
                volume not in node_vol_should[node]) and
2177
                not reserved.Matches(volume))
2178
        self._ErrorIf(test, constants.CV_ENODEORPHANLV, node,
2179
                      "volume %s is unknown", volume)
2180

    
2181
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
2182
    """Verify N+1 Memory Resilience.
2183

2184
    Check that if one single node dies we can still start all the
2185
    instances it was primary for.
2186

2187
    """
2188
    cluster_info = self.cfg.GetClusterInfo()
2189
    for node, n_img in node_image.items():
2190
      # This code checks that every node which is now listed as
2191
      # secondary has enough memory to host all instances it is
2192
      # supposed to should a single other node in the cluster fail.
2193
      # FIXME: not ready for failover to an arbitrary node
2194
      # FIXME: does not support file-backed instances
2195
      # WARNING: we currently take into account down instances as well
2196
      # as up ones, considering that even if they're down someone
2197
      # might want to start them even in the event of a node failure.
2198
      if n_img.offline:
2199
        # we're skipping offline nodes from the N+1 warning, since
2200
        # most likely we don't have good memory infromation from them;
2201
        # we already list instances living on such nodes, and that's
2202
        # enough warning
2203
        continue
2204
      #TODO(dynmem): use MINMEM for checking
2205
      #TODO(dynmem): also consider ballooning out other instances
2206
      for prinode, instances in n_img.sbp.items():
2207
        needed_mem = 0
2208
        for instance in instances:
2209
          bep = cluster_info.FillBE(instance_cfg[instance])
2210
          if bep[constants.BE_AUTO_BALANCE]:
2211
            needed_mem += bep[constants.BE_MAXMEM]
2212
        test = n_img.mfree < needed_mem
2213
        self._ErrorIf(test, constants.CV_ENODEN1, node,
2214
                      "not enough memory to accomodate instance failovers"
2215
                      " should node %s fail (%dMiB needed, %dMiB available)",
2216
                      prinode, needed_mem, n_img.mfree)
2217

    
2218
  @classmethod
2219
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
2220
                   (files_all, files_opt, files_mc, files_vm)):
2221
    """Verifies file checksums collected from all nodes.
2222

2223
    @param errorif: Callback for reporting errors
2224
    @param nodeinfo: List of L{objects.Node} objects
2225
    @param master_node: Name of master node
2226
    @param all_nvinfo: RPC results
2227

2228
    """
2229
    # Define functions determining which nodes to consider for a file
2230
    files2nodefn = [
2231
      (files_all, None),
2232
      (files_mc, lambda node: (node.master_candidate or
2233
                               node.name == master_node)),
2234
      (files_vm, lambda node: node.vm_capable),
2235
      ]
2236

    
2237
    # Build mapping from filename to list of nodes which should have the file
2238
    nodefiles = {}
2239
    for (files, fn) in files2nodefn:
2240
      if fn is None:
2241
        filenodes = nodeinfo
2242
      else:
2243
        filenodes = filter(fn, nodeinfo)
2244
      nodefiles.update((filename,
2245
                        frozenset(map(operator.attrgetter("name"), filenodes)))
2246
                       for filename in files)
2247

    
2248
    assert set(nodefiles) == (files_all | files_mc | files_vm)
2249

    
2250
    fileinfo = dict((filename, {}) for filename in nodefiles)
2251
    ignore_nodes = set()
2252

    
2253
    for node in nodeinfo:
2254
      if node.offline:
2255
        ignore_nodes.add(node.name)
2256
        continue
2257

    
2258
      nresult = all_nvinfo[node.name]
2259

    
2260
      if nresult.fail_msg or not nresult.payload:
2261
        node_files = None
2262
      else:
2263
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
2264

    
2265
      test = not (node_files and isinstance(node_files, dict))
2266
      errorif(test, constants.CV_ENODEFILECHECK, node.name,
2267
              "Node did not return file checksum data")
2268
      if test:
2269
        ignore_nodes.add(node.name)
2270
        continue
2271

    
2272
      # Build per-checksum mapping from filename to nodes having it
2273
      for (filename, checksum) in node_files.items():
2274
        assert filename in nodefiles
2275
        fileinfo[filename].setdefault(checksum, set()).add(node.name)
2276

    
2277
    for (filename, checksums) in fileinfo.items():
2278
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
2279

    
2280
      # Nodes having the file
2281
      with_file = frozenset(node_name
2282
                            for nodes in fileinfo[filename].values()
2283
                            for node_name in nodes) - ignore_nodes
2284

    
2285
      expected_nodes = nodefiles[filename] - ignore_nodes
2286

    
2287
      # Nodes missing file
2288
      missing_file = expected_nodes - with_file
2289

    
2290
      if filename in files_opt:
2291
        # All or no nodes
2292
        errorif(missing_file and missing_file != expected_nodes,
2293
                constants.CV_ECLUSTERFILECHECK, None,
2294
                "File %s is optional, but it must exist on all or no"
2295
                " nodes (not found on %s)",
2296
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
2297
      else:
2298
        errorif(missing_file, constants.CV_ECLUSTERFILECHECK, None,
2299
                "File %s is missing from node(s) %s", filename,
2300
                utils.CommaJoin(utils.NiceSort(missing_file)))
2301

    
2302
        # Warn if a node has a file it shouldn't
2303
        unexpected = with_file - expected_nodes
2304
        errorif(unexpected,
2305
                constants.CV_ECLUSTERFILECHECK, None,
2306
                "File %s should not exist on node(s) %s",
2307
                filename, utils.CommaJoin(utils.NiceSort(unexpected)))
2308

    
2309
      # See if there are multiple versions of the file
2310
      test = len(checksums) > 1
2311
      if test:
2312
        variants = ["variant %s on %s" %
2313
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
2314
                    for (idx, (checksum, nodes)) in
2315
                      enumerate(sorted(checksums.items()))]
2316
      else:
2317
        variants = []
2318

    
2319
      errorif(test, constants.CV_ECLUSTERFILECHECK, None,
2320
              "File %s found with %s different checksums (%s)",
2321
              filename, len(checksums), "; ".join(variants))
2322

    
2323
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
2324
                      drbd_map):
2325
    """Verifies and the node DRBD status.
2326

2327
    @type ninfo: L{objects.Node}
2328
    @param ninfo: the node to check
2329
    @param nresult: the remote results for the node
2330
    @param instanceinfo: the dict of instances
2331
    @param drbd_helper: the configured DRBD usermode helper
2332
    @param drbd_map: the DRBD map as returned by
2333
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
2334

2335
    """
2336
    node = ninfo.name
2337
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2338

    
2339
    if drbd_helper:
2340
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
2341
      test = (helper_result == None)
2342
      _ErrorIf(test, constants.CV_ENODEDRBDHELPER, node,
2343
               "no drbd usermode helper returned")
2344
      if helper_result:
2345
        status, payload = helper_result
2346
        test = not status
2347
        _ErrorIf(test, constants.CV_ENODEDRBDHELPER, node,
2348
                 "drbd usermode helper check unsuccessful: %s", payload)
2349
        test = status and (payload != drbd_helper)
2350
        _ErrorIf(test, constants.CV_ENODEDRBDHELPER, node,
2351
                 "wrong drbd usermode helper: %s", payload)
2352

    
2353
    # compute the DRBD minors
2354
    node_drbd = {}
2355
    for minor, instance in drbd_map[node].items():
2356
      test = instance not in instanceinfo
2357
      _ErrorIf(test, constants.CV_ECLUSTERCFG, None,
2358
               "ghost instance '%s' in temporary DRBD map", instance)
2359
        # ghost instance should not be running, but otherwise we
2360
        # don't give double warnings (both ghost instance and
2361
        # unallocated minor in use)
2362
      if test:
2363
        node_drbd[minor] = (instance, False)
2364
      else:
2365
        instance = instanceinfo[instance]
2366
        node_drbd[minor] = (instance.name,
2367
                            instance.admin_state == constants.ADMINST_UP)
2368

    
2369
    # and now check them
2370
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
2371
    test = not isinstance(used_minors, (tuple, list))
2372
    _ErrorIf(test, constants.CV_ENODEDRBD, node,
2373
             "cannot parse drbd status file: %s", str(used_minors))
2374
    if test:
2375
      # we cannot check drbd status
2376
      return
2377

    
2378
    for minor, (iname, must_exist) in node_drbd.items():
2379
      test = minor not in used_minors and must_exist
2380
      _ErrorIf(test, constants.CV_ENODEDRBD, node,
2381
               "drbd minor %d of instance %s is not active", minor, iname)
2382
    for minor in used_minors:
2383
      test = minor not in node_drbd
2384
      _ErrorIf(test, constants.CV_ENODEDRBD, node,
2385
               "unallocated drbd minor %d is in use", minor)
2386

    
2387
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
2388
    """Builds the node OS structures.
2389

2390
    @type ninfo: L{objects.Node}
2391
    @param ninfo: the node to check
2392
    @param nresult: the remote results for the node
2393
    @param nimg: the node image object
2394

2395
    """
2396
    node = ninfo.name
2397
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2398

    
2399
    remote_os = nresult.get(constants.NV_OSLIST, None)
2400
    test = (not isinstance(remote_os, list) or
2401
            not compat.all(isinstance(v, list) and len(v) == 7
2402
                           for v in remote_os))
2403

    
2404
    _ErrorIf(test, constants.CV_ENODEOS, node,
2405
             "node hasn't returned valid OS data")
2406

    
2407
    nimg.os_fail = test
2408

    
2409
    if test:
2410
      return
2411

    
2412
    os_dict = {}
2413

    
2414
    for (name, os_path, status, diagnose,
2415
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2416

    
2417
      if name not in os_dict:
2418
        os_dict[name] = []
2419

    
2420
      # parameters is a list of lists instead of list of tuples due to
2421
      # JSON lacking a real tuple type, fix it:
2422
      parameters = [tuple(v) for v in parameters]
2423
      os_dict[name].append((os_path, status, diagnose,
2424
                            set(variants), set(parameters), set(api_ver)))
2425

    
2426
    nimg.oslist = os_dict
2427

    
2428
  def _VerifyNodeOS(self, ninfo, nimg, base):
2429
    """Verifies the node OS list.
2430

2431
    @type ninfo: L{objects.Node}
2432
    @param ninfo: the node to check
2433
    @param nimg: the node image object
2434
    @param base: the 'template' node we match against (e.g. from the master)
2435

2436
    """
2437
    node = ninfo.name
2438
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2439

    
2440
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2441

    
2442
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
2443
    for os_name, os_data in nimg.oslist.items():
2444
      assert os_data, "Empty OS status for OS %s?!" % os_name
2445
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
2446
      _ErrorIf(not f_status, constants.CV_ENODEOS, node,
2447
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
2448
      _ErrorIf(len(os_data) > 1, constants.CV_ENODEOS, node,
2449
               "OS '%s' has multiple entries (first one shadows the rest): %s",
2450
               os_name, utils.CommaJoin([v[0] for v in os_data]))
2451
      # comparisons with the 'base' image
2452
      test = os_name not in base.oslist
2453
      _ErrorIf(test, constants.CV_ENODEOS, node,
2454
               "Extra OS %s not present on reference node (%s)",
2455
               os_name, base.name)
2456
      if test:
2457
        continue
2458
      assert base.oslist[os_name], "Base node has empty OS status?"
2459
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
2460
      if not b_status:
2461
        # base OS is invalid, skipping
2462
        continue
2463
      for kind, a, b in [("API version", f_api, b_api),
2464
                         ("variants list", f_var, b_var),
2465
                         ("parameters", beautify_params(f_param),
2466
                          beautify_params(b_param))]:
2467
        _ErrorIf(a != b, constants.CV_ENODEOS, node,
2468
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2469
                 kind, os_name, base.name,
2470
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2471

    
2472
    # check any missing OSes
2473
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2474
    _ErrorIf(missing, constants.CV_ENODEOS, node,
2475
             "OSes present on reference node %s but missing on this node: %s",
2476
             base.name, utils.CommaJoin(missing))
2477

    
2478
  def _VerifyOob(self, ninfo, nresult):
2479
    """Verifies out of band functionality of a node.
2480

2481
    @type ninfo: L{objects.Node}
2482
    @param ninfo: the node to check
2483
    @param nresult: the remote results for the node
2484

2485
    """
2486
    node = ninfo.name
2487
    # We just have to verify the paths on master and/or master candidates
2488
    # as the oob helper is invoked on the master
2489
    if ((ninfo.master_candidate or ninfo.master_capable) and
2490
        constants.NV_OOB_PATHS in nresult):
2491
      for path_result in nresult[constants.NV_OOB_PATHS]:
2492
        self._ErrorIf(path_result, constants.CV_ENODEOOBPATH, node, path_result)
2493

    
2494
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2495
    """Verifies and updates the node volume data.
2496

2497
    This function will update a L{NodeImage}'s internal structures
2498
    with data from the remote call.
2499

2500
    @type ninfo: L{objects.Node}
2501
    @param ninfo: the node to check
2502
    @param nresult: the remote results for the node
2503
    @param nimg: the node image object
2504
    @param vg_name: the configured VG name
2505

2506
    """
2507
    node = ninfo.name
2508
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2509

    
2510
    nimg.lvm_fail = True
2511
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2512
    if vg_name is None:
2513
      pass
2514
    elif isinstance(lvdata, basestring):
2515
      _ErrorIf(True, constants.CV_ENODELVM, node, "LVM problem on node: %s",
2516
               utils.SafeEncode(lvdata))
2517
    elif not isinstance(lvdata, dict):
2518
      _ErrorIf(True, constants.CV_ENODELVM, node,
2519
               "rpc call to node failed (lvlist)")
2520
    else:
2521
      nimg.volumes = lvdata
2522
      nimg.lvm_fail = False
2523

    
2524
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2525
    """Verifies and updates the node instance list.
2526

2527
    If the listing was successful, then updates this node's instance
2528
    list. Otherwise, it marks the RPC call as failed for the instance
2529
    list key.
2530

2531
    @type ninfo: L{objects.Node}
2532
    @param ninfo: the node to check
2533
    @param nresult: the remote results for the node
2534
    @param nimg: the node image object
2535

2536
    """
2537
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2538
    test = not isinstance(idata, list)
2539
    self._ErrorIf(test, constants.CV_ENODEHV, ninfo.name,
2540
                  "rpc call to node failed (instancelist): %s",
2541
                  utils.SafeEncode(str(idata)))
2542
    if test:
2543
      nimg.hyp_fail = True
2544
    else:
2545
      nimg.instances = idata
2546

    
2547
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2548
    """Verifies and computes a node information map
2549

2550
    @type ninfo: L{objects.Node}
2551
    @param ninfo: the node to check
2552
    @param nresult: the remote results for the node
2553
    @param nimg: the node image object
2554
    @param vg_name: the configured VG name
2555

2556
    """
2557
    node = ninfo.name
2558
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2559

    
2560
    # try to read free memory (from the hypervisor)
2561
    hv_info = nresult.get(constants.NV_HVINFO, None)
2562
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2563
    _ErrorIf(test, constants.CV_ENODEHV, node,
2564
             "rpc call to node failed (hvinfo)")
2565
    if not test:
2566
      try:
2567
        nimg.mfree = int(hv_info["memory_free"])
2568
      except (ValueError, TypeError):
2569
        _ErrorIf(True, constants.CV_ENODERPC, node,
2570
                 "node returned invalid nodeinfo, check hypervisor")
2571

    
2572
    # FIXME: devise a free space model for file based instances as well
2573
    if vg_name is not None:
2574
      test = (constants.NV_VGLIST not in nresult or
2575
              vg_name not in nresult[constants.NV_VGLIST])
2576
      _ErrorIf(test, constants.CV_ENODELVM, node,
2577
               "node didn't return data for the volume group '%s'"
2578
               " - it is either missing or broken", vg_name)
2579
      if not test:
2580
        try:
2581
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2582
        except (ValueError, TypeError):
2583
          _ErrorIf(True, constants.CV_ENODERPC, node,
2584
                   "node returned invalid LVM info, check LVM status")
2585

    
2586
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2587
    """Gets per-disk status information for all instances.
2588

2589
    @type nodelist: list of strings
2590
    @param nodelist: Node names
2591
    @type node_image: dict of (name, L{objects.Node})
2592
    @param node_image: Node objects
2593
    @type instanceinfo: dict of (name, L{objects.Instance})
2594
    @param instanceinfo: Instance objects
2595
    @rtype: {instance: {node: [(succes, payload)]}}
2596
    @return: a dictionary of per-instance dictionaries with nodes as
2597
        keys and disk information as values; the disk information is a
2598
        list of tuples (success, payload)
2599

2600
    """
2601
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2602

    
2603
    node_disks = {}
2604
    node_disks_devonly = {}
2605
    diskless_instances = set()
2606
    diskless = constants.DT_DISKLESS
2607

    
2608
    for nname in nodelist:
2609
      node_instances = list(itertools.chain(node_image[nname].pinst,
2610
                                            node_image[nname].sinst))
2611
      diskless_instances.update(inst for inst in node_instances
2612
                                if instanceinfo[inst].disk_template == diskless)
2613
      disks = [(inst, disk)
2614
               for inst in node_instances
2615
               for disk in instanceinfo[inst].disks]
2616

    
2617
      if not disks:
2618
        # No need to collect data
2619
        continue
2620

    
2621
      node_disks[nname] = disks
2622

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

    
2627
      for dev in devonly:
2628
        self.cfg.SetDiskID(dev, nname)
2629

    
2630
      node_disks_devonly[nname] = devonly
2631

    
2632
    assert len(node_disks) == len(node_disks_devonly)
2633

    
2634
    # Collect data from all nodes with disks
2635
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2636
                                                          node_disks_devonly)
2637

    
2638
    assert len(result) == len(node_disks)
2639

    
2640
    instdisk = {}
2641

    
2642
    for (nname, nres) in result.items():
2643
      disks = node_disks[nname]
2644

    
2645
      if nres.offline:
2646
        # No data from this node
2647
        data = len(disks) * [(False, "node offline")]
2648
      else:
2649
        msg = nres.fail_msg
2650
        _ErrorIf(msg, constants.CV_ENODERPC, nname,
2651
                 "while getting disk information: %s", msg)
2652
        if msg:
2653
          # No data from this node
2654
          data = len(disks) * [(False, msg)]
2655
        else:
2656
          data = []
2657
          for idx, i in enumerate(nres.payload):
2658
            if isinstance(i, (tuple, list)) and len(i) == 2:
2659
              data.append(i)
2660
            else:
2661
              logging.warning("Invalid result from node %s, entry %d: %s",
2662
                              nname, idx, i)
2663
              data.append((False, "Invalid result from the remote node"))
2664

    
2665
      for ((inst, _), status) in zip(disks, data):
2666
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2667

    
2668
    # Add empty entries for diskless instances.
2669
    for inst in diskless_instances:
2670
      assert inst not in instdisk
2671
      instdisk[inst] = {}
2672

    
2673
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2674
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2675
                      compat.all(isinstance(s, (tuple, list)) and
2676
                                 len(s) == 2 for s in statuses)
2677
                      for inst, nnames in instdisk.items()
2678
                      for nname, statuses in nnames.items())
2679
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2680

    
2681
    return instdisk
2682

    
2683
  @staticmethod
2684
  def _SshNodeSelector(group_uuid, all_nodes):
2685
    """Create endless iterators for all potential SSH check hosts.
2686

2687
    """
2688
    nodes = [node for node in all_nodes
2689
             if (node.group != group_uuid and
2690
                 not node.offline)]
2691
    keyfunc = operator.attrgetter("group")
2692

    
2693
    return map(itertools.cycle,
2694
               [sorted(map(operator.attrgetter("name"), names))
2695
                for _, names in itertools.groupby(sorted(nodes, key=keyfunc),
2696
                                                  keyfunc)])
2697

    
2698
  @classmethod
2699
  def _SelectSshCheckNodes(cls, group_nodes, group_uuid, all_nodes):
2700
    """Choose which nodes should talk to which other nodes.
2701

2702
    We will make nodes contact all nodes in their group, and one node from
2703
    every other group.
2704

2705
    @warning: This algorithm has a known issue if one node group is much
2706
      smaller than others (e.g. just one node). In such a case all other
2707
      nodes will talk to the single node.
2708

2709
    """
2710
    online_nodes = sorted(node.name for node in group_nodes if not node.offline)
2711
    sel = cls._SshNodeSelector(group_uuid, all_nodes)
2712

    
2713
    return (online_nodes,
2714
            dict((name, sorted([i.next() for i in sel]))
2715
                 for name in online_nodes))
2716

    
2717
  def BuildHooksEnv(self):
2718
    """Build hooks env.
2719

2720
    Cluster-Verify hooks just ran in the post phase and their failure makes
2721
    the output be logged in the verify output and the verification to fail.
2722

2723
    """
2724
    env = {
2725
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2726
      }
2727

    
2728
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2729
               for node in self.my_node_info.values())
2730

    
2731
    return env
2732

    
2733
  def BuildHooksNodes(self):
2734
    """Build hooks nodes.
2735

2736
    """
2737
    return ([], self.my_node_names)
2738

    
2739
  def Exec(self, feedback_fn):
2740
    """Verify integrity of the node group, performing various test on nodes.
2741

2742
    """
2743
    # This method has too many local variables. pylint: disable=R0914
2744
    feedback_fn("* Verifying group '%s'" % self.group_info.name)
2745

    
2746
    if not self.my_node_names:
2747
      # empty node group
2748
      feedback_fn("* Empty node group, skipping verification")
2749
      return True
2750

    
2751
    self.bad = False
2752
    _ErrorIf = self._ErrorIf # pylint: disable=C0103
2753
    verbose = self.op.verbose
2754
    self._feedback_fn = feedback_fn
2755

    
2756
    vg_name = self.cfg.GetVGName()
2757
    drbd_helper = self.cfg.GetDRBDHelper()
2758
    cluster = self.cfg.GetClusterInfo()
2759
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2760
    hypervisors = cluster.enabled_hypervisors
2761
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2762

    
2763
    i_non_redundant = [] # Non redundant instances
2764
    i_non_a_balanced = [] # Non auto-balanced instances
2765
    i_offline = 0 # Count of offline instances
2766
    n_offline = 0 # Count of offline nodes
2767
    n_drained = 0 # Count of nodes being drained
2768
    node_vol_should = {}
2769

    
2770
    # FIXME: verify OS list
2771

    
2772
    # File verification
2773
    filemap = _ComputeAncillaryFiles(cluster, False)
2774

    
2775
    # do local checksums
2776
    master_node = self.master_node = self.cfg.GetMasterNode()
2777
    master_ip = self.cfg.GetMasterIP()
2778

    
2779
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2780

    
2781
    user_scripts = []
2782
    if self.cfg.GetUseExternalMipScript():
2783
      user_scripts.append(constants.EXTERNAL_MASTER_SETUP_SCRIPT)
2784

    
2785
    node_verify_param = {
2786
      constants.NV_FILELIST:
2787
        utils.UniqueSequence(filename
2788
                             for files in filemap
2789
                             for filename in files),
2790
      constants.NV_NODELIST:
2791
        self._SelectSshCheckNodes(node_data_list, self.group_uuid,
2792
                                  self.all_node_info.values()),
2793
      constants.NV_HYPERVISOR: hypervisors,
2794
      constants.NV_HVPARAMS:
2795
        _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2796
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2797
                                 for node in node_data_list
2798
                                 if not node.offline],
2799
      constants.NV_INSTANCELIST: hypervisors,
2800
      constants.NV_VERSION: None,
2801
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2802
      constants.NV_NODESETUP: None,
2803
      constants.NV_TIME: None,
2804
      constants.NV_MASTERIP: (master_node, master_ip),
2805
      constants.NV_OSLIST: None,
2806
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2807
      constants.NV_USERSCRIPTS: user_scripts,
2808
      }
2809

    
2810
    if vg_name is not None:
2811
      node_verify_param[constants.NV_VGLIST] = None
2812
      node_verify_param[constants.NV_LVLIST] = vg_name
2813
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2814
      node_verify_param[constants.NV_DRBDLIST] = None
2815

    
2816
    if drbd_helper:
2817
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2818

    
2819
    # bridge checks
2820
    # FIXME: this needs to be changed per node-group, not cluster-wide
2821
    bridges = set()
2822
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2823
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2824
      bridges.add(default_nicpp[constants.NIC_LINK])
2825
    for instance in self.my_inst_info.values():
2826
      for nic in instance.nics:
2827
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2828
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2829
          bridges.add(full_nic[constants.NIC_LINK])
2830

    
2831
    if bridges:
2832
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2833

    
2834
    # Build our expected cluster state
2835
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2836
                                                 name=node.name,
2837
                                                 vm_capable=node.vm_capable))
2838
                      for node in node_data_list)
2839

    
2840
    # Gather OOB paths
2841
    oob_paths = []
2842
    for node in self.all_node_info.values():
2843
      path = _SupportsOob(self.cfg, node)
2844
      if path and path not in oob_paths:
2845
        oob_paths.append(path)
2846

    
2847
    if oob_paths:
2848
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2849

    
2850
    for instance in self.my_inst_names:
2851
      inst_config = self.my_inst_info[instance]
2852

    
2853
      for nname in inst_config.all_nodes:
2854
        if nname not in node_image:
2855
          gnode = self.NodeImage(name=nname)
2856
          gnode.ghost = (nname not in self.all_node_info)
2857
          node_image[nname] = gnode
2858

    
2859
      inst_config.MapLVsByNode(node_vol_should)
2860

    
2861
      pnode = inst_config.primary_node
2862
      node_image[pnode].pinst.append(instance)
2863

    
2864
      for snode in inst_config.secondary_nodes:
2865
        nimg = node_image[snode]
2866
        nimg.sinst.append(instance)
2867
        if pnode not in nimg.sbp:
2868
          nimg.sbp[pnode] = []
2869
        nimg.sbp[pnode].append(instance)
2870

    
2871
    # At this point, we have the in-memory data structures complete,
2872
    # except for the runtime information, which we'll gather next
2873

    
2874
    # Due to the way our RPC system works, exact response times cannot be
2875
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2876
    # time before and after executing the request, we can at least have a time
2877
    # window.
2878
    nvinfo_starttime = time.time()
2879
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2880
                                           node_verify_param,
2881
                                           self.cfg.GetClusterName())
2882
    nvinfo_endtime = time.time()
2883

    
2884
    if self.extra_lv_nodes and vg_name is not None:
2885
      extra_lv_nvinfo = \
2886
          self.rpc.call_node_verify(self.extra_lv_nodes,
2887
                                    {constants.NV_LVLIST: vg_name},
2888
                                    self.cfg.GetClusterName())
2889
    else:
2890
      extra_lv_nvinfo = {}
2891

    
2892
    all_drbd_map = self.cfg.ComputeDRBDMap()
2893

    
2894
    feedback_fn("* Gathering disk information (%s nodes)" %
2895
                len(self.my_node_names))
2896
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2897
                                     self.my_inst_info)
2898

    
2899
    feedback_fn("* Verifying configuration file consistency")
2900

    
2901
    # If not all nodes are being checked, we need to make sure the master node
2902
    # and a non-checked vm_capable node are in the list.
2903
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2904
    if absent_nodes:
2905
      vf_nvinfo = all_nvinfo.copy()
2906
      vf_node_info = list(self.my_node_info.values())
2907
      additional_nodes = []
2908
      if master_node not in self.my_node_info:
2909
        additional_nodes.append(master_node)
2910
        vf_node_info.append(self.all_node_info[master_node])
2911
      # Add the first vm_capable node we find which is not included
2912
      for node in absent_nodes:
2913
        nodeinfo = self.all_node_info[node]
2914
        if nodeinfo.vm_capable and not nodeinfo.offline:
2915
          additional_nodes.append(node)
2916
          vf_node_info.append(self.all_node_info[node])
2917
          break
2918
      key = constants.NV_FILELIST
2919
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2920
                                                 {key: node_verify_param[key]},
2921
                                                 self.cfg.GetClusterName()))
2922
    else:
2923
      vf_nvinfo = all_nvinfo
2924
      vf_node_info = self.my_node_info.values()
2925

    
2926
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2927

    
2928
    feedback_fn("* Verifying node status")
2929

    
2930
    refos_img = None
2931

    
2932
    for node_i in node_data_list:
2933
      node = node_i.name
2934
      nimg = node_image[node]
2935

    
2936
      if node_i.offline:
2937
        if verbose:
2938
          feedback_fn("* Skipping offline node %s" % (node,))
2939
        n_offline += 1
2940
        continue
2941

    
2942
      if node == master_node:
2943
        ntype = "master"
2944
      elif node_i.master_candidate:
2945
        ntype = "master candidate"
2946
      elif node_i.drained:
2947
        ntype = "drained"
2948
        n_drained += 1
2949
      else:
2950
        ntype = "regular"
2951
      if verbose:
2952
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2953

    
2954
      msg = all_nvinfo[node].fail_msg
2955
      _ErrorIf(msg, constants.CV_ENODERPC, node, "while contacting node: %s",
2956
               msg)
2957
      if msg:
2958
        nimg.rpc_fail = True
2959
        continue
2960

    
2961
      nresult = all_nvinfo[node].payload
2962

    
2963
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2964
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2965
      self._VerifyNodeNetwork(node_i, nresult)
2966
      self._VerifyNodeUserScripts(node_i, nresult)
2967
      self._VerifyOob(node_i, nresult)
2968

    
2969
      if nimg.vm_capable:
2970
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2971
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2972
                             all_drbd_map)
2973

    
2974
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2975
        self._UpdateNodeInstances(node_i, nresult, nimg)
2976
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2977
        self._UpdateNodeOS(node_i, nresult, nimg)
2978

    
2979
        if not nimg.os_fail:
2980
          if refos_img is None:
2981
            refos_img = nimg
2982
          self._VerifyNodeOS(node_i, nimg, refos_img)
2983
        self._VerifyNodeBridges(node_i, nresult, bridges)
2984

    
2985
        # Check whether all running instancies are primary for the node. (This
2986
        # can no longer be done from _VerifyInstance below, since some of the
2987
        # wrong instances could be from other node groups.)
2988
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2989

    
2990
        for inst in non_primary_inst:
2991
          # FIXME: investigate best way to handle offline insts
2992
          if inst.admin_state == constants.ADMINST_OFFLINE:
2993
            if verbose:
2994
              feedback_fn("* Skipping offline instance %s" % inst.name)
2995
            i_offline += 1
2996
            continue
2997
          test = inst in self.all_inst_info
2998
          _ErrorIf(test, constants.CV_EINSTANCEWRONGNODE, inst,
2999
                   "instance should not run on node %s", node_i.name)
3000
          _ErrorIf(not test, constants.CV_ENODEORPHANINSTANCE, node_i.name,
3001
                   "node is running unknown instance %s", inst)
3002

    
3003
    for node, result in extra_lv_nvinfo.items():
3004
      self._UpdateNodeVolumes(self.all_node_info[node], result.payload,
3005
                              node_image[node], vg_name)
3006

    
3007
    feedback_fn("* Verifying instance status")
3008
    for instance in self.my_inst_names:
3009
      if verbose:
3010
        feedback_fn("* Verifying instance %s" % instance)
3011
      inst_config = self.my_inst_info[instance]
3012
      self._VerifyInstance(instance, inst_config, node_image,
3013
                           instdisk[instance])
3014
      inst_nodes_offline = []
3015

    
3016
      pnode = inst_config.primary_node
3017
      pnode_img = node_image[pnode]
3018
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
3019
               constants.CV_ENODERPC, pnode, "instance %s, connection to"
3020
               " primary node failed", instance)
3021

    
3022
      _ErrorIf(inst_config.admin_state == constants.ADMINST_UP and
3023
               pnode_img.offline,
3024
               constants.CV_EINSTANCEBADNODE, instance,
3025
               "instance is marked as running and lives on offline node %s",
3026
               inst_config.primary_node)
3027

    
3028
      # If the instance is non-redundant we cannot survive losing its primary
3029
      # node, so we are not N+1 compliant. On the other hand we have no disk
3030
      # templates with more than one secondary so that situation is not well
3031
      # supported either.
3032
      # FIXME: does not support file-backed instances
3033
      if not inst_config.secondary_nodes:
3034
        i_non_redundant.append(instance)
3035

    
3036
      _ErrorIf(len(inst_config.secondary_nodes) > 1,
3037
               constants.CV_EINSTANCELAYOUT,
3038
               instance, "instance has multiple secondary nodes: %s",
3039
               utils.CommaJoin(inst_config.secondary_nodes),
3040
               code=self.ETYPE_WARNING)
3041

    
3042
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
3043
        pnode = inst_config.primary_node
3044
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
3045
        instance_groups = {}
3046

    
3047
        for node in instance_nodes:
3048
          instance_groups.setdefault(self.all_node_info[node].group,
3049
                                     []).append(node)
3050

    
3051
        pretty_list = [
3052
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
3053
          # Sort so that we always list the primary node first.
3054
          for group, nodes in sorted(instance_groups.items(),
3055
                                     key=lambda (_, nodes): pnode in nodes,
3056
                                     reverse=True)]
3057

    
3058
        self._ErrorIf(len(instance_groups) > 1,
3059
                      constants.CV_EINSTANCESPLITGROUPS,
3060
                      instance, "instance has primary and secondary nodes in"
3061
                      " different groups: %s", utils.CommaJoin(pretty_list),
3062
                      code=self.ETYPE_WARNING)
3063

    
3064
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
3065
        i_non_a_balanced.append(instance)
3066

    
3067
      for snode in inst_config.secondary_nodes:
3068
        s_img = node_image[snode]
3069
        _ErrorIf(s_img.rpc_fail and not s_img.offline, constants.CV_ENODERPC,
3070
                 snode, "instance %s, connection to secondary node failed",
3071
                 instance)
3072

    
3073
        if s_img.offline:
3074
          inst_nodes_offline.append(snode)
3075

    
3076
      # warn that the instance lives on offline nodes
3077
      _ErrorIf(inst_nodes_offline, constants.CV_EINSTANCEBADNODE, instance,
3078
               "instance has offline secondary node(s) %s",
3079
               utils.CommaJoin(inst_nodes_offline))
3080
      # ... or ghost/non-vm_capable nodes
3081
      for node in inst_config.all_nodes:
3082
        _ErrorIf(node_image[node].ghost, constants.CV_EINSTANCEBADNODE,
3083
                 instance, "instance lives on ghost node %s", node)
3084
        _ErrorIf(not node_image[node].vm_capable, constants.CV_EINSTANCEBADNODE,
3085
                 instance, "instance lives on non-vm_capable node %s", node)
3086

    
3087
    feedback_fn("* Verifying orphan volumes")
3088
    reserved = utils.FieldSet(*cluster.reserved_lvs)
3089

    
3090
    # We will get spurious "unknown volume" warnings if any node of this group
3091
    # is secondary for an instance whose primary is in another group. To avoid
3092
    # them, we find these instances and add their volumes to node_vol_should.
3093
    for inst in self.all_inst_info.values():
3094
      for secondary in inst.secondary_nodes:
3095
        if (secondary in self.my_node_info
3096
            and inst.name not in self.my_inst_info):
3097
          inst.MapLVsByNode(node_vol_should)
3098
          break
3099

    
3100
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
3101

    
3102
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
3103
      feedback_fn("* Verifying N+1 Memory redundancy")
3104
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
3105

    
3106
    feedback_fn("* Other Notes")
3107
    if i_non_redundant:
3108
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
3109
                  % len(i_non_redundant))
3110

    
3111
    if i_non_a_balanced:
3112
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
3113
                  % len(i_non_a_balanced))
3114

    
3115
    if i_offline:
3116
      feedback_fn("  - NOTICE: %d offline instance(s) found." % i_offline)
3117

    
3118
    if n_offline:
3119
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
3120

    
3121
    if n_drained:
3122
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
3123

    
3124
    return not self.bad
3125

    
3126
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
3127
    """Analyze the post-hooks' result
3128

3129
    This method analyses the hook result, handles it, and sends some
3130
    nicely-formatted feedback back to the user.
3131

3132
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
3133
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
3134
    @param hooks_results: the results of the multi-node hooks rpc call
3135
    @param feedback_fn: function used send feedback back to the caller
3136
    @param lu_result: previous Exec result
3137
    @return: the new Exec result, based on the previous result
3138
        and hook results
3139

3140
    """
3141
    # We only really run POST phase hooks, only for non-empty groups,
3142
    # and are only interested in their results
3143
    if not self.my_node_names:
3144
      # empty node group
3145
      pass
3146
    elif phase == constants.HOOKS_PHASE_POST:
3147
      # Used to change hooks' output to proper indentation
3148
      feedback_fn("* Hooks Results")
3149
      assert hooks_results, "invalid result from hooks"
3150

    
3151
      for node_name in hooks_results:
3152
        res = hooks_results[node_name]
3153
        msg = res.fail_msg
3154
        test = msg and not res.offline
3155
        self._ErrorIf(test, constants.CV_ENODEHOOKS, node_name,
3156
                      "Communication failure in hooks execution: %s", msg)
3157
        if res.offline or msg:
3158
          # No need to investigate payload if node is offline or gave
3159
          # an error.
3160
          continue
3161
        for script, hkr, output in res.payload:
3162
          test = hkr == constants.HKR_FAIL
3163
          self._ErrorIf(test, constants.CV_ENODEHOOKS, node_name,
3164
                        "Script %s failed, output:", script)
3165
          if test:
3166
            output = self._HOOKS_INDENT_RE.sub("      ", output)
3167
            feedback_fn("%s" % output)
3168
            lu_result = False
3169

    
3170
    return lu_result
3171

    
3172

    
3173
class LUClusterVerifyDisks(NoHooksLU):
3174
  """Verifies the cluster disks status.
3175

3176
  """
3177
  REQ_BGL = False
3178

    
3179
  def ExpandNames(self):
3180
    self.share_locks = _ShareAll()
3181
    self.needed_locks = {
3182
      locking.LEVEL_NODEGROUP: locking.ALL_SET,
3183
      }
3184

    
3185
  def Exec(self, feedback_fn):
3186
    group_names = self.owned_locks(locking.LEVEL_NODEGROUP)
3187

    
3188
    # Submit one instance of L{opcodes.OpGroupVerifyDisks} per node group
3189
    return ResultWithJobs([[opcodes.OpGroupVerifyDisks(group_name=group)]
3190
                           for group in group_names])
3191

    
3192

    
3193
class LUGroupVerifyDisks(NoHooksLU):
3194
  """Verifies the status of all disks in a node group.
3195

3196
  """
3197
  REQ_BGL = False
3198

    
3199
  def ExpandNames(self):
3200
    # Raises errors.OpPrereqError on its own if group can't be found
3201
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
3202

    
3203
    self.share_locks = _ShareAll()
3204
    self.needed_locks = {
3205
      locking.LEVEL_INSTANCE: [],
3206
      locking.LEVEL_NODEGROUP: [],
3207
      locking.LEVEL_NODE: [],
3208
      }
3209

    
3210
  def DeclareLocks(self, level):
3211
    if level == locking.LEVEL_INSTANCE:
3212
      assert not self.needed_locks[locking.LEVEL_INSTANCE]
3213

    
3214
      # Lock instances optimistically, needs verification once node and group
3215
      # locks have been acquired
3216
      self.needed_locks[locking.LEVEL_INSTANCE] = \
3217
        self.cfg.GetNodeGroupInstances(self.group_uuid)
3218

    
3219
    elif level == locking.LEVEL_NODEGROUP:
3220
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
3221

    
3222
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
3223
        set([self.group_uuid] +
3224
            # Lock all groups used by instances optimistically; this requires
3225
            # going via the node before it's locked, requiring verification
3226
            # later on
3227
            [group_uuid
3228
             for instance_name in self.owned_locks(locking.LEVEL_INSTANCE)
3229
             for group_uuid in self.cfg.GetInstanceNodeGroups(instance_name)])
3230

    
3231
    elif level == locking.LEVEL_NODE:
3232
      # This will only lock the nodes in the group to be verified which contain
3233
      # actual instances
3234
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
3235
      self._LockInstancesNodes()
3236

    
3237
      # Lock all nodes in group to be verified
3238
      assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
3239
      member_nodes = self.cfg.GetNodeGroup(self.group_uuid).members
3240
      self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
3241

    
3242
  def CheckPrereq(self):
3243
    owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
3244
    owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
3245
    owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
3246

    
3247
    assert self.group_uuid in owned_groups
3248

    
3249
    # Check if locked instances are still correct
3250
    _CheckNodeGroupInstances(self.cfg, self.group_uuid, owned_instances)
3251

    
3252
    # Get instance information
3253
    self.instances = dict(self.cfg.GetMultiInstanceInfo(owned_instances))
3254

    
3255
    # Check if node groups for locked instances are still correct
3256
    for (instance_name, inst) in self.instances.items():
3257
      assert owned_nodes.issuperset(inst.all_nodes), \
3258
        "Instance %s's nodes changed while we kept the lock" % instance_name
3259

    
3260
      inst_groups = _CheckInstanceNodeGroups(self.cfg, instance_name,
3261
                                             owned_groups)
3262

    
3263
      assert self.group_uuid in inst_groups, \
3264
        "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
3265

    
3266
  def Exec(self, feedback_fn):
3267
    """Verify integrity of cluster disks.
3268

3269
    @rtype: tuple of three items
3270
    @return: a tuple of (dict of node-to-node_error, list of instances
3271
        which need activate-disks, dict of instance: (node, volume) for
3272
        missing volumes
3273

3274
    """
3275
    res_nodes = {}
3276
    res_instances = set()
3277
    res_missing = {}
3278

    
3279
    nv_dict = _MapInstanceDisksToNodes([inst
3280
            for inst in self.instances.values()
3281
            if inst.admin_state == constants.ADMINST_UP])
3282

    
3283
    if nv_dict:
3284
      nodes = utils.NiceSort(set(self.owned_locks(locking.LEVEL_NODE)) &
3285
                             set(self.cfg.GetVmCapableNodeList()))
3286

    
3287
      node_lvs = self.rpc.call_lv_list(nodes, [])
3288

    
3289
      for (node, node_res) in node_lvs.items():
3290
        if node_res.offline:
3291
          continue
3292

    
3293
        msg = node_res.fail_msg
3294
        if msg:
3295
          logging.warning("Error enumerating LVs on node %s: %s", node, msg)
3296
          res_nodes[node] = msg
3297
          continue
3298

    
3299
        for lv_name, (_, _, lv_online) in node_res.payload.items():
3300
          inst = nv_dict.pop((node, lv_name), None)
3301
          if not (lv_online or inst is None):
3302
            res_instances.add(inst)
3303

    
3304
      # any leftover items in nv_dict are missing LVs, let's arrange the data
3305
      # better
3306
      for key, inst in nv_dict.iteritems():
3307
        res_missing.setdefault(inst, []).append(list(key))
3308

    
3309
    return (res_nodes, list(res_instances), res_missing)
3310

    
3311

    
3312
class LUClusterRepairDiskSizes(NoHooksLU):
3313
  """Verifies the cluster disks sizes.
3314

3315
  """
3316
  REQ_BGL = False
3317

    
3318
  def ExpandNames(self):
3319
    if self.op.instances:
3320
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
3321
      self.needed_locks = {
3322
        locking.LEVEL_NODE_RES: [],
3323
        locking.LEVEL_INSTANCE: self.wanted_names,
3324
        }
3325
      self.recalculate_locks[locking.LEVEL_NODE_RES] = constants.LOCKS_REPLACE
3326
    else:
3327
      self.wanted_names = None
3328
      self.needed_locks = {
3329
        locking.LEVEL_NODE_RES: locking.ALL_SET,
3330
        locking.LEVEL_INSTANCE: locking.ALL_SET,
3331
        }
3332
    self.share_locks = {
3333
      locking.LEVEL_NODE_RES: 1,
3334
      locking.LEVEL_INSTANCE: 0,
3335
      }
3336

    
3337
  def DeclareLocks(self, level):
3338
    if level == locking.LEVEL_NODE_RES and self.wanted_names is not None:
3339
      self._LockInstancesNodes(primary_only=True, level=level)
3340

    
3341
  def CheckPrereq(self):
3342
    """Check prerequisites.
3343

3344
    This only checks the optional instance list against the existing names.
3345

3346
    """
3347
    if self.wanted_names is None:
3348
      self.wanted_names = self.owned_locks(locking.LEVEL_INSTANCE)
3349

    
3350
    self.wanted_instances = \
3351
        map(compat.snd, self.cfg.GetMultiInstanceInfo(self.wanted_names))
3352

    
3353
  def _EnsureChildSizes(self, disk):
3354
    """Ensure children of the disk have the needed disk size.
3355

3356
    This is valid mainly for DRBD8 and fixes an issue where the
3357
    children have smaller disk size.
3358

3359
    @param disk: an L{ganeti.objects.Disk} object
3360

3361
    """
3362
    if disk.dev_type == constants.LD_DRBD8:
3363
      assert disk.children, "Empty children for DRBD8?"
3364
      fchild = disk.children[0]
3365
      mismatch = fchild.size < disk.size
3366
      if mismatch:
3367
        self.LogInfo("Child disk has size %d, parent %d, fixing",
3368
                     fchild.size, disk.size)
3369
        fchild.size = disk.size
3370

    
3371
      # and we recurse on this child only, not on the metadev
3372
      return self._EnsureChildSizes(fchild) or mismatch
3373
    else:
3374
      return False
3375

    
3376
  def Exec(self, feedback_fn):
3377
    """Verify the size of cluster disks.
3378

3379
    """
3380
    # TODO: check child disks too
3381
    # TODO: check differences in size between primary/secondary nodes
3382
    per_node_disks = {}
3383
    for instance in self.wanted_instances:
3384
      pnode = instance.primary_node
3385
      if pnode not in per_node_disks:
3386
        per_node_disks[pnode] = []
3387
      for idx, disk in enumerate(instance.disks):
3388
        per_node_disks[pnode].append((instance, idx, disk))
3389

    
3390
    assert not (frozenset(per_node_disks.keys()) -
3391
                self.owned_locks(locking.LEVEL_NODE_RES)), \
3392
      "Not owning correct locks"
3393
    assert not self.owned_locks(locking.LEVEL_NODE)
3394

    
3395
    changed = []
3396
    for node, dskl in per_node_disks.items():
3397
      newl = [v[2].Copy() for v in dskl]
3398
      for dsk in newl:
3399
        self.cfg.SetDiskID(dsk, node)
3400
      result = self.rpc.call_blockdev_getsize(node, newl)
3401
      if result.fail_msg:
3402
        self.LogWarning("Failure in blockdev_getsize call to node"
3403
                        " %s, ignoring", node)
3404
        continue
3405
      if len(result.payload) != len(dskl):
3406
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
3407
                        " result.payload=%s", node, len(dskl), result.payload)
3408
        self.LogWarning("Invalid result from node %s, ignoring node results",
3409
                        node)
3410
        continue
3411
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
3412
        if size is None:
3413
          self.LogWarning("Disk %d of instance %s did not return size"
3414
                          " information, ignoring", idx, instance.name)
3415
          continue
3416
        if not isinstance(size, (int, long)):
3417
          self.LogWarning("Disk %d of instance %s did not return valid"
3418
                          " size information, ignoring", idx, instance.name)
3419
          continue
3420
        size = size >> 20
3421
        if size != disk.size:
3422
          self.LogInfo("Disk %d of instance %s has mismatched size,"
3423
                       " correcting: recorded %d, actual %d", idx,
3424
                       instance.name, disk.size, size)
3425
          disk.size = size
3426
          self.cfg.Update(instance, feedback_fn)
3427
          changed.append((instance.name, idx, size))
3428
        if self._EnsureChildSizes(disk):
3429
          self.cfg.Update(instance, feedback_fn)
3430
          changed.append((instance.name, idx, disk.size))
3431
    return changed
3432

    
3433

    
3434
class LUClusterRename(LogicalUnit):
3435
  """Rename the cluster.
3436

3437
  """
3438
  HPATH = "cluster-rename"
3439
  HTYPE = constants.HTYPE_CLUSTER
3440

    
3441
  def BuildHooksEnv(self):
3442
    """Build hooks env.
3443

3444
    """
3445
    return {
3446
      "OP_TARGET": self.cfg.GetClusterName(),
3447
      "NEW_NAME": self.op.name,
3448
      }
3449

    
3450
  def BuildHooksNodes(self):
3451
    """Build hooks nodes.
3452

3453
    """
3454
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
3455

    
3456
  def CheckPrereq(self):
3457
    """Verify that the passed name is a valid one.
3458

3459
    """
3460
    hostname = netutils.GetHostname(name=self.op.name,
3461
                                    family=self.cfg.GetPrimaryIPFamily())
3462

    
3463
    new_name = hostname.name
3464
    self.ip = new_ip = hostname.ip
3465
    old_name = self.cfg.GetClusterName()
3466
    old_ip = self.cfg.GetMasterIP()
3467
    if new_name == old_name and new_ip == old_ip:
3468
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
3469
                                 " cluster has changed",
3470
                                 errors.ECODE_INVAL)
3471
    if new_ip != old_ip:
3472
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
3473
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
3474
                                   " reachable on the network" %
3475
                                   new_ip, errors.ECODE_NOTUNIQUE)
3476

    
3477
    self.op.name = new_name
3478

    
3479
  def Exec(self, feedback_fn):
3480
    """Rename the cluster.
3481

3482
    """
3483
    clustername = self.op.name
3484
    new_ip = self.ip
3485

    
3486
    # shutdown the master IP
3487
    master_params = self.cfg.GetMasterNetworkParameters()
3488
    ems = self.cfg.GetUseExternalMipScript()
3489
    result = self.rpc.call_node_deactivate_master_ip(master_params.name,
3490
                                                     master_params, ems)
3491
    result.Raise("Could not disable the master role")
3492

    
3493
    try:
3494
      cluster = self.cfg.GetClusterInfo()
3495
      cluster.cluster_name = clustername
3496
      cluster.master_ip = new_ip
3497
      self.cfg.Update(cluster, feedback_fn)
3498

    
3499
      # update the known hosts file
3500
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
3501
      node_list = self.cfg.GetOnlineNodeList()
3502
      try:
3503
        node_list.remove(master_params.name)
3504
      except ValueError:
3505
        pass
3506
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3507
    finally:
3508
      master_params.ip = new_ip
3509
      result = self.rpc.call_node_activate_master_ip(master_params.name,
3510
                                                     master_params, ems)
3511
      msg = result.fail_msg
3512
      if msg:
3513
        self.LogWarning("Could not re-enable the master role on"
3514
                        " the master, please restart manually: %s", msg)
3515

    
3516
    return clustername
3517

    
3518

    
3519
def _ValidateNetmask(cfg, netmask):
3520
  """Checks if a netmask is valid.
3521

3522
  @type cfg: L{config.ConfigWriter}
3523
  @param cfg: The cluster configuration
3524
  @type netmask: int
3525
  @param netmask: the netmask to be verified
3526
  @raise errors.OpPrereqError: if the validation fails
3527

3528
  """
3529
  ip_family = cfg.GetPrimaryIPFamily()
3530
  try:
3531
    ipcls = netutils.IPAddress.GetClassFromIpFamily(ip_family)
3532
  except errors.ProgrammerError:
3533
    raise errors.OpPrereqError("Invalid primary ip family: %s." %
3534
                               ip_family)
3535
  if not ipcls.ValidateNetmask(netmask):
3536
    raise errors.OpPrereqError("CIDR netmask (%s) not valid" %
3537
                                (netmask))
3538

    
3539

    
3540
class LUClusterSetParams(LogicalUnit):
3541
  """Change the parameters of the cluster.
3542

3543
  """
3544
  HPATH = "cluster-modify"
3545
  HTYPE = constants.HTYPE_CLUSTER
3546
  REQ_BGL = False
3547

    
3548
  def CheckArguments(self):
3549
    """Check parameters
3550

3551
    """
3552
    if self.op.uid_pool:
3553
      uidpool.CheckUidPool(self.op.uid_pool)
3554

    
3555
    if self.op.add_uids:
3556
      uidpool.CheckUidPool(self.op.add_uids)
3557

    
3558
    if self.op.remove_uids:
3559
      uidpool.CheckUidPool(self.op.remove_uids)
3560

    
3561
    if self.op.master_netmask is not None:
3562
      _ValidateNetmask(self.cfg, self.op.master_netmask)
3563

    
3564
    if self.op.diskparams:
3565
      for dt_params in self.op.diskparams.values():
3566
        utils.ForceDictType(dt_params, constants.DISK_DT_TYPES)
3567

    
3568
  def ExpandNames(self):
3569
    # FIXME: in the future maybe other cluster params won't require checking on
3570
    # all nodes to be modified.
3571
    self.needed_locks = {
3572
      locking.LEVEL_NODE: locking.ALL_SET,
3573
    }
3574
    self.share_locks[locking.LEVEL_NODE] = 1
3575

    
3576
  def BuildHooksEnv(self):
3577
    """Build hooks env.
3578

3579
    """
3580
    return {
3581
      "OP_TARGET": self.cfg.GetClusterName(),
3582
      "NEW_VG_NAME": self.op.vg_name,
3583
      }
3584

    
3585
  def BuildHooksNodes(self):
3586
    """Build hooks nodes.
3587

3588
    """
3589
    mn = self.cfg.GetMasterNode()
3590
    return ([mn], [mn])
3591

    
3592
  def CheckPrereq(self):
3593
    """Check prerequisites.
3594

3595
    This checks whether the given params don't conflict and
3596
    if the given volume group is valid.
3597

3598
    """
3599
    if self.op.vg_name is not None and not self.op.vg_name:
3600
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3601
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3602
                                   " instances exist", errors.ECODE_INVAL)
3603

    
3604
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
3605
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3606
        raise errors.OpPrereqError("Cannot disable drbd helper while"
3607
                                   " drbd-based instances exist",
3608
                                   errors.ECODE_INVAL)
3609

    
3610
    node_list = self.owned_locks(locking.LEVEL_NODE)
3611

    
3612
    # if vg_name not None, checks given volume group on all nodes
3613
    if self.op.vg_name:
3614
      vglist = self.rpc.call_vg_list(node_list)
3615
      for node in node_list:
3616
        msg = vglist[node].fail_msg
3617
        if msg:
3618
          # ignoring down node
3619
          self.LogWarning("Error while gathering data on node %s"
3620
                          " (ignoring node): %s", node, msg)
3621
          continue
3622
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3623
                                              self.op.vg_name,
3624
                                              constants.MIN_VG_SIZE)
3625
        if vgstatus:
3626
          raise errors.OpPrereqError("Error on node '%s': %s" %
3627
                                     (node, vgstatus), errors.ECODE_ENVIRON)
3628

    
3629
    if self.op.drbd_helper:
3630
      # checks given drbd helper on all nodes
3631
      helpers = self.rpc.call_drbd_helper(node_list)
3632
      for (node, ninfo) in self.cfg.GetMultiNodeInfo(node_list):
3633
        if ninfo.offline:
3634
          self.LogInfo("Not checking drbd helper on offline node %s", node)
3635
          continue
3636
        msg = helpers[node].fail_msg
3637
        if msg:
3638
          raise errors.OpPrereqError("Error checking drbd helper on node"
3639
                                     " '%s': %s" % (node, msg),
3640
                                     errors.ECODE_ENVIRON)
3641
        node_helper = helpers[node].payload
3642
        if node_helper != self.op.drbd_helper:
3643
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3644
                                     (node, node_helper), errors.ECODE_ENVIRON)
3645

    
3646
    self.cluster = cluster = self.cfg.GetClusterInfo()
3647
    # validate params changes
3648
    if self.op.beparams:
3649
      objects.UpgradeBeParams(self.op.beparams)
3650
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3651
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3652

    
3653
    if self.op.ndparams:
3654
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3655
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3656

    
3657
      # TODO: we need a more general way to handle resetting
3658
      # cluster-level parameters to default values
3659
      if self.new_ndparams["oob_program"] == "":
3660
        self.new_ndparams["oob_program"] = \
3661
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3662

    
3663
    if self.op.nicparams:
3664
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3665
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3666
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3667
      nic_errors = []
3668

    
3669
      # check all instances for consistency
3670
      for instance in self.cfg.GetAllInstancesInfo().values():
3671
        for nic_idx, nic in enumerate(instance.nics):
3672
          params_copy = copy.deepcopy(nic.nicparams)
3673
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3674

    
3675
          # check parameter syntax
3676
          try:
3677
            objects.NIC.CheckParameterSyntax(params_filled)
3678
          except errors.ConfigurationError, err:
3679
            nic_errors.append("Instance %s, nic/%d: %s" %
3680
                              (instance.name, nic_idx, err))
3681

    
3682
          # if we're moving instances to routed, check that they have an ip
3683
          target_mode = params_filled[constants.NIC_MODE]
3684
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3685
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3686
                              " address" % (instance.name, nic_idx))
3687
      if nic_errors:
3688
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3689
                                   "\n".join(nic_errors))
3690

    
3691
    # hypervisor list/parameters
3692
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3693
    if self.op.hvparams:
3694
      for hv_name, hv_dict in self.op.hvparams.items():
3695
        if hv_name not in self.new_hvparams:
3696
          self.new_hvparams[hv_name] = hv_dict
3697
        else:
3698
          self.new_hvparams[hv_name].update(hv_dict)
3699

    
3700
    # disk template parameters
3701
    self.new_diskparams = objects.FillDict(cluster.diskparams, {})
3702
    if self.op.diskparams:
3703
      for dt_name, dt_params in self.op.diskparams.items():
3704
        if dt_name not in self.op.diskparams:
3705
          self.new_diskparams[dt_name] = dt_params
3706
        else:
3707
          self.new_diskparams[dt_name].update(dt_params)
3708

    
3709
    # os hypervisor parameters
3710
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3711
    if self.op.os_hvp:
3712
      for os_name, hvs in self.op.os_hvp.items():
3713
        if os_name not in self.new_os_hvp:
3714
          self.new_os_hvp[os_name] = hvs
3715
        else:
3716
          for hv_name, hv_dict in hvs.items():
3717
            if hv_name not in self.new_os_hvp[os_name]:
3718
              self.new_os_hvp[os_name][hv_name] = hv_dict
3719
            else:
3720
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3721

    
3722
    # os parameters
3723
    self.new_osp = objects.FillDict(cluster.osparams, {})
3724
    if self.op.osparams:
3725
      for os_name, osp in self.op.osparams.items():
3726
        if os_name not in self.new_osp:
3727
          self.new_osp[os_name] = {}
3728

    
3729
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3730
                                                  use_none=True)
3731

    
3732
        if not self.new_osp[os_name]:
3733
          # we removed all parameters
3734
          del self.new_osp[os_name]
3735
        else:
3736
          # check the parameter validity (remote check)
3737
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3738
                         os_name, self.new_osp[os_name])
3739

    
3740
    # changes to the hypervisor list
3741
    if self.op.enabled_hypervisors is not None:
3742
      self.hv_list = self.op.enabled_hypervisors
3743
      for hv in self.hv_list:
3744
        # if the hypervisor doesn't already exist in the cluster
3745
        # hvparams, we initialize it to empty, and then (in both
3746
        # cases) we make sure to fill the defaults, as we might not
3747
        # have a complete defaults list if the hypervisor wasn't
3748
        # enabled before
3749
        if hv not in new_hvp:
3750
          new_hvp[hv] = {}
3751
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3752
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3753
    else:
3754
      self.hv_list = cluster.enabled_hypervisors
3755

    
3756
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3757
      # either the enabled list has changed, or the parameters have, validate
3758
      for hv_name, hv_params in self.new_hvparams.items():
3759
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3760
            (self.op.enabled_hypervisors and
3761
             hv_name in self.op.enabled_hypervisors)):
3762
          # either this is a new hypervisor, or its parameters have changed
3763
          hv_class = hypervisor.GetHypervisor(hv_name)
3764
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3765
          hv_class.CheckParameterSyntax(hv_params)
3766
          _CheckHVParams(self, node_list, hv_name, hv_params)
3767

    
3768
    if self.op.os_hvp:
3769
      # no need to check any newly-enabled hypervisors, since the
3770
      # defaults have already been checked in the above code-block
3771
      for os_name, os_hvp in self.new_os_hvp.items():
3772
        for hv_name, hv_params in os_hvp.items():
3773
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3774
          # we need to fill in the new os_hvp on top of the actual hv_p
3775
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3776
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3777
          hv_class = hypervisor.GetHypervisor(hv_name)
3778
          hv_class.CheckParameterSyntax(new_osp)
3779
          _CheckHVParams(self, node_list, hv_name, new_osp)
3780

    
3781
    if self.op.default_iallocator:
3782
      alloc_script = utils.FindFile(self.op.default_iallocator,
3783
                                    constants.IALLOCATOR_SEARCH_PATH,
3784
                                    os.path.isfile)
3785
      if alloc_script is None:
3786
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3787
                                   " specified" % self.op.default_iallocator,
3788
                                   errors.ECODE_INVAL)
3789

    
3790
  def Exec(self, feedback_fn):
3791
    """Change the parameters of the cluster.
3792

3793
    """
3794
    if self.op.vg_name is not None:
3795
      new_volume = self.op.vg_name
3796
      if not new_volume:
3797
        new_volume = None
3798
      if new_volume != self.cfg.GetVGName():
3799
        self.cfg.SetVGName(new_volume)
3800
      else:
3801
        feedback_fn("Cluster LVM configuration already in desired"
3802
                    " state, not changing")
3803
    if self.op.drbd_helper is not None:
3804
      new_helper = self.op.drbd_helper
3805
      if not new_helper:
3806
        new_helper = None
3807
      if new_helper != self.cfg.GetDRBDHelper():
3808
        self.cfg.SetDRBDHelper(new_helper)
3809
      else:
3810
        feedback_fn("Cluster DRBD helper already in desired state,"
3811
                    " not changing")
3812
    if self.op.hvparams:
3813
      self.cluster.hvparams = self.new_hvparams
3814
    if self.op.os_hvp:
3815
      self.cluster.os_hvp = self.new_os_hvp
3816
    if self.op.enabled_hypervisors is not None:
3817
      self.cluster.hvparams = self.new_hvparams
3818
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3819
    if self.op.beparams:
3820
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3821
    if self.op.nicparams:
3822
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3823
    if self.op.osparams:
3824
      self.cluster.osparams = self.new_osp
3825
    if self.op.ndparams:
3826
      self.cluster.ndparams = self.new_ndparams
3827
    if self.op.diskparams:
3828
      self.cluster.diskparams = self.new_diskparams
3829

    
3830
    if self.op.candidate_pool_size is not None:
3831
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3832
      # we need to update the pool size here, otherwise the save will fail
3833
      _AdjustCandidatePool(self, [])
3834

    
3835
    if self.op.maintain_node_health is not None:
3836
      if self.op.maintain_node_health and not constants.ENABLE_CONFD:
3837
        feedback_fn("Note: CONFD was disabled at build time, node health"
3838
                    " maintenance is not useful (still enabling it)")
3839
      self.cluster.maintain_node_health = self.op.maintain_node_health
3840

    
3841
    if self.op.prealloc_wipe_disks is not None:
3842
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3843

    
3844
    if self.op.add_uids is not None:
3845
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3846

    
3847
    if self.op.remove_uids is not None:
3848
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3849

    
3850
    if self.op.uid_pool is not None:
3851
      self.cluster.uid_pool = self.op.uid_pool
3852

    
3853
    if self.op.default_iallocator is not None:
3854
      self.cluster.default_iallocator = self.op.default_iallocator
3855

    
3856
    if self.op.reserved_lvs is not None:
3857
      self.cluster.reserved_lvs = self.op.reserved_lvs
3858

    
3859
    if self.op.use_external_mip_script is not None:
3860
      self.cluster.use_external_mip_script = self.op.use_external_mip_script
3861

    
3862
    def helper_os(aname, mods, desc):
3863
      desc += " OS list"
3864
      lst = getattr(self.cluster, aname)
3865
      for key, val in mods:
3866
        if key == constants.DDM_ADD:
3867
          if val in lst:
3868
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3869
          else:
3870
            lst.append(val)
3871
        elif key == constants.DDM_REMOVE:
3872
          if val in lst:
3873
            lst.remove(val)
3874
          else:
3875
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3876
        else:
3877
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3878

    
3879
    if self.op.hidden_os:
3880
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3881

    
3882
    if self.op.blacklisted_os:
3883
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3884

    
3885
    if self.op.master_netdev:
3886
      master_params = self.cfg.GetMasterNetworkParameters()
3887
      ems = self.cfg.GetUseExternalMipScript()
3888
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3889
                  self.cluster.master_netdev)
3890
      result = self.rpc.call_node_deactivate_master_ip(master_params.name,
3891
                                                       master_params, ems)
3892
      result.Raise("Could not disable the master ip")
3893
      feedback_fn("Changing master_netdev from %s to %s" %
3894
                  (master_params.netdev, self.op.master_netdev))
3895
      self.cluster.master_netdev = self.op.master_netdev
3896

    
3897
    if self.op.master_netmask:
3898
      master_params = self.cfg.GetMasterNetworkParameters()
3899
      feedback_fn("Changing master IP netmask to %s" % self.op.master_netmask)
3900
      result = self.rpc.call_node_change_master_netmask(master_params.name,
3901
                                                        master_params.netmask,
3902
                                                        self.op.master_netmask,
3903
                                                        master_params.ip,
3904
                                                        master_params.netdev)
3905
      if result.fail_msg:
3906
        msg = "Could not change the master IP netmask: %s" % result.fail_msg
3907
        feedback_fn(msg)
3908

    
3909
      self.cluster.master_netmask = self.op.master_netmask
3910

    
3911
    self.cfg.Update(self.cluster, feedback_fn)
3912

    
3913
    if self.op.master_netdev:
3914
      master_params = self.cfg.GetMasterNetworkParameters()
3915
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3916
                  self.op.master_netdev)
3917
      ems = self.cfg.GetUseExternalMipScript()
3918
      result = self.rpc.call_node_activate_master_ip(master_params.name,
3919
                                                     master_params, ems)
3920
      if result.fail_msg:
3921
        self.LogWarning("Could not re-enable the master ip on"
3922
                        " the master, please restart manually: %s",
3923
                        result.fail_msg)
3924

    
3925

    
3926
def _UploadHelper(lu, nodes, fname):
3927
  """Helper for uploading a file and showing warnings.
3928

3929
  """
3930
  if os.path.exists(fname):
3931
    result = lu.rpc.call_upload_file(nodes, fname)
3932
    for to_node, to_result in result.items():
3933
      msg = to_result.fail_msg
3934
      if msg:
3935
        msg = ("Copy of file %s to node %s failed: %s" %
3936
               (fname, to_node, msg))
3937
        lu.proc.LogWarning(msg)
3938

    
3939

    
3940
def _ComputeAncillaryFiles(cluster, redist):
3941
  """Compute files external to Ganeti which need to be consistent.
3942

3943
  @type redist: boolean
3944
  @param redist: Whether to include files which need to be redistributed
3945

3946
  """
3947
  # Compute files for all nodes
3948
  files_all = set([
3949
    constants.SSH_KNOWN_HOSTS_FILE,
3950
    constants.CONFD_HMAC_KEY,
3951
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3952
    constants.SPICE_CERT_FILE,
3953
    constants.SPICE_CACERT_FILE,
3954
    constants.RAPI_USERS_FILE,
3955
    ])
3956

    
3957
  if not redist:
3958
    files_all.update(constants.ALL_CERT_FILES)
3959
    files_all.update(ssconf.SimpleStore().GetFileList())
3960
  else:
3961
    # we need to ship at least the RAPI certificate
3962
    files_all.add(constants.RAPI_CERT_FILE)
3963

    
3964
  if cluster.modify_etc_hosts:
3965
    files_all.add(constants.ETC_HOSTS)
3966

    
3967
  # Files which are optional, these must:
3968
  # - be present in one other category as well
3969
  # - either exist or not exist on all nodes of that category (mc, vm all)
3970
  files_opt = set([
3971
    constants.RAPI_USERS_FILE,
3972
    ])
3973

    
3974
  # Files which should only be on master candidates
3975
  files_mc = set()
3976

    
3977
  if not redist:
3978
    files_mc.add(constants.CLUSTER_CONF_FILE)
3979

    
3980
    # FIXME: this should also be replicated but Ganeti doesn't support files_mc
3981
    # replication
3982
    files_mc.add(constants.DEFAULT_MASTER_SETUP_SCRIPT)
3983

    
3984
  # Files which should only be on VM-capable nodes
3985
  files_vm = set(filename
3986
    for hv_name in cluster.enabled_hypervisors
3987
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles()[0])
3988

    
3989
  files_opt |= set(filename
3990
    for hv_name in cluster.enabled_hypervisors
3991
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles()[1])
3992

    
3993
  # Filenames in each category must be unique
3994
  all_files_set = files_all | files_mc | files_vm
3995
  assert (len(all_files_set) ==
3996
          sum(map(len, [files_all, files_mc, files_vm]))), \
3997
         "Found file listed in more than one file list"
3998

    
3999
  # Optional files must be present in one other category
4000
  assert all_files_set.issuperset(files_opt), \
4001
         "Optional file not in a different required list"
4002

    
4003
  return (files_all, files_opt, files_mc, files_vm)
4004

    
4005

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

4009
  ConfigWriter takes care of distributing the config and ssconf files, but
4010
  there are more files which should be distributed to all nodes. This function
4011
  makes sure those are copied.
4012

4013
  @param lu: calling logical unit
4014
  @param additional_nodes: list of nodes not in the config to distribute to
4015
  @type additional_vm: boolean
4016
  @param additional_vm: whether the additional nodes are vm-capable or not
4017

4018
  """
4019
  # Gather target nodes
4020
  cluster = lu.cfg.GetClusterInfo()
4021
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
4022

    
4023
  online_nodes = lu.cfg.GetOnlineNodeList()
4024
  vm_nodes = lu.cfg.GetVmCapableNodeList()
4025

    
4026
  if additional_nodes is not None:
4027
    online_nodes.extend(additional_nodes)
4028
    if additional_vm:
4029
      vm_nodes.extend(additional_nodes)
4030

    
4031
  # Never distribute to master node
4032
  for nodelist in [online_nodes, vm_nodes]:
4033
    if master_info.name in nodelist:
4034
      nodelist.remove(master_info.name)
4035

    
4036
  # Gather file lists
4037
  (files_all, _, files_mc, files_vm) = \
4038
    _ComputeAncillaryFiles(cluster, True)
4039

    
4040
  # Never re-distribute configuration file from here
4041
  assert not (constants.CLUSTER_CONF_FILE in files_all or
4042
              constants.CLUSTER_CONF_FILE in files_vm)
4043
  assert not files_mc, "Master candidates not handled in this function"
4044

    
4045
  filemap = [
4046
    (online_nodes, files_all),
4047
    (vm_nodes, files_vm),
4048
    ]
4049

    
4050
  # Upload the files
4051
  for (node_list, files) in filemap:
4052
    for fname in files:
4053
      _UploadHelper(lu, node_list, fname)
4054

    
4055

    
4056
class LUClusterRedistConf(NoHooksLU):
4057
  """Force the redistribution of cluster configuration.
4058

4059
  This is a very simple LU.
4060

4061
  """
4062
  REQ_BGL = False
4063

    
4064
  def ExpandNames(self):
4065
    self.needed_locks = {
4066
      locking.LEVEL_NODE: locking.ALL_SET,
4067
    }
4068
    self.share_locks[locking.LEVEL_NODE] = 1
4069

    
4070
  def Exec(self, feedback_fn):
4071
    """Redistribute the configuration.
4072

4073
    """
4074
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
4075
    _RedistributeAncillaryFiles(self)
4076

    
4077

    
4078
class LUClusterActivateMasterIp(NoHooksLU):
4079
  """Activate the master IP on the master node.
4080

4081
  """
4082
  def Exec(self, feedback_fn):
4083
    """Activate the master IP.
4084

4085
    """
4086
    master_params = self.cfg.GetMasterNetworkParameters()
4087
    ems = self.cfg.GetUseExternalMipScript()
4088
    result = self.rpc.call_node_activate_master_ip(master_params.name,
4089
                                                   master_params, ems)
4090
    result.Raise("Could not activate the master IP")
4091

    
4092

    
4093
class LUClusterDeactivateMasterIp(NoHooksLU):
4094
  """Deactivate the master IP on the master node.
4095

4096
  """
4097
  def Exec(self, feedback_fn):
4098
    """Deactivate the master IP.
4099

4100
    """
4101
    master_params = self.cfg.GetMasterNetworkParameters()
4102
    ems = self.cfg.GetUseExternalMipScript()
4103
    result = self.rpc.call_node_deactivate_master_ip(master_params.name,
4104
                                                     master_params, ems)
4105
    result.Raise("Could not deactivate the master IP")
4106

    
4107

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

4111
  """
4112
  if not instance.disks or disks is not None and not disks:
4113
    return True
4114

    
4115
  disks = _ExpandCheckDisks(instance, disks)
4116

    
4117
  if not oneshot:
4118
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
4119

    
4120
  node = instance.primary_node
4121

    
4122
  for dev in disks:
4123
    lu.cfg.SetDiskID(dev, node)
4124

    
4125
  # TODO: Convert to utils.Retry
4126

    
4127
  retries = 0
4128
  degr_retries = 10 # in seconds, as we sleep 1 second each time
4129
  while True:
4130
    max_time = 0
4131
    done = True
4132
    cumul_degraded = False
4133
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
4134
    msg = rstats.fail_msg
4135
    if msg:
4136
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
4137
      retries += 1
4138
      if retries >= 10:
4139
        raise errors.RemoteError("Can't contact node %s for mirror data,"
4140
                                 " aborting." % node)
4141
      time.sleep(6)
4142
      continue
4143
    rstats = rstats.payload
4144
    retries = 0
4145
    for i, mstat in enumerate(rstats):
4146
      if mstat is None:
4147
        lu.LogWarning("Can't compute data for node %s/%s",
4148
                           node, disks[i].iv_name)
4149
        continue
4150

    
4151
      cumul_degraded = (cumul_degraded or
4152
                        (mstat.is_degraded and mstat.sync_percent is None))
4153
      if mstat.sync_percent is not None:
4154
        done = False
4155
        if mstat.estimated_time is not None:
4156
          rem_time = ("%s remaining (estimated)" %
4157
                      utils.FormatSeconds(mstat.estimated_time))
4158
          max_time = mstat.estimated_time
4159
        else:
4160
          rem_time = "no time estimate"
4161
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
4162
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
4163

    
4164
    # if we're done but degraded, let's do a few small retries, to
4165
    # make sure we see a stable and not transient situation; therefore
4166
    # we force restart of the loop
4167
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
4168
      logging.info("Degraded disks found, %d retries left", degr_retries)
4169
      degr_retries -= 1
4170
      time.sleep(1)
4171
      continue
4172

    
4173
    if done or oneshot:
4174
      break
4175

    
4176
    time.sleep(min(60, max_time))
4177

    
4178
  if done:
4179
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
4180
  return not cumul_degraded
4181

    
4182

    
4183
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
4184
  """Check that mirrors are not degraded.
4185

4186
  The ldisk parameter, if True, will change the test from the
4187
  is_degraded attribute (which represents overall non-ok status for
4188
  the device(s)) to the ldisk (representing the local storage status).
4189

4190
  """
4191
  lu.cfg.SetDiskID(dev, node)
4192

    
4193
  result = True
4194

    
4195
  if on_primary or dev.AssembleOnSecondary():
4196
    rstats = lu.rpc.call_blockdev_find(node, dev)
4197
    msg = rstats.fail_msg
4198
    if msg:
4199
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
4200
      result = False
4201
    elif not rstats.payload:
4202
      lu.LogWarning("Can't find disk on node %s", node)
4203
      result = False
4204
    else:
4205
      if ldisk:
4206
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
4207
      else:
4208
        result = result and not rstats.payload.is_degraded
4209

    
4210
  if dev.children:
4211
    for child in dev.children:
4212
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
4213

    
4214
  return result
4215

    
4216

    
4217
class LUOobCommand(NoHooksLU):
4218
  """Logical unit for OOB handling.
4219

4220
  """
4221
  REG_BGL = False
4222
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
4223

    
4224
  def ExpandNames(self):
4225
    """Gather locks we need.
4226

4227
    """
4228
    if self.op.node_names:
4229
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
4230
      lock_names = self.op.node_names
4231
    else:
4232
      lock_names = locking.ALL_SET
4233

    
4234
    self.needed_locks = {
4235
      locking.LEVEL_NODE: lock_names,
4236
      }
4237

    
4238
  def CheckPrereq(self):
4239
    """Check prerequisites.
4240

4241
    This checks:
4242
     - the node exists in the configuration
4243
     - OOB is supported
4244

4245
    Any errors are signaled by raising errors.OpPrereqError.
4246

4247
    """
4248
    self.nodes = []
4249
    self.master_node = self.cfg.GetMasterNode()
4250

    
4251
    assert self.op.power_delay >= 0.0
4252

    
4253
    if self.op.node_names:
4254
      if (self.op.command in self._SKIP_MASTER and
4255
          self.master_node in self.op.node_names):
4256
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
4257
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
4258

    
4259
        if master_oob_handler:
4260
          additional_text = ("run '%s %s %s' if you want to operate on the"
4261
                             " master regardless") % (master_oob_handler,
4262
                                                      self.op.command,
4263
                                                      self.master_node)
4264
        else:
4265
          additional_text = "it does not support out-of-band operations"
4266

    
4267
        raise errors.OpPrereqError(("Operating on the master node %s is not"
4268
                                    " allowed for %s; %s") %
4269
                                   (self.master_node, self.op.command,
4270
                                    additional_text), errors.ECODE_INVAL)
4271
    else:
4272
      self.op.node_names = self.cfg.GetNodeList()
4273
      if self.op.command in self._SKIP_MASTER:
4274
        self.op.node_names.remove(self.master_node)
4275

    
4276
    if self.op.command in self._SKIP_MASTER:
4277
      assert self.master_node not in self.op.node_names
4278

    
4279
    for (node_name, node) in self.cfg.GetMultiNodeInfo(self.op.node_names):
4280
      if node is None:
4281
        raise errors.OpPrereqError("Node %s not found" % node_name,
4282
                                   errors.ECODE_NOENT)
4283
      else:
4284
        self.nodes.append(node)
4285

    
4286
      if (not self.op.ignore_status and
4287
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
4288
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
4289
                                    " not marked offline") % node_name,
4290
                                   errors.ECODE_STATE)
4291

    
4292
  def Exec(self, feedback_fn):
4293
    """Execute OOB and return result if we expect any.
4294

4295
    """
4296
    master_node = self.master_node
4297
    ret = []
4298

    
4299
    for idx, node in enumerate(utils.NiceSort(self.nodes,
4300
                                              key=lambda node: node.name)):
4301
      node_entry = [(constants.RS_NORMAL, node.name)]
4302
      ret.append(node_entry)
4303

    
4304
      oob_program = _SupportsOob(self.cfg, node)
4305

    
4306
      if not oob_program:
4307
        node_entry.append((constants.RS_UNAVAIL, None))
4308
        continue
4309

    
4310
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
4311
                   self.op.command, oob_program, node.name)
4312
      result = self.rpc.call_run_oob(master_node, oob_program,
4313
                                     self.op.command, node.name,
4314
                                     self.op.timeout)
4315

    
4316
      if result.fail_msg:
4317
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
4318
                        node.name, result.fail_msg)
4319
        node_entry.append((constants.RS_NODATA, None))
4320
      else:
4321
        try:
4322
          self._CheckPayload(result)
4323
        except errors.OpExecError, err:
4324
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
4325
                          node.name, err)
4326
          node_entry.append((constants.RS_NODATA, None))
4327
        else:
4328
          if self.op.command == constants.OOB_HEALTH:
4329
            # For health we should log important events
4330
            for item, status in result.payload:
4331
              if status in [constants.OOB_STATUS_WARNING,
4332
                            constants.OOB_STATUS_CRITICAL]:
4333
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
4334
                                item, node.name, status)
4335

    
4336
          if self.op.command == constants.OOB_POWER_ON:
4337
            node.powered = True
4338
          elif self.op.command == constants.OOB_POWER_OFF:
4339
            node.powered = False
4340
          elif self.op.command == constants.OOB_POWER_STATUS:
4341
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
4342
            if powered != node.powered:
4343
              logging.warning(("Recorded power state (%s) of node '%s' does not"
4344
                               " match actual power state (%s)"), node.powered,
4345
                              node.name, powered)
4346

    
4347
          # For configuration changing commands we should update the node
4348
          if self.op.command in (constants.OOB_POWER_ON,
4349
                                 constants.OOB_POWER_OFF):
4350
            self.cfg.Update(node, feedback_fn)
4351

    
4352
          node_entry.append((constants.RS_NORMAL, result.payload))
4353

    
4354
          if (self.op.command == constants.OOB_POWER_ON and
4355
              idx < len(self.nodes) - 1):
4356
            time.sleep(self.op.power_delay)
4357

    
4358
    return ret
4359

    
4360
  def _CheckPayload(self, result):
4361
    """Checks if the payload is valid.
4362

4363
    @param result: RPC result
4364
    @raises errors.OpExecError: If payload is not valid
4365

4366
    """
4367
    errs = []
4368
    if self.op.command == constants.OOB_HEALTH:
4369
      if not isinstance(result.payload, list):
4370
        errs.append("command 'health' is expected to return a list but got %s" %
4371
                    type(result.payload))
4372
      else:
4373
        for item, status in result.payload:
4374
          if status not in constants.OOB_STATUSES:
4375
            errs.append("health item '%s' has invalid status '%s'" %
4376
                        (item, status))
4377

    
4378
    if self.op.command == constants.OOB_POWER_STATUS:
4379
      if not isinstance(result.payload, dict):
4380
        errs.append("power-status is expected to return a dict but got %s" %
4381
                    type(result.payload))
4382

    
4383
    if self.op.command in [
4384
        constants.OOB_POWER_ON,
4385
        constants.OOB_POWER_OFF,
4386
        constants.OOB_POWER_CYCLE,
4387
        ]:
4388
      if result.payload is not None:
4389
        errs.append("%s is expected to not return payload but got '%s'" %
4390
                    (self.op.command, result.payload))
4391

    
4392
    if errs:
4393
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
4394
                               utils.CommaJoin(errs))
4395

    
4396

    
4397
class _OsQuery(_QueryBase):
4398
  FIELDS = query.OS_FIELDS
4399

    
4400
  def ExpandNames(self, lu):
4401
    # Lock all nodes in shared mode
4402
    # Temporary removal of locks, should be reverted later
4403
    # TODO: reintroduce locks when they are lighter-weight
4404
    lu.needed_locks = {}
4405
    #self.share_locks[locking.LEVEL_NODE] = 1
4406
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4407

    
4408
    # The following variables interact with _QueryBase._GetNames
4409
    if self.names:
4410
      self.wanted = self.names
4411
    else:
4412
      self.wanted = locking.ALL_SET
4413

    
4414
    self.do_locking = self.use_locking
4415

    
4416
  def DeclareLocks(self, lu, level):
4417
    pass
4418

    
4419
  @staticmethod
4420
  def _DiagnoseByOS(rlist):
4421
    """Remaps a per-node return list into an a per-os per-node dictionary
4422

4423
    @param rlist: a map with node names as keys and OS objects as values
4424

4425
    @rtype: dict
4426
    @return: a dictionary with osnames as keys and as value another
4427
        map, with nodes as keys and tuples of (path, status, diagnose,
4428
        variants, parameters, api_versions) as values, eg::
4429

4430
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
4431
                                     (/srv/..., False, "invalid api")],
4432
                           "node2": [(/srv/..., True, "", [], [])]}
4433
          }
4434

4435
    """
4436
    all_os = {}
4437
    # we build here the list of nodes that didn't fail the RPC (at RPC
4438
    # level), so that nodes with a non-responding node daemon don't
4439
    # make all OSes invalid
4440
    good_nodes = [node_name for node_name in rlist
4441
                  if not rlist[node_name].fail_msg]
4442
    for node_name, nr in rlist.items():
4443
      if nr.fail_msg or not nr.payload:
4444
        continue
4445
      for (name, path, status, diagnose, variants,
4446
           params, api_versions) in nr.payload:
4447
        if name not in all_os:
4448
          # build a list of nodes for this os containing empty lists
4449
          # for each node in node_list
4450
          all_os[name] = {}
4451
          for nname in good_nodes:
4452
            all_os[name][nname] = []
4453
        # convert params from [name, help] to (name, help)
4454
        params = [tuple(v) for v in params]
4455
        all_os[name][node_name].append((path, status, diagnose,
4456
                                        variants, params, api_versions))
4457
    return all_os
4458

    
4459
  def _GetQueryData(self, lu):
4460
    """Computes the list of nodes and their attributes.
4461

4462
    """
4463
    # Locking is not used
4464
    assert not (compat.any(lu.glm.is_owned(level)
4465
                           for level in locking.LEVELS
4466
                           if level != locking.LEVEL_CLUSTER) or
4467
                self.do_locking or self.use_locking)
4468

    
4469
    valid_nodes = [node.name
4470
                   for node in lu.cfg.GetAllNodesInfo().values()
4471
                   if not node.offline and node.vm_capable]
4472
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
4473
    cluster = lu.cfg.GetClusterInfo()
4474

    
4475
    data = {}
4476

    
4477
    for (os_name, os_data) in pol.items():
4478
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
4479
                          hidden=(os_name in cluster.hidden_os),
4480
                          blacklisted=(os_name in cluster.blacklisted_os))
4481

    
4482
      variants = set()
4483
      parameters = set()
4484
      api_versions = set()
4485

    
4486
      for idx, osl in enumerate(os_data.values()):
4487
        info.valid = bool(info.valid and osl and osl[0][1])
4488
        if not info.valid:
4489
          break
4490

    
4491
        (node_variants, node_params, node_api) = osl[0][3:6]
4492
        if idx == 0:
4493
          # First entry
4494
          variants.update(node_variants)
4495
          parameters.update(node_params)
4496
          api_versions.update(node_api)
4497
        else:
4498
          # Filter out inconsistent values
4499
          variants.intersection_update(node_variants)
4500
          parameters.intersection_update(node_params)
4501
          api_versions.intersection_update(node_api)
4502

    
4503
      info.variants = list(variants)
4504
      info.parameters = list(parameters)
4505
      info.api_versions = list(api_versions)
4506

    
4507
      data[os_name] = info
4508

    
4509
    # Prepare data in requested order
4510
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
4511
            if name in data]
4512

    
4513

    
4514
class LUOsDiagnose(NoHooksLU):
4515
  """Logical unit for OS diagnose/query.
4516

4517
  """
4518
  REQ_BGL = False
4519

    
4520
  @staticmethod
4521
  def _BuildFilter(fields, names):
4522
    """Builds a filter for querying OSes.
4523

4524
    """
4525
    name_filter = qlang.MakeSimpleFilter("name", names)
4526

    
4527
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
4528
    # respective field is not requested
4529
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
4530
                     for fname in ["hidden", "blacklisted"]
4531
                     if fname not in fields]
4532
    if "valid" not in fields:
4533
      status_filter.append([qlang.OP_TRUE, "valid"])
4534

    
4535
    if status_filter:
4536
      status_filter.insert(0, qlang.OP_AND)
4537
    else:
4538
      status_filter = None
4539

    
4540
    if name_filter and status_filter:
4541
      return [qlang.OP_AND, name_filter, status_filter]
4542
    elif name_filter:
4543
      return name_filter
4544
    else:
4545
      return status_filter
4546

    
4547
  def CheckArguments(self):
4548
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
4549
                       self.op.output_fields, False)
4550

    
4551
  def ExpandNames(self):
4552
    self.oq.ExpandNames(self)
4553

    
4554
  def Exec(self, feedback_fn):
4555
    return self.oq.OldStyleQuery(self)
4556

    
4557

    
4558
class LUNodeRemove(LogicalUnit):
4559
  """Logical unit for removing a node.
4560

4561
  """
4562
  HPATH = "node-remove"
4563
  HTYPE = constants.HTYPE_NODE
4564

    
4565
  def BuildHooksEnv(self):
4566
    """Build hooks env.
4567

4568
    This doesn't run on the target node in the pre phase as a failed
4569
    node would then be impossible to remove.
4570

4571
    """
4572
    return {
4573
      "OP_TARGET": self.op.node_name,
4574
      "NODE_NAME": self.op.node_name,
4575
      }
4576

    
4577
  def BuildHooksNodes(self):
4578
    """Build hooks nodes.
4579

4580
    """
4581
    all_nodes = self.cfg.GetNodeList()
4582
    try:
4583
      all_nodes.remove(self.op.node_name)
4584
    except ValueError:
4585
      logging.warning("Node '%s', which is about to be removed, was not found"
4586
                      " in the list of all nodes", self.op.node_name)
4587
    return (all_nodes, all_nodes)
4588

    
4589
  def CheckPrereq(self):
4590
    """Check prerequisites.
4591

4592
    This checks:
4593
     - the node exists in the configuration
4594
     - it does not have primary or secondary instances
4595
     - it's not the master
4596

4597
    Any errors are signaled by raising errors.OpPrereqError.
4598

4599
    """
4600
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4601
    node = self.cfg.GetNodeInfo(self.op.node_name)
4602
    assert node is not None
4603

    
4604
    masternode = self.cfg.GetMasterNode()
4605
    if node.name == masternode:
4606
      raise errors.OpPrereqError("Node is the master node, failover to another"
4607
                                 " node is required", errors.ECODE_INVAL)
4608

    
4609
    for instance_name, instance in self.cfg.GetAllInstancesInfo().items():
4610
      if node.name in instance.all_nodes:
4611
        raise errors.OpPrereqError("Instance %s is still running on the node,"
4612
                                   " please remove first" % instance_name,
4613
                                   errors.ECODE_INVAL)
4614
    self.op.node_name = node.name
4615
    self.node = node
4616

    
4617
  def Exec(self, feedback_fn):
4618
    """Removes the node from the cluster.
4619

4620
    """
4621
    node = self.node
4622
    logging.info("Stopping the node daemon and removing configs from node %s",
4623
                 node.name)
4624

    
4625
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
4626

    
4627
    assert locking.BGL in self.owned_locks(locking.LEVEL_CLUSTER), \
4628
      "Not owning BGL"
4629

    
4630
    # Promote nodes to master candidate as needed
4631
    _AdjustCandidatePool(self, exceptions=[node.name])
4632
    self.context.RemoveNode(node.name)
4633

    
4634
    # Run post hooks on the node before it's removed
4635
    _RunPostHook(self, node.name)
4636

    
4637
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
4638
    msg = result.fail_msg
4639
    if msg:
4640
      self.LogWarning("Errors encountered on the remote node while leaving"
4641
                      " the cluster: %s", msg)
4642

    
4643
    # Remove node from our /etc/hosts
4644
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4645
      master_node = self.cfg.GetMasterNode()
4646
      result = self.rpc.call_etc_hosts_modify(master_node,
4647
                                              constants.ETC_HOSTS_REMOVE,
4648
                                              node.name, None)
4649
      result.Raise("Can't update hosts file with new host data")
4650
      _RedistributeAncillaryFiles(self)
4651

    
4652

    
4653
class _NodeQuery(_QueryBase):
4654
  FIELDS = query.NODE_FIELDS
4655

    
4656
  def ExpandNames(self, lu):
4657
    lu.needed_locks = {}
4658
    lu.share_locks = _ShareAll()
4659

    
4660
    if self.names:
4661
      self.wanted = _GetWantedNodes(lu, self.names)
4662
    else:
4663
      self.wanted = locking.ALL_SET
4664

    
4665
    self.do_locking = (self.use_locking and
4666
                       query.NQ_LIVE in self.requested_data)
4667

    
4668
    if self.do_locking:
4669
      # If any non-static field is requested we need to lock the nodes
4670
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
4671

    
4672
  def DeclareLocks(self, lu, level):
4673
    pass
4674

    
4675
  def _GetQueryData(self, lu):
4676
    """Computes the list of nodes and their attributes.
4677

4678
    """
4679
    all_info = lu.cfg.GetAllNodesInfo()
4680

    
4681
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
4682

    
4683
    # Gather data as requested
4684
    if query.NQ_LIVE in self.requested_data:
4685
      # filter out non-vm_capable nodes
4686
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
4687

    
4688
      node_data = lu.rpc.call_node_info(toquery_nodes, [lu.cfg.GetVGName()],
4689
                                        [lu.cfg.GetHypervisorType()])
4690
      live_data = dict((name, _MakeLegacyNodeInfo(nresult.payload))
4691
                       for (name, nresult) in node_data.items()
4692
                       if not nresult.fail_msg and nresult.payload)
4693
    else:
4694
      live_data = None
4695

    
4696
    if query.NQ_INST in self.requested_data:
4697
      node_to_primary = dict([(name, set()) for name in nodenames])
4698
      node_to_secondary = dict([(name, set()) for name in nodenames])
4699

    
4700
      inst_data = lu.cfg.GetAllInstancesInfo()
4701

    
4702
      for inst in inst_data.values():
4703
        if inst.primary_node in node_to_primary:
4704
          node_to_primary[inst.primary_node].add(inst.name)
4705
        for secnode in inst.secondary_nodes:
4706
          if secnode in node_to_secondary:
4707
            node_to_secondary[secnode].add(inst.name)
4708
    else:
4709
      node_to_primary = None
4710
      node_to_secondary = None
4711

    
4712
    if query.NQ_OOB in self.requested_data:
4713
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
4714
                         for name, node in all_info.iteritems())
4715
    else:
4716
      oob_support = None
4717

    
4718
    if query.NQ_GROUP in self.requested_data:
4719
      groups = lu.cfg.GetAllNodeGroupsInfo()
4720
    else:
4721
      groups = {}
4722

    
4723
    return query.NodeQueryData([all_info[name] for name in nodenames],
4724
                               live_data, lu.cfg.GetMasterNode(),
4725
                               node_to_primary, node_to_secondary, groups,
4726
                               oob_support, lu.cfg.GetClusterInfo())
4727

    
4728

    
4729
class LUNodeQuery(NoHooksLU):
4730
  """Logical unit for querying nodes.
4731

4732
  """
4733
  # pylint: disable=W0142
4734
  REQ_BGL = False
4735

    
4736
  def CheckArguments(self):
4737
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4738
                         self.op.output_fields, self.op.use_locking)
4739

    
4740
  def ExpandNames(self):
4741
    self.nq.ExpandNames(self)
4742

    
4743
  def DeclareLocks(self, level):
4744
    self.nq.DeclareLocks(self, level)
4745

    
4746
  def Exec(self, feedback_fn):
4747
    return self.nq.OldStyleQuery(self)
4748

    
4749

    
4750
class LUNodeQueryvols(NoHooksLU):
4751
  """Logical unit for getting volumes on node(s).
4752

4753
  """
4754
  REQ_BGL = False
4755
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4756
  _FIELDS_STATIC = utils.FieldSet("node")
4757

    
4758
  def CheckArguments(self):
4759
    _CheckOutputFields(static=self._FIELDS_STATIC,
4760
                       dynamic=self._FIELDS_DYNAMIC,
4761
                       selected=self.op.output_fields)
4762

    
4763
  def ExpandNames(self):
4764
    self.share_locks = _ShareAll()
4765
    self.needed_locks = {}
4766

    
4767
    if not self.op.nodes:
4768
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4769
    else:
4770
      self.needed_locks[locking.LEVEL_NODE] = \
4771
        _GetWantedNodes(self, self.op.nodes)
4772

    
4773
  def Exec(self, feedback_fn):
4774
    """Computes the list of nodes and their attributes.
4775

4776
    """
4777
    nodenames = self.owned_locks(locking.LEVEL_NODE)
4778
    volumes = self.rpc.call_node_volumes(nodenames)
4779

    
4780
    ilist = self.cfg.GetAllInstancesInfo()
4781
    vol2inst = _MapInstanceDisksToNodes(ilist.values())
4782

    
4783
    output = []
4784
    for node in nodenames:
4785
      nresult = volumes[node]
4786
      if nresult.offline:
4787
        continue
4788
      msg = nresult.fail_msg
4789
      if msg:
4790
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4791
        continue
4792

    
4793
      node_vols = sorted(nresult.payload,
4794
                         key=operator.itemgetter("dev"))
4795

    
4796
      for vol in node_vols:
4797
        node_output = []
4798
        for field in self.op.output_fields:
4799
          if field == "node":
4800
            val = node
4801
          elif field == "phys":
4802
            val = vol["dev"]
4803
          elif field == "vg":
4804
            val = vol["vg"]
4805
          elif field == "name":
4806
            val = vol["name"]
4807
          elif field == "size":
4808
            val = int(float(vol["size"]))
4809
          elif field == "instance":
4810
            val = vol2inst.get((node, vol["vg"] + "/" + vol["name"]), "-")
4811
          else:
4812
            raise errors.ParameterError(field)
4813
          node_output.append(str(val))
4814

    
4815
        output.append(node_output)
4816

    
4817
    return output
4818

    
4819

    
4820
class LUNodeQueryStorage(NoHooksLU):
4821
  """Logical unit for getting information on storage units on node(s).
4822

4823
  """
4824
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4825
  REQ_BGL = False
4826

    
4827
  def CheckArguments(self):
4828
    _CheckOutputFields(static=self._FIELDS_STATIC,
4829
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4830
                       selected=self.op.output_fields)
4831

    
4832
  def ExpandNames(self):
4833
    self.share_locks = _ShareAll()
4834
    self.needed_locks = {}
4835

    
4836
    if self.op.nodes:
4837
      self.needed_locks[locking.LEVEL_NODE] = \
4838
        _GetWantedNodes(self, self.op.nodes)
4839
    else:
4840
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4841

    
4842
  def Exec(self, feedback_fn):
4843
    """Computes the list of nodes and their attributes.
4844

4845
    """
4846
    self.nodes = self.owned_locks(locking.LEVEL_NODE)
4847

    
4848
    # Always get name to sort by
4849
    if constants.SF_NAME in self.op.output_fields:
4850
      fields = self.op.output_fields[:]
4851
    else:
4852
      fields = [constants.SF_NAME] + self.op.output_fields
4853

    
4854
    # Never ask for node or type as it's only known to the LU
4855
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4856
      while extra in fields:
4857
        fields.remove(extra)
4858

    
4859
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4860
    name_idx = field_idx[constants.SF_NAME]
4861

    
4862
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4863
    data = self.rpc.call_storage_list(self.nodes,
4864
                                      self.op.storage_type, st_args,
4865
                                      self.op.name, fields)
4866

    
4867
    result = []
4868

    
4869
    for node in utils.NiceSort(self.nodes):
4870
      nresult = data[node]
4871
      if nresult.offline:
4872
        continue
4873

    
4874
      msg = nresult.fail_msg
4875
      if msg:
4876
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4877
        continue
4878

    
4879
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4880

    
4881
      for name in utils.NiceSort(rows.keys()):
4882
        row = rows[name]
4883

    
4884
        out = []
4885

    
4886
        for field in self.op.output_fields:
4887
          if field == constants.SF_NODE:
4888
            val = node
4889
          elif field == constants.SF_TYPE:
4890
            val = self.op.storage_type
4891
          elif field in field_idx:
4892
            val = row[field_idx[field]]
4893
          else:
4894
            raise errors.ParameterError(field)
4895

    
4896
          out.append(val)
4897

    
4898
        result.append(out)
4899

    
4900
    return result
4901

    
4902

    
4903
class _InstanceQuery(_QueryBase):
4904
  FIELDS = query.INSTANCE_FIELDS
4905

    
4906
  def ExpandNames(self, lu):
4907
    lu.needed_locks = {}
4908
    lu.share_locks = _ShareAll()
4909

    
4910
    if self.names:
4911
      self.wanted = _GetWantedInstances(lu, self.names)
4912
    else:
4913
      self.wanted = locking.ALL_SET
4914

    
4915
    self.do_locking = (self.use_locking and
4916
                       query.IQ_LIVE in self.requested_data)
4917
    if self.do_locking:
4918
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4919
      lu.needed_locks[locking.LEVEL_NODEGROUP] = []
4920
      lu.needed_locks[locking.LEVEL_NODE] = []
4921
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4922

    
4923
    self.do_grouplocks = (self.do_locking and
4924
                          query.IQ_NODES in self.requested_data)
4925

    
4926
  def DeclareLocks(self, lu, level):
4927
    if self.do_locking:
4928
      if level == locking.LEVEL_NODEGROUP and self.do_grouplocks:
4929
        assert not lu.needed_locks[locking.LEVEL_NODEGROUP]
4930

    
4931
        # Lock all groups used by instances optimistically; this requires going
4932
        # via the node before it's locked, requiring verification later on
4933
        lu.needed_locks[locking.LEVEL_NODEGROUP] = \
4934
          set(group_uuid
4935
              for instance_name in lu.owned_locks(locking.LEVEL_INSTANCE)
4936
              for group_uuid in lu.cfg.GetInstanceNodeGroups(instance_name))
4937
      elif level == locking.LEVEL_NODE:
4938
        lu._LockInstancesNodes() # pylint: disable=W0212
4939

    
4940
  @staticmethod
4941
  def _CheckGroupLocks(lu):
4942
    owned_instances = frozenset(lu.owned_locks(locking.LEVEL_INSTANCE))
4943
    owned_groups = frozenset(lu.owned_locks(locking.LEVEL_NODEGROUP))
4944

    
4945
    # Check if node groups for locked instances are still correct
4946
    for instance_name in owned_instances:
4947
      _CheckInstanceNodeGroups(lu.cfg, instance_name, owned_groups)
4948

    
4949
  def _GetQueryData(self, lu):
4950
    """Computes the list of instances and their attributes.
4951

4952
    """
4953
    if self.do_grouplocks:
4954
      self._CheckGroupLocks(lu)
4955

    
4956
    cluster = lu.cfg.GetClusterInfo()
4957
    all_info = lu.cfg.GetAllInstancesInfo()
4958

    
4959
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4960

    
4961
    instance_list = [all_info[name] for name in instance_names]
4962
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4963
                                        for inst in instance_list)))
4964
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4965
    bad_nodes = []
4966
    offline_nodes = []
4967
    wrongnode_inst = set()
4968

    
4969
    # Gather data as requested
4970
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4971
      live_data = {}
4972
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4973
      for name in nodes:
4974
        result = node_data[name]
4975
        if result.offline:
4976
          # offline nodes will be in both lists
4977
          assert result.fail_msg
4978
          offline_nodes.append(name)
4979
        if result.fail_msg:
4980
          bad_nodes.append(name)
4981
        elif result.payload:
4982
          for inst in result.payload:
4983
            if inst in all_info:
4984
              if all_info[inst].primary_node == name:
4985
                live_data.update(result.payload)
4986
              else:
4987
                wrongnode_inst.add(inst)
4988
            else:
4989
              # orphan instance; we don't list it here as we don't
4990
              # handle this case yet in the output of instance listing
4991
              logging.warning("Orphan instance '%s' found on node %s",
4992
                              inst, name)
4993
        # else no instance is alive
4994
    else:
4995
      live_data = {}
4996

    
4997
    if query.IQ_DISKUSAGE in self.requested_data:
4998
      disk_usage = dict((inst.name,
4999
                         _ComputeDiskSize(inst.disk_template,
5000
                                          [{constants.IDISK_SIZE: disk.size}
5001
                                           for disk in inst.disks]))
5002
                        for inst in instance_list)
5003
    else:
5004
      disk_usage = None
5005

    
5006
    if query.IQ_CONSOLE in self.requested_data:
5007
      consinfo = {}
5008
      for inst in instance_list:
5009
        if inst.name in live_data:
5010
          # Instance is running
5011
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
5012
        else:
5013
          consinfo[inst.name] = None
5014
      assert set(consinfo.keys()) == set(instance_names)
5015
    else:
5016
      consinfo = None
5017

    
5018
    if query.IQ_NODES in self.requested_data:
5019
      node_names = set(itertools.chain(*map(operator.attrgetter("all_nodes"),
5020
                                            instance_list)))
5021
      nodes = dict(lu.cfg.GetMultiNodeInfo(node_names))
5022
      groups = dict((uuid, lu.cfg.GetNodeGroup(uuid))
5023
                    for uuid in set(map(operator.attrgetter("group"),
5024
                                        nodes.values())))
5025
    else:
5026
      nodes = None
5027
      groups = None
5028

    
5029
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
5030
                                   disk_usage, offline_nodes, bad_nodes,
5031
                                   live_data, wrongnode_inst, consinfo,
5032
                                   nodes, groups)
5033

    
5034

    
5035
class LUQuery(NoHooksLU):
5036
  """Query for resources/items of a certain kind.
5037

5038
  """
5039
  # pylint: disable=W0142
5040
  REQ_BGL = False
5041

    
5042
  def CheckArguments(self):
5043
    qcls = _GetQueryImplementation(self.op.what)
5044

    
5045
    self.impl = qcls(self.op.qfilter, self.op.fields, self.op.use_locking)
5046

    
5047
  def ExpandNames(self):
5048
    self.impl.ExpandNames(self)
5049

    
5050
  def DeclareLocks(self, level):
5051
    self.impl.DeclareLocks(self, level)
5052

    
5053
  def Exec(self, feedback_fn):
5054
    return self.impl.NewStyleQuery(self)
5055

    
5056

    
5057
class LUQueryFields(NoHooksLU):
5058
  """Query for resources/items of a certain kind.
5059

5060
  """
5061
  # pylint: disable=W0142
5062
  REQ_BGL = False
5063

    
5064
  def CheckArguments(self):
5065
    self.qcls = _GetQueryImplementation(self.op.what)
5066

    
5067
  def ExpandNames(self):
5068
    self.needed_locks = {}
5069

    
5070
  def Exec(self, feedback_fn):
5071
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
5072

    
5073

    
5074
class LUNodeModifyStorage(NoHooksLU):
5075
  """Logical unit for modifying a storage volume on a node.
5076

5077
  """
5078
  REQ_BGL = False
5079

    
5080
  def CheckArguments(self):
5081
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5082

    
5083
    storage_type = self.op.storage_type
5084

    
5085
    try:
5086
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
5087
    except KeyError:
5088
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
5089
                                 " modified" % storage_type,
5090
                                 errors.ECODE_INVAL)
5091

    
5092
    diff = set(self.op.changes.keys()) - modifiable
5093
    if diff:
5094
      raise errors.OpPrereqError("The following fields can not be modified for"
5095
                                 " storage units of type '%s': %r" %
5096
                                 (storage_type, list(diff)),
5097
                                 errors.ECODE_INVAL)
5098

    
5099
  def ExpandNames(self):
5100
    self.needed_locks = {
5101
      locking.LEVEL_NODE: self.op.node_name,
5102
      }
5103

    
5104
  def Exec(self, feedback_fn):
5105
    """Computes the list of nodes and their attributes.
5106

5107
    """
5108
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
5109
    result = self.rpc.call_storage_modify(self.op.node_name,
5110
                                          self.op.storage_type, st_args,
5111
                                          self.op.name, self.op.changes)
5112
    result.Raise("Failed to modify storage unit '%s' on %s" %
5113
                 (self.op.name, self.op.node_name))
5114

    
5115

    
5116
class LUNodeAdd(LogicalUnit):
5117
  """Logical unit for adding node to the cluster.
5118

5119
  """
5120
  HPATH = "node-add"
5121
  HTYPE = constants.HTYPE_NODE
5122
  _NFLAGS = ["master_capable", "vm_capable"]
5123

    
5124
  def CheckArguments(self):
5125
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
5126
    # validate/normalize the node name
5127
    self.hostname = netutils.GetHostname(name=self.op.node_name,
5128
                                         family=self.primary_ip_family)
5129
    self.op.node_name = self.hostname.name
5130

    
5131
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
5132
      raise errors.OpPrereqError("Cannot readd the master node",
5133
                                 errors.ECODE_STATE)
5134

    
5135
    if self.op.readd and self.op.group:
5136
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
5137
                                 " being readded", errors.ECODE_INVAL)
5138

    
5139
  def BuildHooksEnv(self):
5140
    """Build hooks env.
5141

5142
    This will run on all nodes before, and on all nodes + the new node after.
5143

5144
    """
5145
    return {
5146
      "OP_TARGET": self.op.node_name,
5147
      "NODE_NAME": self.op.node_name,
5148
      "NODE_PIP": self.op.primary_ip,
5149
      "NODE_SIP": self.op.secondary_ip,
5150
      "MASTER_CAPABLE": str(self.op.master_capable),
5151
      "VM_CAPABLE": str(self.op.vm_capable),
5152
      }
5153

    
5154
  def BuildHooksNodes(self):
5155
    """Build hooks nodes.
5156

5157
    """
5158
    # Exclude added node
5159
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
5160
    post_nodes = pre_nodes + [self.op.node_name, ]
5161

    
5162
    return (pre_nodes, post_nodes)
5163

    
5164
  def CheckPrereq(self):
5165
    """Check prerequisites.
5166

5167
    This checks:
5168
     - the new node is not already in the config
5169
     - it is resolvable
5170
     - its parameters (single/dual homed) matches the cluster
5171

5172
    Any errors are signaled by raising errors.OpPrereqError.
5173

5174
    """
5175
    cfg = self.cfg
5176
    hostname = self.hostname
5177
    node = hostname.name
5178
    primary_ip = self.op.primary_ip = hostname.ip
5179
    if self.op.secondary_ip is None:
5180
      if self.primary_ip_family == netutils.IP6Address.family:
5181
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
5182
                                   " IPv4 address must be given as secondary",
5183
                                   errors.ECODE_INVAL)
5184
      self.op.secondary_ip = primary_ip
5185

    
5186
    secondary_ip = self.op.secondary_ip
5187
    if not netutils.IP4Address.IsValid(secondary_ip):
5188
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
5189
                                 " address" % secondary_ip, errors.ECODE_INVAL)
5190

    
5191
    node_list = cfg.GetNodeList()
5192
    if not self.op.readd and node in node_list:
5193
      raise errors.OpPrereqError("Node %s is already in the configuration" %
5194
                                 node, errors.ECODE_EXISTS)
5195
    elif self.op.readd and node not in node_list:
5196
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
5197
                                 errors.ECODE_NOENT)
5198

    
5199
    self.changed_primary_ip = False
5200

    
5201
    for existing_node_name, existing_node in cfg.GetMultiNodeInfo(node_list):
5202
      if self.op.readd and node == existing_node_name:
5203
        if existing_node.secondary_ip != secondary_ip:
5204
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
5205
                                     " address configuration as before",
5206
                                     errors.ECODE_INVAL)
5207
        if existing_node.primary_ip != primary_ip:
5208
          self.changed_primary_ip = True
5209

    
5210
        continue
5211

    
5212
      if (existing_node.primary_ip == primary_ip or
5213
          existing_node.secondary_ip == primary_ip or
5214
          existing_node.primary_ip == secondary_ip or
5215
          existing_node.secondary_ip == secondary_ip):
5216
        raise errors.OpPrereqError("New node ip address(es) conflict with"
5217
                                   " existing node %s" % existing_node.name,
5218
                                   errors.ECODE_NOTUNIQUE)
5219

    
5220
    # After this 'if' block, None is no longer a valid value for the
5221
    # _capable op attributes
5222
    if self.op.readd:
5223
      old_node = self.cfg.GetNodeInfo(node)
5224
      assert old_node is not None, "Can't retrieve locked node %s" % node
5225
      for attr in self._NFLAGS:
5226
        if getattr(self.op, attr) is None:
5227
          setattr(self.op, attr, getattr(old_node, attr))
5228
    else:
5229
      for attr in self._NFLAGS:
5230
        if getattr(self.op, attr) is None:
5231
          setattr(self.op, attr, True)
5232

    
5233
    if self.op.readd and not self.op.vm_capable:
5234
      pri, sec = cfg.GetNodeInstances(node)
5235
      if pri or sec:
5236
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
5237
                                   " flag set to false, but it already holds"
5238
                                   " instances" % node,
5239
                                   errors.ECODE_STATE)
5240

    
5241
    # check that the type of the node (single versus dual homed) is the
5242
    # same as for the master
5243
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
5244
    master_singlehomed = myself.secondary_ip == myself.primary_ip
5245
    newbie_singlehomed = secondary_ip == primary_ip
5246
    if master_singlehomed != newbie_singlehomed:
5247
      if master_singlehomed:
5248
        raise errors.OpPrereqError("The master has no secondary ip but the"
5249
                                   " new node has one",
5250
                                   errors.ECODE_INVAL)
5251
      else:
5252
        raise errors.OpPrereqError("The master has a secondary ip but the"
5253
                                   " new node doesn't have one",
5254
                                   errors.ECODE_INVAL)
5255

    
5256
    # checks reachability
5257
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
5258
      raise errors.OpPrereqError("Node not reachable by ping",
5259
                                 errors.ECODE_ENVIRON)
5260

    
5261
    if not newbie_singlehomed:
5262
      # check reachability from my secondary ip to newbie's secondary ip
5263
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
5264
                           source=myself.secondary_ip):
5265
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5266
                                   " based ping to node daemon port",
5267
                                   errors.ECODE_ENVIRON)
5268

    
5269
    if self.op.readd:
5270
      exceptions = [node]
5271
    else:
5272
      exceptions = []
5273

    
5274
    if self.op.master_capable:
5275
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
5276
    else:
5277
      self.master_candidate = False
5278

    
5279
    if self.op.readd:
5280
      self.new_node = old_node
5281
    else:
5282
      node_group = cfg.LookupNodeGroup(self.op.group)
5283
      self.new_node = objects.Node(name=node,
5284
                                   primary_ip=primary_ip,
5285
                                   secondary_ip=secondary_ip,
5286
                                   master_candidate=self.master_candidate,
5287
                                   offline=False, drained=False,
5288
                                   group=node_group)
5289

    
5290
    if self.op.ndparams:
5291
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
5292

    
5293
  def Exec(self, feedback_fn):
5294
    """Adds the new node to the cluster.
5295

5296
    """
5297
    new_node = self.new_node
5298
    node = new_node.name
5299

    
5300
    assert locking.BGL in self.owned_locks(locking.LEVEL_CLUSTER), \
5301
      "Not owning BGL"
5302

    
5303
    # We adding a new node so we assume it's powered
5304
    new_node.powered = True
5305

    
5306
    # for re-adds, reset the offline/drained/master-candidate flags;
5307
    # we need to reset here, otherwise offline would prevent RPC calls
5308
    # later in the procedure; this also means that if the re-add
5309
    # fails, we are left with a non-offlined, broken node
5310
    if self.op.readd:
5311
      new_node.drained = new_node.offline = False # pylint: disable=W0201
5312
      self.LogInfo("Readding a node, the offline/drained flags were reset")
5313
      # if we demote the node, we do cleanup later in the procedure
5314
      new_node.master_candidate = self.master_candidate
5315
      if self.changed_primary_ip:
5316
        new_node.primary_ip = self.op.primary_ip
5317

    
5318
    # copy the master/vm_capable flags
5319
    for attr in self._NFLAGS:
5320
      setattr(new_node, attr, getattr(self.op, attr))
5321

    
5322
    # notify the user about any possible mc promotion
5323
    if new_node.master_candidate:
5324
      self.LogInfo("Node will be a master candidate")
5325

    
5326
    if self.op.ndparams:
5327
      new_node.ndparams = self.op.ndparams
5328
    else:
5329
      new_node.ndparams = {}
5330

    
5331
    # check connectivity
5332
    result = self.rpc.call_version([node])[node]
5333
    result.Raise("Can't get version information from node %s" % node)
5334
    if constants.PROTOCOL_VERSION == result.payload:
5335
      logging.info("Communication to node %s fine, sw version %s match",
5336
                   node, result.payload)
5337
    else:
5338
      raise errors.OpExecError("Version mismatch master version %s,"
5339
                               " node version %s" %
5340
                               (constants.PROTOCOL_VERSION, result.payload))
5341

    
5342
    # Add node to our /etc/hosts, and add key to known_hosts
5343
    if self.cfg.GetClusterInfo().modify_etc_hosts:
5344
      master_node = self.cfg.GetMasterNode()
5345
      result = self.rpc.call_etc_hosts_modify(master_node,
5346
                                              constants.ETC_HOSTS_ADD,
5347
                                              self.hostname.name,
5348
                                              self.hostname.ip)
5349
      result.Raise("Can't update hosts file with new host data")
5350

    
5351
    if new_node.secondary_ip != new_node.primary_ip:
5352
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
5353
                               False)
5354

    
5355
    node_verify_list = [self.cfg.GetMasterNode()]
5356
    node_verify_param = {
5357
      constants.NV_NODELIST: ([node], {}),
5358
      # TODO: do a node-net-test as well?
5359
    }
5360

    
5361
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
5362
                                       self.cfg.GetClusterName())
5363
    for verifier in node_verify_list:
5364
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
5365
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
5366
      if nl_payload:
5367
        for failed in nl_payload:
5368
          feedback_fn("ssh/hostname verification failed"
5369
                      " (checking from %s): %s" %
5370
                      (verifier, nl_payload[failed]))
5371
        raise errors.OpExecError("ssh/hostname verification failed")
5372

    
5373
    if self.op.readd:
5374
      _RedistributeAncillaryFiles(self)
5375
      self.context.ReaddNode(new_node)
5376
      # make sure we redistribute the config
5377
      self.cfg.Update(new_node, feedback_fn)
5378
      # and make sure the new node will not have old files around
5379
      if not new_node.master_candidate:
5380
        result = self.rpc.call_node_demote_from_mc(new_node.name)
5381
        msg = result.fail_msg
5382
        if msg:
5383
          self.LogWarning("Node failed to demote itself from master"
5384
                          " candidate status: %s" % msg)
5385
    else:
5386
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
5387
                                  additional_vm=self.op.vm_capable)
5388
      self.context.AddNode(new_node, self.proc.GetECId())
5389

    
5390

    
5391
class LUNodeSetParams(LogicalUnit):
5392
  """Modifies the parameters of a node.
5393

5394
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
5395
      to the node role (as _ROLE_*)
5396
  @cvar _R2F: a dictionary from node role to tuples of flags
5397
  @cvar _FLAGS: a list of attribute names corresponding to the flags
5398

5399
  """
5400
  HPATH = "node-modify"
5401
  HTYPE = constants.HTYPE_NODE
5402
  REQ_BGL = False
5403
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
5404
  _F2R = {
5405
    (True, False, False): _ROLE_CANDIDATE,
5406
    (False, True, False): _ROLE_DRAINED,
5407
    (False, False, True): _ROLE_OFFLINE,
5408
    (False, False, False): _ROLE_REGULAR,
5409
    }
5410
  _R2F = dict((v, k) for k, v in _F2R.items())
5411
  _FLAGS = ["master_candidate", "drained", "offline"]
5412

    
5413
  def CheckArguments(self):
5414
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5415
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
5416
                self.op.master_capable, self.op.vm_capable,
5417
                self.op.secondary_ip, self.op.ndparams]
5418
    if all_mods.count(None) == len(all_mods):
5419
      raise errors.OpPrereqError("Please pass at least one modification",
5420
                                 errors.ECODE_INVAL)
5421
    if all_mods.count(True) > 1:
5422
      raise errors.OpPrereqError("Can't set the node into more than one"
5423
                                 " state at the same time",
5424
                                 errors.ECODE_INVAL)
5425

    
5426
    # Boolean value that tells us whether we might be demoting from MC
5427
    self.might_demote = (self.op.master_candidate == False or
5428
                         self.op.offline == True or
5429
                         self.op.drained == True or
5430
                         self.op.master_capable == False)
5431

    
5432
    if self.op.secondary_ip:
5433
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
5434
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
5435
                                   " address" % self.op.secondary_ip,
5436
                                   errors.ECODE_INVAL)
5437

    
5438
    self.lock_all = self.op.auto_promote and self.might_demote
5439
    self.lock_instances = self.op.secondary_ip is not None
5440

    
5441
  def _InstanceFilter(self, instance):
5442
    """Filter for getting affected instances.
5443

5444
    """
5445
    return (instance.disk_template in constants.DTS_INT_MIRROR and
5446
            self.op.node_name in instance.all_nodes)
5447

    
5448
  def ExpandNames(self):
5449
    if self.lock_all:
5450
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
5451
    else:
5452
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
5453

    
5454
    # Since modifying a node can have severe effects on currently running
5455
    # operations the resource lock is at least acquired in shared mode
5456
    self.needed_locks[locking.LEVEL_NODE_RES] = \
5457
      self.needed_locks[locking.LEVEL_NODE]
5458

    
5459
    # Get node resource and instance locks in shared mode; they are not used
5460
    # for anything but read-only access
5461
    self.share_locks[locking.LEVEL_NODE_RES] = 1
5462
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5463

    
5464
    if self.lock_instances:
5465
      self.needed_locks[locking.LEVEL_INSTANCE] = \
5466
        frozenset(self.cfg.GetInstancesInfoByFilter(self._InstanceFilter))
5467

    
5468
  def BuildHooksEnv(self):
5469
    """Build hooks env.
5470

5471
    This runs on the master node.
5472

5473
    """
5474
    return {
5475
      "OP_TARGET": self.op.node_name,
5476
      "MASTER_CANDIDATE": str(self.op.master_candidate),
5477
      "OFFLINE": str(self.op.offline),
5478
      "DRAINED": str(self.op.drained),
5479
      "MASTER_CAPABLE": str(self.op.master_capable),
5480
      "VM_CAPABLE": str(self.op.vm_capable),
5481
      }
5482

    
5483
  def BuildHooksNodes(self):
5484
    """Build hooks nodes.
5485

5486
    """
5487
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
5488
    return (nl, nl)
5489

    
5490
  def CheckPrereq(self):
5491
    """Check prerequisites.
5492

5493
    This only checks the instance list against the existing names.
5494

5495
    """
5496
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
5497

    
5498
    if self.lock_instances:
5499
      affected_instances = \
5500
        self.cfg.GetInstancesInfoByFilter(self._InstanceFilter)
5501

    
5502
      # Verify instance locks
5503
      owned_instances = self.owned_locks(locking.LEVEL_INSTANCE)
5504
      wanted_instances = frozenset(affected_instances.keys())
5505
      if wanted_instances - owned_instances:
5506
        raise errors.OpPrereqError("Instances affected by changing node %s's"
5507
                                   " secondary IP address have changed since"
5508
                                   " locks were acquired, wanted '%s', have"
5509
                                   " '%s'; retry the operation" %
5510
                                   (self.op.node_name,
5511
                                    utils.CommaJoin(wanted_instances),
5512
                                    utils.CommaJoin(owned_instances)),
5513
                                   errors.ECODE_STATE)
5514
    else:
5515
      affected_instances = None
5516

    
5517
    if (self.op.master_candidate is not None or
5518
        self.op.drained is not None or
5519
        self.op.offline is not None):
5520
      # we can't change the master's node flags
5521
      if self.op.node_name == self.cfg.GetMasterNode():
5522
        raise errors.OpPrereqError("The master role can be changed"
5523
                                   " only via master-failover",
5524
                                   errors.ECODE_INVAL)
5525

    
5526
    if self.op.master_candidate and not node.master_capable:
5527
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
5528
                                 " it a master candidate" % node.name,
5529
                                 errors.ECODE_STATE)
5530

    
5531
    if self.op.vm_capable == False:
5532
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
5533
      if ipri or isec:
5534
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
5535
                                   " the vm_capable flag" % node.name,
5536
                                   errors.ECODE_STATE)
5537

    
5538
    if node.master_candidate and self.might_demote and not self.lock_all:
5539
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
5540
      # check if after removing the current node, we're missing master
5541
      # candidates
5542
      (mc_remaining, mc_should, _) = \
5543
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
5544
      if mc_remaining < mc_should:
5545
        raise errors.OpPrereqError("Not enough master candidates, please"
5546
                                   " pass auto promote option to allow"
5547
                                   " promotion", errors.ECODE_STATE)
5548

    
5549
    self.old_flags = old_flags = (node.master_candidate,
5550
                                  node.drained, node.offline)
5551
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
5552
    self.old_role = old_role = self._F2R[old_flags]
5553

    
5554
    # Check for ineffective changes
5555
    for attr in self._FLAGS:
5556
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
5557
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
5558
        setattr(self.op, attr, None)
5559

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

    
5563
    # TODO: We might query the real power state if it supports OOB
5564
    if _SupportsOob(self.cfg, node):
5565
      if self.op.offline is False and not (node.powered or
5566
                                           self.op.powered == True):
5567
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
5568
                                    " offline status can be reset") %
5569
                                   self.op.node_name)
5570
    elif self.op.powered is not None:
5571
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
5572
                                  " as it does not support out-of-band"
5573
                                  " handling") % self.op.node_name)
5574

    
5575
    # If we're being deofflined/drained, we'll MC ourself if needed
5576
    if (self.op.drained == False or self.op.offline == False or
5577
        (self.op.master_capable and not node.master_capable)):
5578
      if _DecideSelfPromotion(self):
5579
        self.op.master_candidate = True
5580
        self.LogInfo("Auto-promoting node to master candidate")
5581

    
5582
    # If we're no longer master capable, we'll demote ourselves from MC
5583
    if self.op.master_capable == False and node.master_candidate:
5584
      self.LogInfo("Demoting from master candidate")
5585
      self.op.master_candidate = False
5586

    
5587
    # Compute new role
5588
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
5589
    if self.op.master_candidate:
5590
      new_role = self._ROLE_CANDIDATE
5591
    elif self.op.drained:
5592
      new_role = self._ROLE_DRAINED
5593
    elif self.op.offline:
5594
      new_role = self._ROLE_OFFLINE
5595
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
5596
      # False is still in new flags, which means we're un-setting (the
5597
      # only) True flag
5598
      new_role = self._ROLE_REGULAR
5599
    else: # no new flags, nothing, keep old role
5600
      new_role = old_role
5601

    
5602
    self.new_role = new_role
5603

    
5604
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
5605
      # Trying to transition out of offline status
5606
      # TODO: Use standard RPC runner, but make sure it works when the node is
5607
      # still marked offline
5608
      result = rpc.BootstrapRunner().call_version([node.name])[node.name]
5609
      if result.fail_msg:
5610
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
5611
                                   " to report its version: %s" %
5612
                                   (node.name, result.fail_msg),
5613
                                   errors.ECODE_STATE)
5614
      else:
5615
        self.LogWarning("Transitioning node from offline to online state"
5616
                        " without using re-add. Please make sure the node"
5617
                        " is healthy!")
5618

    
5619
    if self.op.secondary_ip:
5620
      # Ok even without locking, because this can't be changed by any LU
5621
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
5622
      master_singlehomed = master.secondary_ip == master.primary_ip
5623
      if master_singlehomed and self.op.secondary_ip:
5624
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
5625
                                   " homed cluster", errors.ECODE_INVAL)
5626

    
5627
      assert not (frozenset(affected_instances) -
5628
                  self.owned_locks(locking.LEVEL_INSTANCE))
5629

    
5630
      if node.offline:
5631
        if affected_instances:
5632
          raise errors.OpPrereqError("Cannot change secondary IP address:"
5633
                                     " offline node has instances (%s)"
5634
                                     " configured to use it" %
5635
                                     utils.CommaJoin(affected_instances.keys()))
5636
      else:
5637
        # On online nodes, check that no instances are running, and that
5638
        # the node has the new ip and we can reach it.
5639
        for instance in affected_instances.values():
5640
          _CheckInstanceState(self, instance, INSTANCE_DOWN,
5641
                              msg="cannot change secondary ip")
5642

    
5643
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
5644
        if master.name != node.name:
5645
          # check reachability from master secondary ip to new secondary ip
5646
          if not netutils.TcpPing(self.op.secondary_ip,
5647
                                  constants.DEFAULT_NODED_PORT,
5648
                                  source=master.secondary_ip):
5649
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5650
                                       " based ping to node daemon port",
5651
                                       errors.ECODE_ENVIRON)
5652

    
5653
    if self.op.ndparams:
5654
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
5655
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
5656
      self.new_ndparams = new_ndparams
5657

    
5658
  def Exec(self, feedback_fn):
5659
    """Modifies a node.
5660

5661
    """
5662
    node = self.node
5663
    old_role = self.old_role
5664
    new_role = self.new_role
5665

    
5666
    result = []
5667

    
5668
    if self.op.ndparams:
5669
      node.ndparams = self.new_ndparams
5670

    
5671
    if self.op.powered is not None:
5672
      node.powered = self.op.powered
5673

    
5674
    for attr in ["master_capable", "vm_capable"]:
5675
      val = getattr(self.op, attr)
5676
      if val is not None:
5677
        setattr(node, attr, val)
5678
        result.append((attr, str(val)))
5679

    
5680
    if new_role != old_role:
5681
      # Tell the node to demote itself, if no longer MC and not offline
5682
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5683
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5684
        if msg:
5685
          self.LogWarning("Node failed to demote itself: %s", msg)
5686

    
5687
      new_flags = self._R2F[new_role]
5688
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5689
        if of != nf:
5690
          result.append((desc, str(nf)))
5691
      (node.master_candidate, node.drained, node.offline) = new_flags
5692

    
5693
      # we locked all nodes, we adjust the CP before updating this node
5694
      if self.lock_all:
5695
        _AdjustCandidatePool(self, [node.name])
5696

    
5697
    if self.op.secondary_ip:
5698
      node.secondary_ip = self.op.secondary_ip
5699
      result.append(("secondary_ip", self.op.secondary_ip))
5700

    
5701
    # this will trigger configuration file update, if needed
5702
    self.cfg.Update(node, feedback_fn)
5703

    
5704
    # this will trigger job queue propagation or cleanup if the mc
5705
    # flag changed
5706
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5707
      self.context.ReaddNode(node)
5708

    
5709
    return result
5710

    
5711

    
5712
class LUNodePowercycle(NoHooksLU):
5713
  """Powercycles a node.
5714

5715
  """
5716
  REQ_BGL = False
5717

    
5718
  def CheckArguments(self):
5719
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5720
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5721
      raise errors.OpPrereqError("The node is the master and the force"
5722
                                 " parameter was not set",
5723
                                 errors.ECODE_INVAL)
5724

    
5725
  def ExpandNames(self):
5726
    """Locking for PowercycleNode.
5727

5728
    This is a last-resort option and shouldn't block on other
5729
    jobs. Therefore, we grab no locks.
5730

5731
    """
5732
    self.needed_locks = {}
5733

    
5734
  def Exec(self, feedback_fn):
5735
    """Reboots a node.
5736

5737
    """
5738
    result = self.rpc.call_node_powercycle(self.op.node_name,
5739
                                           self.cfg.GetHypervisorType())
5740
    result.Raise("Failed to schedule the reboot")
5741
    return result.payload
5742

    
5743

    
5744
class LUClusterQuery(NoHooksLU):
5745
  """Query cluster configuration.
5746

5747
  """
5748
  REQ_BGL = False
5749

    
5750
  def ExpandNames(self):
5751
    self.needed_locks = {}
5752

    
5753
  def Exec(self, feedback_fn):
5754
    """Return cluster config.
5755

5756
    """
5757
    cluster = self.cfg.GetClusterInfo()
5758
    os_hvp = {}
5759

    
5760
    # Filter just for enabled hypervisors
5761
    for os_name, hv_dict in cluster.os_hvp.items():
5762
      os_hvp[os_name] = {}
5763
      for hv_name, hv_params in hv_dict.items():
5764
        if hv_name in cluster.enabled_hypervisors:
5765
          os_hvp[os_name][hv_name] = hv_params
5766

    
5767
    # Convert ip_family to ip_version
5768
    primary_ip_version = constants.IP4_VERSION
5769
    if cluster.primary_ip_family == netutils.IP6Address.family:
5770
      primary_ip_version = constants.IP6_VERSION
5771

    
5772
    result = {
5773
      "software_version": constants.RELEASE_VERSION,
5774
      "protocol_version": constants.PROTOCOL_VERSION,
5775
      "config_version": constants.CONFIG_VERSION,
5776
      "os_api_version": max(constants.OS_API_VERSIONS),
5777
      "export_version": constants.EXPORT_VERSION,
5778
      "architecture": (platform.architecture()[0], platform.machine()),
5779
      "name": cluster.cluster_name,
5780
      "master": cluster.master_node,
5781
      "default_hypervisor": cluster.primary_hypervisor,
5782
      "enabled_hypervisors": cluster.enabled_hypervisors,
5783
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5784
                        for hypervisor_name in cluster.enabled_hypervisors]),
5785
      "os_hvp": os_hvp,
5786
      "beparams": cluster.beparams,
5787
      "osparams": cluster.osparams,
5788
      "nicparams": cluster.nicparams,
5789
      "ndparams": cluster.ndparams,
5790
      "candidate_pool_size": cluster.candidate_pool_size,
5791
      "master_netdev": cluster.master_netdev,
5792
      "master_netmask": cluster.master_netmask,
5793
      "use_external_mip_script": cluster.use_external_mip_script,
5794
      "volume_group_name": cluster.volume_group_name,
5795
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5796
      "file_storage_dir": cluster.file_storage_dir,
5797
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5798
      "maintain_node_health": cluster.maintain_node_health,
5799
      "ctime": cluster.ctime,
5800
      "mtime": cluster.mtime,
5801
      "uuid": cluster.uuid,
5802
      "tags": list(cluster.GetTags()),
5803
      "uid_pool": cluster.uid_pool,
5804
      "default_iallocator": cluster.default_iallocator,
5805
      "reserved_lvs": cluster.reserved_lvs,
5806
      "primary_ip_version": primary_ip_version,
5807
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5808
      "hidden_os": cluster.hidden_os,
5809
      "blacklisted_os": cluster.blacklisted_os,
5810
      }
5811

    
5812
    return result
5813

    
5814

    
5815
class LUClusterConfigQuery(NoHooksLU):
5816
  """Return configuration values.
5817

5818
  """
5819
  REQ_BGL = False
5820
  _FIELDS_DYNAMIC = utils.FieldSet()
5821
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5822
                                  "watcher_pause", "volume_group_name")
5823

    
5824
  def CheckArguments(self):
5825
    _CheckOutputFields(static=self._FIELDS_STATIC,
5826
                       dynamic=self._FIELDS_DYNAMIC,
5827
                       selected=self.op.output_fields)
5828

    
5829
  def ExpandNames(self):
5830
    self.needed_locks = {}
5831

    
5832
  def Exec(self, feedback_fn):
5833
    """Dump a representation of the cluster config to the standard output.
5834

5835
    """
5836
    values = []
5837
    for field in self.op.output_fields:
5838
      if field == "cluster_name":
5839
        entry = self.cfg.GetClusterName()
5840
      elif field == "master_node":
5841
        entry = self.cfg.GetMasterNode()
5842
      elif field == "drain_flag":
5843
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5844
      elif field == "watcher_pause":
5845
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5846
      elif field == "volume_group_name":
5847
        entry = self.cfg.GetVGName()
5848
      else:
5849
        raise errors.ParameterError(field)
5850
      values.append(entry)
5851
    return values
5852

    
5853

    
5854
class LUInstanceActivateDisks(NoHooksLU):
5855
  """Bring up an instance's disks.
5856

5857
  """
5858
  REQ_BGL = False
5859

    
5860
  def ExpandNames(self):
5861
    self._ExpandAndLockInstance()
5862
    self.needed_locks[locking.LEVEL_NODE] = []
5863
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5864

    
5865
  def DeclareLocks(self, level):
5866
    if level == locking.LEVEL_NODE:
5867
      self._LockInstancesNodes()
5868

    
5869
  def CheckPrereq(self):
5870
    """Check prerequisites.
5871

5872
    This checks that the instance is in the cluster.
5873

5874
    """
5875
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5876
    assert self.instance is not None, \
5877
      "Cannot retrieve locked instance %s" % self.op.instance_name
5878
    _CheckNodeOnline(self, self.instance.primary_node)
5879

    
5880
  def Exec(self, feedback_fn):
5881
    """Activate the disks.
5882

5883
    """
5884
    disks_ok, disks_info = \
5885
              _AssembleInstanceDisks(self, self.instance,
5886
                                     ignore_size=self.op.ignore_size)
5887
    if not disks_ok:
5888
      raise errors.OpExecError("Cannot activate block devices")
5889

    
5890
    return disks_info
5891

    
5892

    
5893
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5894
                           ignore_size=False):
5895
  """Prepare the block devices for an instance.
5896

5897
  This sets up the block devices on all nodes.
5898

5899
  @type lu: L{LogicalUnit}
5900
  @param lu: the logical unit on whose behalf we execute
5901
  @type instance: L{objects.Instance}
5902
  @param instance: the instance for whose disks we assemble
5903
  @type disks: list of L{objects.Disk} or None
5904
  @param disks: which disks to assemble (or all, if None)
5905
  @type ignore_secondaries: boolean
5906
  @param ignore_secondaries: if true, errors on secondary nodes
5907
      won't result in an error return from the function
5908
  @type ignore_size: boolean
5909
  @param ignore_size: if true, the current known size of the disk
5910
      will not be used during the disk activation, useful for cases
5911
      when the size is wrong
5912
  @return: False if the operation failed, otherwise a list of
5913
      (host, instance_visible_name, node_visible_name)
5914
      with the mapping from node devices to instance devices
5915

5916
  """
5917
  device_info = []
5918
  disks_ok = True
5919
  iname = instance.name
5920
  disks = _ExpandCheckDisks(instance, disks)
5921

    
5922
  # With the two passes mechanism we try to reduce the window of
5923
  # opportunity for the race condition of switching DRBD to primary
5924
  # before handshaking occured, but we do not eliminate it
5925

    
5926
  # The proper fix would be to wait (with some limits) until the
5927
  # connection has been made and drbd transitions from WFConnection
5928
  # into any other network-connected state (Connected, SyncTarget,
5929
  # SyncSource, etc.)
5930

    
5931
  # 1st pass, assemble on all nodes in secondary mode
5932
  for idx, inst_disk in enumerate(disks):
5933
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5934
      if ignore_size:
5935
        node_disk = node_disk.Copy()
5936
        node_disk.UnsetSize()
5937
      lu.cfg.SetDiskID(node_disk, node)
5938
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5939
      msg = result.fail_msg
5940
      if msg:
5941
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5942
                           " (is_primary=False, pass=1): %s",
5943
                           inst_disk.iv_name, node, msg)
5944
        if not ignore_secondaries:
5945
          disks_ok = False
5946

    
5947
  # FIXME: race condition on drbd migration to primary
5948

    
5949
  # 2nd pass, do only the primary node
5950
  for idx, inst_disk in enumerate(disks):
5951
    dev_path = None
5952

    
5953
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5954
      if node != instance.primary_node:
5955
        continue
5956
      if ignore_size:
5957
        node_disk = node_disk.Copy()
5958
        node_disk.UnsetSize()
5959
      lu.cfg.SetDiskID(node_disk, node)
5960
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5961
      msg = result.fail_msg
5962
      if msg:
5963
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5964
                           " (is_primary=True, pass=2): %s",
5965
                           inst_disk.iv_name, node, msg)
5966
        disks_ok = False
5967
      else:
5968
        dev_path = result.payload
5969

    
5970
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5971

    
5972
  # leave the disks configured for the primary node
5973
  # this is a workaround that would be fixed better by
5974
  # improving the logical/physical id handling
5975
  for disk in disks:
5976
    lu.cfg.SetDiskID(disk, instance.primary_node)
5977

    
5978
  return disks_ok, device_info
5979

    
5980

    
5981
def _StartInstanceDisks(lu, instance, force):
5982
  """Start the disks of an instance.
5983

5984
  """
5985
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5986
                                           ignore_secondaries=force)
5987
  if not disks_ok:
5988
    _ShutdownInstanceDisks(lu, instance)
5989
    if force is not None and not force:
5990
      lu.proc.LogWarning("", hint="If the message above refers to a"
5991
                         " secondary node,"
5992
                         " you can retry the operation using '--force'.")
5993
    raise errors.OpExecError("Disk consistency error")
5994

    
5995

    
5996
class LUInstanceDeactivateDisks(NoHooksLU):
5997
  """Shutdown an instance's disks.
5998

5999
  """
6000
  REQ_BGL = False
6001

    
6002
  def ExpandNames(self):
6003
    self._ExpandAndLockInstance()
6004
    self.needed_locks[locking.LEVEL_NODE] = []
6005
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6006

    
6007
  def DeclareLocks(self, level):
6008
    if level == locking.LEVEL_NODE:
6009
      self._LockInstancesNodes()
6010

    
6011
  def CheckPrereq(self):
6012
    """Check prerequisites.
6013

6014
    This checks that the instance is in the cluster.
6015

6016
    """
6017
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6018
    assert self.instance is not None, \
6019
      "Cannot retrieve locked instance %s" % self.op.instance_name
6020

    
6021
  def Exec(self, feedback_fn):
6022
    """Deactivate the disks
6023

6024
    """
6025
    instance = self.instance
6026
    if self.op.force:
6027
      _ShutdownInstanceDisks(self, instance)
6028
    else:
6029
      _SafeShutdownInstanceDisks(self, instance)
6030

    
6031

    
6032
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
6033
  """Shutdown block devices of an instance.
6034

6035
  This function checks if an instance is running, before calling
6036
  _ShutdownInstanceDisks.
6037

6038
  """
6039
  _CheckInstanceState(lu, instance, INSTANCE_DOWN, msg="cannot shutdown disks")
6040
  _ShutdownInstanceDisks(lu, instance, disks=disks)
6041

    
6042

    
6043
def _ExpandCheckDisks(instance, disks):
6044
  """Return the instance disks selected by the disks list
6045

6046
  @type disks: list of L{objects.Disk} or None
6047
  @param disks: selected disks
6048
  @rtype: list of L{objects.Disk}
6049
  @return: selected instance disks to act on
6050

6051
  """
6052
  if disks is None:
6053
    return instance.disks
6054
  else:
6055
    if not set(disks).issubset(instance.disks):
6056
      raise errors.ProgrammerError("Can only act on disks belonging to the"
6057
                                   " target instance")
6058
    return disks
6059

    
6060

    
6061
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
6062
  """Shutdown block devices of an instance.
6063

6064
  This does the shutdown on all nodes of the instance.
6065

6066
  If the ignore_primary is false, errors on the primary node are
6067
  ignored.
6068

6069
  """
6070
  all_result = True
6071
  disks = _ExpandCheckDisks(instance, disks)
6072

    
6073
  for disk in disks:
6074
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
6075
      lu.cfg.SetDiskID(top_disk, node)
6076
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
6077
      msg = result.fail_msg
6078
      if msg:
6079
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
6080
                      disk.iv_name, node, msg)
6081
        if ((node == instance.primary_node and not ignore_primary) or
6082
            (node != instance.primary_node and not result.offline)):
6083
          all_result = False
6084
  return all_result
6085

    
6086

    
6087
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
6088
  """Checks if a node has enough free memory.
6089

6090
  This function check if a given node has the needed amount of free
6091
  memory. In case the node has less memory or we cannot get the
6092
  information from the node, this function raise an OpPrereqError
6093
  exception.
6094

6095
  @type lu: C{LogicalUnit}
6096
  @param lu: a logical unit from which we get configuration data
6097
  @type node: C{str}
6098
  @param node: the node to check
6099
  @type reason: C{str}
6100
  @param reason: string to use in the error message
6101
  @type requested: C{int}
6102
  @param requested: the amount of memory in MiB to check for
6103
  @type hypervisor_name: C{str}
6104
  @param hypervisor_name: the hypervisor to ask for memory stats
6105
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
6106
      we cannot check the node
6107

6108
  """
6109
  nodeinfo = lu.rpc.call_node_info([node], None, [hypervisor_name])
6110
  nodeinfo[node].Raise("Can't get data from node %s" % node,
6111
                       prereq=True, ecode=errors.ECODE_ENVIRON)
6112
  (_, _, (hv_info, )) = nodeinfo[node].payload
6113

    
6114
  free_mem = hv_info.get("memory_free", None)
6115
  if not isinstance(free_mem, int):
6116
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
6117
                               " was '%s'" % (node, free_mem),
6118
                               errors.ECODE_ENVIRON)
6119
  if requested > free_mem:
6120
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
6121
                               " needed %s MiB, available %s MiB" %
6122
                               (node, reason, requested, free_mem),
6123
                               errors.ECODE_NORES)
6124

    
6125

    
6126
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
6127
  """Checks if nodes have enough free disk space in the all VGs.
6128

6129
  This function check if all given nodes have the needed amount of
6130
  free disk. In case any node has less disk or we cannot get the
6131
  information from the node, this function raise an OpPrereqError
6132
  exception.
6133

6134
  @type lu: C{LogicalUnit}
6135
  @param lu: a logical unit from which we get configuration data
6136
  @type nodenames: C{list}
6137
  @param nodenames: the list of node names to check
6138
  @type req_sizes: C{dict}
6139
  @param req_sizes: the hash of vg and corresponding amount of disk in
6140
      MiB to check for
6141
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
6142
      or we cannot check the node
6143

6144
  """
6145
  for vg, req_size in req_sizes.items():
6146
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
6147

    
6148

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

6152
  This function check if all given nodes have the needed amount of
6153
  free disk. In case any node has less disk or we cannot get the
6154
  information from the node, this function raise an OpPrereqError
6155
  exception.
6156

6157
  @type lu: C{LogicalUnit}
6158
  @param lu: a logical unit from which we get configuration data
6159
  @type nodenames: C{list}
6160
  @param nodenames: the list of node names to check
6161
  @type vg: C{str}
6162
  @param vg: the volume group to check
6163
  @type requested: C{int}
6164
  @param requested: the amount of disk in MiB to check for
6165
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
6166
      or we cannot check the node
6167

6168
  """
6169
  nodeinfo = lu.rpc.call_node_info(nodenames, [vg], None)
6170
  for node in nodenames:
6171
    info = nodeinfo[node]
6172
    info.Raise("Cannot get current information from node %s" % node,
6173
               prereq=True, ecode=errors.ECODE_ENVIRON)
6174
    (_, (vg_info, ), _) = info.payload
6175
    vg_free = vg_info.get("vg_free", None)
6176
    if not isinstance(vg_free, int):
6177
      raise errors.OpPrereqError("Can't compute free disk space on node"
6178
                                 " %s for vg %s, result was '%s'" %
6179
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
6180
    if requested > vg_free:
6181
      raise errors.OpPrereqError("Not enough disk space on target node %s"
6182
                                 " vg %s: required %d MiB, available %d MiB" %
6183
                                 (node, vg, requested, vg_free),
6184
                                 errors.ECODE_NORES)
6185

    
6186

    
6187
def _CheckNodesPhysicalCPUs(lu, nodenames, requested, hypervisor_name):
6188
  """Checks if nodes have enough physical CPUs
6189

6190
  This function checks if all given nodes have the needed number of
6191
  physical CPUs. In case any node has less CPUs or we cannot get the
6192
  information from the node, this function raises an OpPrereqError
6193
  exception.
6194

6195
  @type lu: C{LogicalUnit}
6196
  @param lu: a logical unit from which we get configuration data
6197
  @type nodenames: C{list}
6198
  @param nodenames: the list of node names to check
6199
  @type requested: C{int}
6200
  @param requested: the minimum acceptable number of physical CPUs
6201
  @raise errors.OpPrereqError: if the node doesn't have enough CPUs,
6202
      or we cannot check the node
6203

6204
  """
6205
  nodeinfo = lu.rpc.call_node_info(nodenames, None, [hypervisor_name])
6206
  for node in nodenames:
6207
    info = nodeinfo[node]
6208
    info.Raise("Cannot get current information from node %s" % node,
6209
               prereq=True, ecode=errors.ECODE_ENVIRON)
6210
    (_, _, (hv_info, )) = info.payload
6211
    num_cpus = hv_info.get("cpu_total", None)
6212
    if not isinstance(num_cpus, int):
6213
      raise errors.OpPrereqError("Can't compute the number of physical CPUs"
6214
                                 " on node %s, result was '%s'" %
6215
                                 (node, num_cpus), errors.ECODE_ENVIRON)
6216
    if requested > num_cpus:
6217
      raise errors.OpPrereqError("Node %s has %s physical CPUs, but %s are "
6218
                                 "required" % (node, num_cpus, requested),
6219
                                 errors.ECODE_NORES)
6220

    
6221

    
6222
class LUInstanceStartup(LogicalUnit):
6223
  """Starts an instance.
6224

6225
  """
6226
  HPATH = "instance-start"
6227
  HTYPE = constants.HTYPE_INSTANCE
6228
  REQ_BGL = False
6229

    
6230
  def CheckArguments(self):
6231
    # extra beparams
6232
    if self.op.beparams:
6233
      # fill the beparams dict
6234
      objects.UpgradeBeParams(self.op.beparams)
6235
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6236

    
6237
  def ExpandNames(self):
6238
    self._ExpandAndLockInstance()
6239

    
6240
  def BuildHooksEnv(self):
6241
    """Build hooks env.
6242

6243
    This runs on master, primary and secondary nodes of the instance.
6244

6245
    """
6246
    env = {
6247
      "FORCE": self.op.force,
6248
      }
6249

    
6250
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6251

    
6252
    return env
6253

    
6254
  def BuildHooksNodes(self):
6255
    """Build hooks nodes.
6256

6257
    """
6258
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6259
    return (nl, nl)
6260

    
6261
  def CheckPrereq(self):
6262
    """Check prerequisites.
6263

6264
    This checks that the instance is in the cluster.
6265

6266
    """
6267
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6268
    assert self.instance is not None, \
6269
      "Cannot retrieve locked instance %s" % self.op.instance_name
6270

    
6271
    # extra hvparams
6272
    if self.op.hvparams:
6273
      # check hypervisor parameter syntax (locally)
6274
      cluster = self.cfg.GetClusterInfo()
6275
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6276
      filled_hvp = cluster.FillHV(instance)
6277
      filled_hvp.update(self.op.hvparams)
6278
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
6279
      hv_type.CheckParameterSyntax(filled_hvp)
6280
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
6281

    
6282
    _CheckInstanceState(self, instance, INSTANCE_ONLINE)
6283

    
6284
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
6285

    
6286
    if self.primary_offline and self.op.ignore_offline_nodes:
6287
      self.proc.LogWarning("Ignoring offline primary node")
6288

    
6289
      if self.op.hvparams or self.op.beparams:
6290
        self.proc.LogWarning("Overridden parameters are ignored")
6291
    else:
6292
      _CheckNodeOnline(self, instance.primary_node)
6293

    
6294
      bep = self.cfg.GetClusterInfo().FillBE(instance)
6295

    
6296
      # check bridges existence
6297
      _CheckInstanceBridgesExist(self, instance)
6298

    
6299
      remote_info = self.rpc.call_instance_info(instance.primary_node,
6300
                                                instance.name,
6301
                                                instance.hypervisor)
6302
      remote_info.Raise("Error checking node %s" % instance.primary_node,
6303
                        prereq=True, ecode=errors.ECODE_ENVIRON)
6304
      if not remote_info.payload: # not running already
6305
        _CheckNodeFreeMemory(self, instance.primary_node,
6306
                             "starting instance %s" % instance.name,
6307
                             bep[constants.BE_MAXMEM], instance.hypervisor)
6308

    
6309
  def Exec(self, feedback_fn):
6310
    """Start the instance.
6311

6312
    """
6313
    instance = self.instance
6314
    force = self.op.force
6315

    
6316
    if not self.op.no_remember:
6317
      self.cfg.MarkInstanceUp(instance.name)
6318

    
6319
    if self.primary_offline:
6320
      assert self.op.ignore_offline_nodes
6321
      self.proc.LogInfo("Primary node offline, marked instance as started")
6322
    else:
6323
      node_current = instance.primary_node
6324

    
6325
      _StartInstanceDisks(self, instance, force)
6326

    
6327
      result = \
6328
        self.rpc.call_instance_start(node_current,
6329
                                     (instance, self.op.hvparams,
6330
                                      self.op.beparams),
6331
                                     self.op.startup_paused)
6332
      msg = result.fail_msg
6333
      if msg:
6334
        _ShutdownInstanceDisks(self, instance)
6335
        raise errors.OpExecError("Could not start instance: %s" % msg)
6336

    
6337

    
6338
class LUInstanceReboot(LogicalUnit):
6339
  """Reboot an instance.
6340

6341
  """
6342
  HPATH = "instance-reboot"
6343
  HTYPE = constants.HTYPE_INSTANCE
6344
  REQ_BGL = False
6345

    
6346
  def ExpandNames(self):
6347
    self._ExpandAndLockInstance()
6348

    
6349
  def BuildHooksEnv(self):
6350
    """Build hooks env.
6351

6352
    This runs on master, primary and secondary nodes of the instance.
6353

6354
    """
6355
    env = {
6356
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
6357
      "REBOOT_TYPE": self.op.reboot_type,
6358
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6359
      }
6360

    
6361
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6362

    
6363
    return env
6364

    
6365
  def BuildHooksNodes(self):
6366
    """Build hooks nodes.
6367

6368
    """
6369
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6370
    return (nl, nl)
6371

    
6372
  def CheckPrereq(self):
6373
    """Check prerequisites.
6374

6375
    This checks that the instance is in the cluster.
6376

6377
    """
6378
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6379
    assert self.instance is not None, \
6380
      "Cannot retrieve locked instance %s" % self.op.instance_name
6381
    _CheckInstanceState(self, instance, INSTANCE_ONLINE)
6382
    _CheckNodeOnline(self, instance.primary_node)
6383

    
6384
    # check bridges existence
6385
    _CheckInstanceBridgesExist(self, instance)
6386

    
6387
  def Exec(self, feedback_fn):
6388
    """Reboot the instance.
6389

6390
    """
6391
    instance = self.instance
6392
    ignore_secondaries = self.op.ignore_secondaries
6393
    reboot_type = self.op.reboot_type
6394

    
6395
    remote_info = self.rpc.call_instance_info(instance.primary_node,
6396
                                              instance.name,
6397
                                              instance.hypervisor)
6398
    remote_info.Raise("Error checking node %s" % instance.primary_node)
6399
    instance_running = bool(remote_info.payload)
6400

    
6401
    node_current = instance.primary_node
6402

    
6403
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
6404
                                            constants.INSTANCE_REBOOT_HARD]:
6405
      for disk in instance.disks:
6406
        self.cfg.SetDiskID(disk, node_current)
6407
      result = self.rpc.call_instance_reboot(node_current, instance,
6408
                                             reboot_type,
6409
                                             self.op.shutdown_timeout)
6410
      result.Raise("Could not reboot instance")
6411
    else:
6412
      if instance_running:
6413
        result = self.rpc.call_instance_shutdown(node_current, instance,
6414
                                                 self.op.shutdown_timeout)
6415
        result.Raise("Could not shutdown instance for full reboot")
6416
        _ShutdownInstanceDisks(self, instance)
6417
      else:
6418
        self.LogInfo("Instance %s was already stopped, starting now",
6419
                     instance.name)
6420
      _StartInstanceDisks(self, instance, ignore_secondaries)
6421
      result = self.rpc.call_instance_start(node_current,
6422
                                            (instance, None, None), False)
6423
      msg = result.fail_msg
6424
      if msg:
6425
        _ShutdownInstanceDisks(self, instance)
6426
        raise errors.OpExecError("Could not start instance for"
6427
                                 " full reboot: %s" % msg)
6428

    
6429
    self.cfg.MarkInstanceUp(instance.name)
6430

    
6431

    
6432
class LUInstanceShutdown(LogicalUnit):
6433
  """Shutdown an instance.
6434

6435
  """
6436
  HPATH = "instance-stop"
6437
  HTYPE = constants.HTYPE_INSTANCE
6438
  REQ_BGL = False
6439

    
6440
  def ExpandNames(self):
6441
    self._ExpandAndLockInstance()
6442

    
6443
  def BuildHooksEnv(self):
6444
    """Build hooks env.
6445

6446
    This runs on master, primary and secondary nodes of the instance.
6447

6448
    """
6449
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6450
    env["TIMEOUT"] = self.op.timeout
6451
    return env
6452

    
6453
  def BuildHooksNodes(self):
6454
    """Build hooks nodes.
6455

6456
    """
6457
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6458
    return (nl, nl)
6459

    
6460
  def CheckPrereq(self):
6461
    """Check prerequisites.
6462

6463
    This checks that the instance is in the cluster.
6464

6465
    """
6466
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6467
    assert self.instance is not None, \
6468
      "Cannot retrieve locked instance %s" % self.op.instance_name
6469

    
6470
    _CheckInstanceState(self, self.instance, INSTANCE_ONLINE)
6471

    
6472
    self.primary_offline = \
6473
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
6474

    
6475
    if self.primary_offline and self.op.ignore_offline_nodes:
6476
      self.proc.LogWarning("Ignoring offline primary node")
6477
    else:
6478
      _CheckNodeOnline(self, self.instance.primary_node)
6479

    
6480
  def Exec(self, feedback_fn):
6481
    """Shutdown the instance.
6482

6483
    """
6484
    instance = self.instance
6485
    node_current = instance.primary_node
6486
    timeout = self.op.timeout
6487

    
6488
    if not self.op.no_remember:
6489
      self.cfg.MarkInstanceDown(instance.name)
6490

    
6491
    if self.primary_offline:
6492
      assert self.op.ignore_offline_nodes
6493
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
6494
    else:
6495
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
6496
      msg = result.fail_msg
6497
      if msg:
6498
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
6499

    
6500
      _ShutdownInstanceDisks(self, instance)
6501

    
6502

    
6503
class LUInstanceReinstall(LogicalUnit):
6504
  """Reinstall an instance.
6505

6506
  """
6507
  HPATH = "instance-reinstall"
6508
  HTYPE = constants.HTYPE_INSTANCE
6509
  REQ_BGL = False
6510

    
6511
  def ExpandNames(self):
6512
    self._ExpandAndLockInstance()
6513

    
6514
  def BuildHooksEnv(self):
6515
    """Build hooks env.
6516

6517
    This runs on master, primary and secondary nodes of the instance.
6518

6519
    """
6520
    return _BuildInstanceHookEnvByObject(self, self.instance)
6521

    
6522
  def BuildHooksNodes(self):
6523
    """Build hooks nodes.
6524

6525
    """
6526
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6527
    return (nl, nl)
6528

    
6529
  def CheckPrereq(self):
6530
    """Check prerequisites.
6531

6532
    This checks that the instance is in the cluster and is not running.
6533

6534
    """
6535
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6536
    assert instance is not None, \
6537
      "Cannot retrieve locked instance %s" % self.op.instance_name
6538
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
6539
                     " offline, cannot reinstall")
6540
    for node in instance.secondary_nodes:
6541
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
6542
                       " cannot reinstall")
6543

    
6544
    if instance.disk_template == constants.DT_DISKLESS:
6545
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6546
                                 self.op.instance_name,
6547
                                 errors.ECODE_INVAL)
6548
    _CheckInstanceState(self, instance, INSTANCE_DOWN, msg="cannot reinstall")
6549

    
6550
    if self.op.os_type is not None:
6551
      # OS verification
6552
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
6553
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
6554
      instance_os = self.op.os_type
6555
    else:
6556
      instance_os = instance.os
6557

    
6558
    nodelist = list(instance.all_nodes)
6559

    
6560
    if self.op.osparams:
6561
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
6562
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
6563
      self.os_inst = i_osdict # the new dict (without defaults)
6564
    else:
6565
      self.os_inst = None
6566

    
6567
    self.instance = instance
6568

    
6569
  def Exec(self, feedback_fn):
6570
    """Reinstall the instance.
6571

6572
    """
6573
    inst = self.instance
6574

    
6575
    if self.op.os_type is not None:
6576
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
6577
      inst.os = self.op.os_type
6578
      # Write to configuration
6579
      self.cfg.Update(inst, feedback_fn)
6580

    
6581
    _StartInstanceDisks(self, inst, None)
6582
    try:
6583
      feedback_fn("Running the instance OS create scripts...")
6584
      # FIXME: pass debug option from opcode to backend
6585
      result = self.rpc.call_instance_os_add(inst.primary_node,
6586
                                             (inst, self.os_inst), True,
6587
                                             self.op.debug_level)
6588
      result.Raise("Could not install OS for instance %s on node %s" %
6589
                   (inst.name, inst.primary_node))
6590
    finally:
6591
      _ShutdownInstanceDisks(self, inst)
6592

    
6593

    
6594
class LUInstanceRecreateDisks(LogicalUnit):
6595
  """Recreate an instance's missing disks.
6596

6597
  """
6598
  HPATH = "instance-recreate-disks"
6599
  HTYPE = constants.HTYPE_INSTANCE
6600
  REQ_BGL = False
6601

    
6602
  def CheckArguments(self):
6603
    # normalise the disk list
6604
    self.op.disks = sorted(frozenset(self.op.disks))
6605

    
6606
  def ExpandNames(self):
6607
    self._ExpandAndLockInstance()
6608
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6609
    if self.op.nodes:
6610
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
6611
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
6612
    else:
6613
      self.needed_locks[locking.LEVEL_NODE] = []
6614

    
6615
  def DeclareLocks(self, level):
6616
    if level == locking.LEVEL_NODE:
6617
      # if we replace the nodes, we only need to lock the old primary,
6618
      # otherwise we need to lock all nodes for disk re-creation
6619
      primary_only = bool(self.op.nodes)
6620
      self._LockInstancesNodes(primary_only=primary_only)
6621
    elif level == locking.LEVEL_NODE_RES:
6622
      # Copy node locks
6623
      self.needed_locks[locking.LEVEL_NODE_RES] = \
6624
        self.needed_locks[locking.LEVEL_NODE][:]
6625

    
6626
  def BuildHooksEnv(self):
6627
    """Build hooks env.
6628

6629
    This runs on master, primary and secondary nodes of the instance.
6630

6631
    """
6632
    return _BuildInstanceHookEnvByObject(self, self.instance)
6633

    
6634
  def BuildHooksNodes(self):
6635
    """Build hooks nodes.
6636

6637
    """
6638
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6639
    return (nl, nl)
6640

    
6641
  def CheckPrereq(self):
6642
    """Check prerequisites.
6643

6644
    This checks that the instance is in the cluster and is not running.
6645

6646
    """
6647
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6648
    assert instance is not None, \
6649
      "Cannot retrieve locked instance %s" % self.op.instance_name
6650
    if self.op.nodes:
6651
      if len(self.op.nodes) != len(instance.all_nodes):
6652
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6653
                                   " %d replacement nodes were specified" %
6654
                                   (instance.name, len(instance.all_nodes),
6655
                                    len(self.op.nodes)),
6656
                                   errors.ECODE_INVAL)
6657
      assert instance.disk_template != constants.DT_DRBD8 or \
6658
          len(self.op.nodes) == 2
6659
      assert instance.disk_template != constants.DT_PLAIN or \
6660
          len(self.op.nodes) == 1
6661
      primary_node = self.op.nodes[0]
6662
    else:
6663
      primary_node = instance.primary_node
6664
    _CheckNodeOnline(self, primary_node)
6665

    
6666
    if instance.disk_template == constants.DT_DISKLESS:
6667
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6668
                                 self.op.instance_name, errors.ECODE_INVAL)
6669
    # if we replace nodes *and* the old primary is offline, we don't
6670
    # check
6671
    assert instance.primary_node in self.owned_locks(locking.LEVEL_NODE)
6672
    assert instance.primary_node in self.owned_locks(locking.LEVEL_NODE_RES)
6673
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6674
    if not (self.op.nodes and old_pnode.offline):
6675
      _CheckInstanceState(self, instance, INSTANCE_NOT_RUNNING,
6676
                          msg="cannot recreate disks")
6677

    
6678
    if not self.op.disks:
6679
      self.op.disks = range(len(instance.disks))
6680
    else:
6681
      for idx in self.op.disks:
6682
        if idx >= len(instance.disks):
6683
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6684
                                     errors.ECODE_INVAL)
6685
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6686
      raise errors.OpPrereqError("Can't recreate disks partially and"
6687
                                 " change the nodes at the same time",
6688
                                 errors.ECODE_INVAL)
6689
    self.instance = instance
6690

    
6691
  def Exec(self, feedback_fn):
6692
    """Recreate the disks.
6693

6694
    """
6695
    instance = self.instance
6696

    
6697
    assert (self.owned_locks(locking.LEVEL_NODE) ==
6698
            self.owned_locks(locking.LEVEL_NODE_RES))
6699

    
6700
    to_skip = []
6701
    mods = [] # keeps track of needed logical_id changes
6702

    
6703
    for idx, disk in enumerate(instance.disks):
6704
      if idx not in self.op.disks: # disk idx has not been passed in
6705
        to_skip.append(idx)
6706
        continue
6707
      # update secondaries for disks, if needed
6708
      if self.op.nodes:
6709
        if disk.dev_type == constants.LD_DRBD8:
6710
          # need to update the nodes and minors
6711
          assert len(self.op.nodes) == 2
6712
          assert len(disk.logical_id) == 6 # otherwise disk internals
6713
                                           # have changed
6714
          (_, _, old_port, _, _, old_secret) = disk.logical_id
6715
          new_minors = self.cfg.AllocateDRBDMinor(self.op.nodes, instance.name)
6716
          new_id = (self.op.nodes[0], self.op.nodes[1], old_port,
6717
                    new_minors[0], new_minors[1], old_secret)
6718
          assert len(disk.logical_id) == len(new_id)
6719
          mods.append((idx, new_id))
6720

    
6721
    # now that we have passed all asserts above, we can apply the mods
6722
    # in a single run (to avoid partial changes)
6723
    for idx, new_id in mods:
6724
      instance.disks[idx].logical_id = new_id
6725

    
6726
    # change primary node, if needed
6727
    if self.op.nodes:
6728
      instance.primary_node = self.op.nodes[0]
6729
      self.LogWarning("Changing the instance's nodes, you will have to"
6730
                      " remove any disks left on the older nodes manually")
6731

    
6732
    if self.op.nodes:
6733
      self.cfg.Update(instance, feedback_fn)
6734

    
6735
    _CreateDisks(self, instance, to_skip=to_skip)
6736

    
6737

    
6738
class LUInstanceRename(LogicalUnit):
6739
  """Rename an instance.
6740

6741
  """
6742
  HPATH = "instance-rename"
6743
  HTYPE = constants.HTYPE_INSTANCE
6744

    
6745
  def CheckArguments(self):
6746
    """Check arguments.
6747

6748
    """
6749
    if self.op.ip_check and not self.op.name_check:
6750
      # TODO: make the ip check more flexible and not depend on the name check
6751
      raise errors.OpPrereqError("IP address check requires a name check",
6752
                                 errors.ECODE_INVAL)
6753

    
6754
  def BuildHooksEnv(self):
6755
    """Build hooks env.
6756

6757
    This runs on master, primary and secondary nodes of the instance.
6758

6759
    """
6760
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6761
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6762
    return env
6763

    
6764
  def BuildHooksNodes(self):
6765
    """Build hooks nodes.
6766

6767
    """
6768
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6769
    return (nl, nl)
6770

    
6771
  def CheckPrereq(self):
6772
    """Check prerequisites.
6773

6774
    This checks that the instance is in the cluster and is not running.
6775

6776
    """
6777
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6778
                                                self.op.instance_name)
6779
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6780
    assert instance is not None
6781
    _CheckNodeOnline(self, instance.primary_node)
6782
    _CheckInstanceState(self, instance, INSTANCE_NOT_RUNNING,
6783
                        msg="cannot rename")
6784
    self.instance = instance
6785

    
6786
    new_name = self.op.new_name
6787
    if self.op.name_check:
6788
      hostname = netutils.GetHostname(name=new_name)
6789
      if hostname.name != new_name:
6790
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6791
                     hostname.name)
6792
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6793
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6794
                                    " same as given hostname '%s'") %
6795
                                    (hostname.name, self.op.new_name),
6796
                                    errors.ECODE_INVAL)
6797
      new_name = self.op.new_name = hostname.name
6798
      if (self.op.ip_check and
6799
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6800
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6801
                                   (hostname.ip, new_name),
6802
                                   errors.ECODE_NOTUNIQUE)
6803

    
6804
    instance_list = self.cfg.GetInstanceList()
6805
    if new_name in instance_list and new_name != instance.name:
6806
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6807
                                 new_name, errors.ECODE_EXISTS)
6808

    
6809
  def Exec(self, feedback_fn):
6810
    """Rename the instance.
6811

6812
    """
6813
    inst = self.instance
6814
    old_name = inst.name
6815

    
6816
    rename_file_storage = False
6817
    if (inst.disk_template in constants.DTS_FILEBASED and
6818
        self.op.new_name != inst.name):
6819
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6820
      rename_file_storage = True
6821

    
6822
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6823
    # Change the instance lock. This is definitely safe while we hold the BGL.
6824
    # Otherwise the new lock would have to be added in acquired mode.
6825
    assert self.REQ_BGL
6826
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6827
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6828

    
6829
    # re-read the instance from the configuration after rename
6830
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6831

    
6832
    if rename_file_storage:
6833
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6834
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6835
                                                     old_file_storage_dir,
6836
                                                     new_file_storage_dir)
6837
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6838
                   " (but the instance has been renamed in Ganeti)" %
6839
                   (inst.primary_node, old_file_storage_dir,
6840
                    new_file_storage_dir))
6841

    
6842
    _StartInstanceDisks(self, inst, None)
6843
    try:
6844
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6845
                                                 old_name, self.op.debug_level)
6846
      msg = result.fail_msg
6847
      if msg:
6848
        msg = ("Could not run OS rename script for instance %s on node %s"
6849
               " (but the instance has been renamed in Ganeti): %s" %
6850
               (inst.name, inst.primary_node, msg))
6851
        self.proc.LogWarning(msg)
6852
    finally:
6853
      _ShutdownInstanceDisks(self, inst)
6854

    
6855
    return inst.name
6856

    
6857

    
6858
class LUInstanceRemove(LogicalUnit):
6859
  """Remove an instance.
6860

6861
  """
6862
  HPATH = "instance-remove"
6863
  HTYPE = constants.HTYPE_INSTANCE
6864
  REQ_BGL = False
6865

    
6866
  def ExpandNames(self):
6867
    self._ExpandAndLockInstance()
6868
    self.needed_locks[locking.LEVEL_NODE] = []
6869
    self.needed_locks[locking.LEVEL_NODE_RES] = []
6870
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6871

    
6872
  def DeclareLocks(self, level):
6873
    if level == locking.LEVEL_NODE:
6874
      self._LockInstancesNodes()
6875
    elif level == locking.LEVEL_NODE_RES:
6876
      # Copy node locks
6877
      self.needed_locks[locking.LEVEL_NODE_RES] = \
6878
        self.needed_locks[locking.LEVEL_NODE][:]
6879

    
6880
  def BuildHooksEnv(self):
6881
    """Build hooks env.
6882

6883
    This runs on master, primary and secondary nodes of the instance.
6884

6885
    """
6886
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6887
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6888
    return env
6889

    
6890
  def BuildHooksNodes(self):
6891
    """Build hooks nodes.
6892

6893
    """
6894
    nl = [self.cfg.GetMasterNode()]
6895
    nl_post = list(self.instance.all_nodes) + nl
6896
    return (nl, nl_post)
6897

    
6898
  def CheckPrereq(self):
6899
    """Check prerequisites.
6900

6901
    This checks that the instance is in the cluster.
6902

6903
    """
6904
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6905
    assert self.instance is not None, \
6906
      "Cannot retrieve locked instance %s" % self.op.instance_name
6907

    
6908
  def Exec(self, feedback_fn):
6909
    """Remove the instance.
6910

6911
    """
6912
    instance = self.instance
6913
    logging.info("Shutting down instance %s on node %s",
6914
                 instance.name, instance.primary_node)
6915

    
6916
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6917
                                             self.op.shutdown_timeout)
6918
    msg = result.fail_msg
6919
    if msg:
6920
      if self.op.ignore_failures:
6921
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6922
      else:
6923
        raise errors.OpExecError("Could not shutdown instance %s on"
6924
                                 " node %s: %s" %
6925
                                 (instance.name, instance.primary_node, msg))
6926

    
6927
    assert (self.owned_locks(locking.LEVEL_NODE) ==
6928
            self.owned_locks(locking.LEVEL_NODE_RES))
6929
    assert not (set(instance.all_nodes) -
6930
                self.owned_locks(locking.LEVEL_NODE)), \
6931
      "Not owning correct locks"
6932

    
6933
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6934

    
6935

    
6936
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6937
  """Utility function to remove an instance.
6938

6939
  """
6940
  logging.info("Removing block devices for instance %s", instance.name)
6941

    
6942
  if not _RemoveDisks(lu, instance):
6943
    if not ignore_failures:
6944
      raise errors.OpExecError("Can't remove instance's disks")
6945
    feedback_fn("Warning: can't remove instance's disks")
6946

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

    
6949
  lu.cfg.RemoveInstance(instance.name)
6950

    
6951
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6952
    "Instance lock removal conflict"
6953

    
6954
  # Remove lock for the instance
6955
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6956

    
6957

    
6958
class LUInstanceQuery(NoHooksLU):
6959
  """Logical unit for querying instances.
6960

6961
  """
6962
  # pylint: disable=W0142
6963
  REQ_BGL = False
6964

    
6965
  def CheckArguments(self):
6966
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6967
                             self.op.output_fields, self.op.use_locking)
6968

    
6969
  def ExpandNames(self):
6970
    self.iq.ExpandNames(self)
6971

    
6972
  def DeclareLocks(self, level):
6973
    self.iq.DeclareLocks(self, level)
6974

    
6975
  def Exec(self, feedback_fn):
6976
    return self.iq.OldStyleQuery(self)
6977

    
6978

    
6979
class LUInstanceFailover(LogicalUnit):
6980
  """Failover an instance.
6981

6982
  """
6983
  HPATH = "instance-failover"
6984
  HTYPE = constants.HTYPE_INSTANCE
6985
  REQ_BGL = False
6986

    
6987
  def CheckArguments(self):
6988
    """Check the arguments.
6989

6990
    """
6991
    self.iallocator = getattr(self.op, "iallocator", None)
6992
    self.target_node = getattr(self.op, "target_node", None)
6993

    
6994
  def ExpandNames(self):
6995
    self._ExpandAndLockInstance()
6996

    
6997
    if self.op.target_node is not None:
6998
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6999

    
7000
    self.needed_locks[locking.LEVEL_NODE] = []
7001
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7002

    
7003
    ignore_consistency = self.op.ignore_consistency
7004
    shutdown_timeout = self.op.shutdown_timeout
7005
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
7006
                                       cleanup=False,
7007
                                       failover=True,
7008
                                       ignore_consistency=ignore_consistency,
7009
                                       shutdown_timeout=shutdown_timeout)
7010
    self.tasklets = [self._migrater]
7011

    
7012
  def DeclareLocks(self, level):
7013
    if level == locking.LEVEL_NODE:
7014
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
7015
      if instance.disk_template in constants.DTS_EXT_MIRROR:
7016
        if self.op.target_node is None:
7017
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7018
        else:
7019
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
7020
                                                   self.op.target_node]
7021
        del self.recalculate_locks[locking.LEVEL_NODE]
7022
      else:
7023
        self._LockInstancesNodes()
7024

    
7025
  def BuildHooksEnv(self):
7026
    """Build hooks env.
7027

7028
    This runs on master, primary and secondary nodes of the instance.
7029

7030
    """
7031
    instance = self._migrater.instance
7032
    source_node = instance.primary_node
7033
    target_node = self.op.target_node
7034
    env = {
7035
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
7036
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
7037
      "OLD_PRIMARY": source_node,
7038
      "NEW_PRIMARY": target_node,
7039
      }
7040

    
7041
    if instance.disk_template in constants.DTS_INT_MIRROR:
7042
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
7043
      env["NEW_SECONDARY"] = source_node
7044
    else:
7045
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
7046

    
7047
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7048

    
7049
    return env
7050

    
7051
  def BuildHooksNodes(self):
7052
    """Build hooks nodes.
7053

7054
    """
7055
    instance = self._migrater.instance
7056
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
7057
    return (nl, nl + [instance.primary_node])
7058

    
7059

    
7060
class LUInstanceMigrate(LogicalUnit):
7061
  """Migrate an instance.
7062

7063
  This is migration without shutting down, compared to the failover,
7064
  which is done with shutdown.
7065

7066
  """
7067
  HPATH = "instance-migrate"
7068
  HTYPE = constants.HTYPE_INSTANCE
7069
  REQ_BGL = False
7070

    
7071
  def ExpandNames(self):
7072
    self._ExpandAndLockInstance()
7073

    
7074
    if self.op.target_node is not None:
7075
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
7076

    
7077
    self.needed_locks[locking.LEVEL_NODE] = []
7078
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7079

    
7080
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
7081
                                       cleanup=self.op.cleanup,
7082
                                       failover=False,
7083
                                       fallback=self.op.allow_failover)
7084
    self.tasklets = [self._migrater]
7085

    
7086
  def DeclareLocks(self, level):
7087
    if level == locking.LEVEL_NODE:
7088
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
7089
      if instance.disk_template in constants.DTS_EXT_MIRROR:
7090
        if self.op.target_node is None:
7091
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7092
        else:
7093
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
7094
                                                   self.op.target_node]
7095
        del self.recalculate_locks[locking.LEVEL_NODE]
7096
      else:
7097
        self._LockInstancesNodes()
7098

    
7099
  def BuildHooksEnv(self):
7100
    """Build hooks env.
7101

7102
    This runs on master, primary and secondary nodes of the instance.
7103

7104
    """
7105
    instance = self._migrater.instance
7106
    source_node = instance.primary_node
7107
    target_node = self.op.target_node
7108
    env = _BuildInstanceHookEnvByObject(self, instance)
7109
    env.update({
7110
      "MIGRATE_LIVE": self._migrater.live,
7111
      "MIGRATE_CLEANUP": self.op.cleanup,
7112
      "OLD_PRIMARY": source_node,
7113
      "NEW_PRIMARY": target_node,
7114
      })
7115

    
7116
    if instance.disk_template in constants.DTS_INT_MIRROR:
7117
      env["OLD_SECONDARY"] = target_node
7118
      env["NEW_SECONDARY"] = source_node
7119
    else:
7120
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
7121

    
7122
    return env
7123

    
7124
  def BuildHooksNodes(self):
7125
    """Build hooks nodes.
7126

7127
    """
7128
    instance = self._migrater.instance
7129
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
7130
    return (nl, nl + [instance.primary_node])
7131

    
7132

    
7133
class LUInstanceMove(LogicalUnit):
7134
  """Move an instance by data-copying.
7135

7136
  """
7137
  HPATH = "instance-move"
7138
  HTYPE = constants.HTYPE_INSTANCE
7139
  REQ_BGL = False
7140

    
7141
  def ExpandNames(self):
7142
    self._ExpandAndLockInstance()
7143
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
7144
    self.op.target_node = target_node
7145
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
7146
    self.needed_locks[locking.LEVEL_NODE_RES] = []
7147
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7148

    
7149
  def DeclareLocks(self, level):
7150
    if level == locking.LEVEL_NODE:
7151
      self._LockInstancesNodes(primary_only=True)
7152
    elif level == locking.LEVEL_NODE_RES:
7153
      # Copy node locks
7154
      self.needed_locks[locking.LEVEL_NODE_RES] = \
7155
        self.needed_locks[locking.LEVEL_NODE][:]
7156

    
7157
  def BuildHooksEnv(self):
7158
    """Build hooks env.
7159

7160
    This runs on master, primary and secondary nodes of the instance.
7161

7162
    """
7163
    env = {
7164
      "TARGET_NODE": self.op.target_node,
7165
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
7166
      }
7167
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7168
    return env
7169

    
7170
  def BuildHooksNodes(self):
7171
    """Build hooks nodes.
7172

7173
    """
7174
    nl = [
7175
      self.cfg.GetMasterNode(),
7176
      self.instance.primary_node,
7177
      self.op.target_node,
7178
      ]
7179
    return (nl, nl)
7180

    
7181
  def CheckPrereq(self):
7182
    """Check prerequisites.
7183

7184
    This checks that the instance is in the cluster.
7185

7186
    """
7187
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7188
    assert self.instance is not None, \
7189
      "Cannot retrieve locked instance %s" % self.op.instance_name
7190

    
7191
    node = self.cfg.GetNodeInfo(self.op.target_node)
7192
    assert node is not None, \
7193
      "Cannot retrieve locked node %s" % self.op.target_node
7194

    
7195
    self.target_node = target_node = node.name
7196

    
7197
    if target_node == instance.primary_node:
7198
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
7199
                                 (instance.name, target_node),
7200
                                 errors.ECODE_STATE)
7201

    
7202
    bep = self.cfg.GetClusterInfo().FillBE(instance)
7203

    
7204
    for idx, dsk in enumerate(instance.disks):
7205
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
7206
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
7207
                                   " cannot copy" % idx, errors.ECODE_STATE)
7208

    
7209
    _CheckNodeOnline(self, target_node)
7210
    _CheckNodeNotDrained(self, target_node)
7211
    _CheckNodeVmCapable(self, target_node)
7212

    
7213
    if instance.admin_state == constants.ADMINST_UP:
7214
      # check memory requirements on the secondary node
7215
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
7216
                           instance.name, bep[constants.BE_MAXMEM],
7217
                           instance.hypervisor)
7218
    else:
7219
      self.LogInfo("Not checking memory on the secondary node as"
7220
                   " instance will not be started")
7221

    
7222
    # check bridge existance
7223
    _CheckInstanceBridgesExist(self, instance, node=target_node)
7224

    
7225
  def Exec(self, feedback_fn):
7226
    """Move an instance.
7227

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

7231
    """
7232
    instance = self.instance
7233

    
7234
    source_node = instance.primary_node
7235
    target_node = self.target_node
7236

    
7237
    self.LogInfo("Shutting down instance %s on source node %s",
7238
                 instance.name, source_node)
7239

    
7240
    assert (self.owned_locks(locking.LEVEL_NODE) ==
7241
            self.owned_locks(locking.LEVEL_NODE_RES))
7242

    
7243
    result = self.rpc.call_instance_shutdown(source_node, instance,
7244
                                             self.op.shutdown_timeout)
7245
    msg = result.fail_msg
7246
    if msg:
7247
      if self.op.ignore_consistency:
7248
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
7249
                             " Proceeding anyway. Please make sure node"
7250
                             " %s is down. Error details: %s",
7251
                             instance.name, source_node, source_node, msg)
7252
      else:
7253
        raise errors.OpExecError("Could not shutdown instance %s on"
7254
                                 " node %s: %s" %
7255
                                 (instance.name, source_node, msg))
7256

    
7257
    # create the target disks
7258
    try:
7259
      _CreateDisks(self, instance, target_node=target_node)
7260
    except errors.OpExecError:
7261
      self.LogWarning("Device creation failed, reverting...")
7262
      try:
7263
        _RemoveDisks(self, instance, target_node=target_node)
7264
      finally:
7265
        self.cfg.ReleaseDRBDMinors(instance.name)
7266
        raise
7267

    
7268
    cluster_name = self.cfg.GetClusterInfo().cluster_name
7269

    
7270
    errs = []
7271
    # activate, get path, copy the data over
7272
    for idx, disk in enumerate(instance.disks):
7273
      self.LogInfo("Copying data for disk %d", idx)
7274
      result = self.rpc.call_blockdev_assemble(target_node, disk,
7275
                                               instance.name, True, idx)
7276
      if result.fail_msg:
7277
        self.LogWarning("Can't assemble newly created disk %d: %s",
7278
                        idx, result.fail_msg)
7279
        errs.append(result.fail_msg)
7280
        break
7281
      dev_path = result.payload
7282
      result = self.rpc.call_blockdev_export(source_node, disk,
7283
                                             target_node, dev_path,
7284
                                             cluster_name)
7285
      if result.fail_msg:
7286
        self.LogWarning("Can't copy data over for disk %d: %s",
7287
                        idx, result.fail_msg)
7288
        errs.append(result.fail_msg)
7289
        break
7290

    
7291
    if errs:
7292
      self.LogWarning("Some disks failed to copy, aborting")
7293
      try:
7294
        _RemoveDisks(self, instance, target_node=target_node)
7295
      finally:
7296
        self.cfg.ReleaseDRBDMinors(instance.name)
7297
        raise errors.OpExecError("Errors during disk copy: %s" %
7298
                                 (",".join(errs),))
7299

    
7300
    instance.primary_node = target_node
7301
    self.cfg.Update(instance, feedback_fn)
7302

    
7303
    self.LogInfo("Removing the disks on the original node")
7304
    _RemoveDisks(self, instance, target_node=source_node)
7305

    
7306
    # Only start the instance if it's marked as up
7307
    if instance.admin_state == constants.ADMINST_UP:
7308
      self.LogInfo("Starting instance %s on node %s",
7309
                   instance.name, target_node)
7310

    
7311
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7312
                                           ignore_secondaries=True)
7313
      if not disks_ok:
7314
        _ShutdownInstanceDisks(self, instance)
7315
        raise errors.OpExecError("Can't activate the instance's disks")
7316

    
7317
      result = self.rpc.call_instance_start(target_node,
7318
                                            (instance, None, None), False)
7319
      msg = result.fail_msg
7320
      if msg:
7321
        _ShutdownInstanceDisks(self, instance)
7322
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7323
                                 (instance.name, target_node, msg))
7324

    
7325

    
7326
class LUNodeMigrate(LogicalUnit):
7327
  """Migrate all instances from a node.
7328

7329
  """
7330
  HPATH = "node-migrate"
7331
  HTYPE = constants.HTYPE_NODE
7332
  REQ_BGL = False
7333

    
7334
  def CheckArguments(self):
7335
    pass
7336

    
7337
  def ExpandNames(self):
7338
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7339

    
7340
    self.share_locks = _ShareAll()
7341
    self.needed_locks = {
7342
      locking.LEVEL_NODE: [self.op.node_name],
7343
      }
7344

    
7345
  def BuildHooksEnv(self):
7346
    """Build hooks env.
7347

7348
    This runs on the master, the primary and all the secondaries.
7349

7350
    """
7351
    return {
7352
      "NODE_NAME": self.op.node_name,
7353
      }
7354

    
7355
  def BuildHooksNodes(self):
7356
    """Build hooks nodes.
7357

7358
    """
7359
    nl = [self.cfg.GetMasterNode()]
7360
    return (nl, nl)
7361

    
7362
  def CheckPrereq(self):
7363
    pass
7364

    
7365
  def Exec(self, feedback_fn):
7366
    # Prepare jobs for migration instances
7367
    jobs = [
7368
      [opcodes.OpInstanceMigrate(instance_name=inst.name,
7369
                                 mode=self.op.mode,
7370
                                 live=self.op.live,
7371
                                 iallocator=self.op.iallocator,
7372
                                 target_node=self.op.target_node)]
7373
      for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name)
7374
      ]
7375

    
7376
    # TODO: Run iallocator in this opcode and pass correct placement options to
7377
    # OpInstanceMigrate. Since other jobs can modify the cluster between
7378
    # running the iallocator and the actual migration, a good consistency model
7379
    # will have to be found.
7380

    
7381
    assert (frozenset(self.owned_locks(locking.LEVEL_NODE)) ==
7382
            frozenset([self.op.node_name]))
7383

    
7384
    return ResultWithJobs(jobs)
7385

    
7386

    
7387
class TLMigrateInstance(Tasklet):
7388
  """Tasklet class for instance migration.
7389

7390
  @type live: boolean
7391
  @ivar live: whether the migration will be done live or non-live;
7392
      this variable is initalized only after CheckPrereq has run
7393
  @type cleanup: boolean
7394
  @ivar cleanup: Wheater we cleanup from a failed migration
7395
  @type iallocator: string
7396
  @ivar iallocator: The iallocator used to determine target_node
7397
  @type target_node: string
7398
  @ivar target_node: If given, the target_node to reallocate the instance to
7399
  @type failover: boolean
7400
  @ivar failover: Whether operation results in failover or migration
7401
  @type fallback: boolean
7402
  @ivar fallback: Whether fallback to failover is allowed if migration not
7403
                  possible
7404
  @type ignore_consistency: boolean
7405
  @ivar ignore_consistency: Wheter we should ignore consistency between source
7406
                            and target node
7407
  @type shutdown_timeout: int
7408
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
7409

7410
  """
7411

    
7412
  # Constants
7413
  _MIGRATION_POLL_INTERVAL = 1      # seconds
7414
  _MIGRATION_FEEDBACK_INTERVAL = 10 # seconds
7415

    
7416
  def __init__(self, lu, instance_name, cleanup=False,
7417
               failover=False, fallback=False,
7418
               ignore_consistency=False,
7419
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
7420
    """Initializes this class.
7421

7422
    """
7423
    Tasklet.__init__(self, lu)
7424

    
7425
    # Parameters
7426
    self.instance_name = instance_name
7427
    self.cleanup = cleanup
7428
    self.live = False # will be overridden later
7429
    self.failover = failover
7430
    self.fallback = fallback
7431
    self.ignore_consistency = ignore_consistency
7432
    self.shutdown_timeout = shutdown_timeout
7433

    
7434
  def CheckPrereq(self):
7435
    """Check prerequisites.
7436

7437
    This checks that the instance is in the cluster.
7438

7439
    """
7440
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
7441
    instance = self.cfg.GetInstanceInfo(instance_name)
7442
    assert instance is not None
7443
    self.instance = instance
7444

    
7445
    if (not self.cleanup and
7446
        not instance.admin_state == constants.ADMINST_UP and
7447
        not self.failover and self.fallback):
7448
      self.lu.LogInfo("Instance is marked down or offline, fallback allowed,"
7449
                      " switching to failover")
7450
      self.failover = True
7451

    
7452
    if instance.disk_template not in constants.DTS_MIRRORED:
7453
      if self.failover:
7454
        text = "failovers"
7455
      else:
7456
        text = "migrations"
7457
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
7458
                                 " %s" % (instance.disk_template, text),
7459
                                 errors.ECODE_STATE)
7460

    
7461
    if instance.disk_template in constants.DTS_EXT_MIRROR:
7462
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
7463

    
7464
      if self.lu.op.iallocator:
7465
        self._RunAllocator()
7466
      else:
7467
        # We set set self.target_node as it is required by
7468
        # BuildHooksEnv
7469
        self.target_node = self.lu.op.target_node
7470

    
7471
      # self.target_node is already populated, either directly or by the
7472
      # iallocator run
7473
      target_node = self.target_node
7474
      if self.target_node == instance.primary_node:
7475
        raise errors.OpPrereqError("Cannot migrate instance %s"
7476
                                   " to its primary (%s)" %
7477
                                   (instance.name, instance.primary_node))
7478

    
7479
      if len(self.lu.tasklets) == 1:
7480
        # It is safe to release locks only when we're the only tasklet
7481
        # in the LU
7482
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
7483
                      keep=[instance.primary_node, self.target_node])
7484

    
7485
    else:
7486
      secondary_nodes = instance.secondary_nodes
7487
      if not secondary_nodes:
7488
        raise errors.ConfigurationError("No secondary node but using"
7489
                                        " %s disk template" %
7490
                                        instance.disk_template)
7491
      target_node = secondary_nodes[0]
7492
      if self.lu.op.iallocator or (self.lu.op.target_node and
7493
                                   self.lu.op.target_node != target_node):
7494
        if self.failover:
7495
          text = "failed over"
7496
        else:
7497
          text = "migrated"
7498
        raise errors.OpPrereqError("Instances with disk template %s cannot"
7499
                                   " be %s to arbitrary nodes"
7500
                                   " (neither an iallocator nor a target"
7501
                                   " node can be passed)" %
7502
                                   (instance.disk_template, text),
7503
                                   errors.ECODE_INVAL)
7504

    
7505
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
7506

    
7507
    # check memory requirements on the secondary node
7508
    if not self.failover or instance.admin_state == constants.ADMINST_UP:
7509
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
7510
                           instance.name, i_be[constants.BE_MAXMEM],
7511
                           instance.hypervisor)
7512
    else:
7513
      self.lu.LogInfo("Not checking memory on the secondary node as"
7514
                      " instance will not be started")
7515

    
7516
    # check bridge existance
7517
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
7518

    
7519
    if not self.cleanup:
7520
      _CheckNodeNotDrained(self.lu, target_node)
7521
      if not self.failover:
7522
        result = self.rpc.call_instance_migratable(instance.primary_node,
7523
                                                   instance)
7524
        if result.fail_msg and self.fallback:
7525
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
7526
                          " failover")
7527
          self.failover = True
7528
        else:
7529
          result.Raise("Can't migrate, please use failover",
7530
                       prereq=True, ecode=errors.ECODE_STATE)
7531

    
7532
    assert not (self.failover and self.cleanup)
7533

    
7534
    if not self.failover:
7535
      if self.lu.op.live is not None and self.lu.op.mode is not None:
7536
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
7537
                                   " parameters are accepted",
7538
                                   errors.ECODE_INVAL)
7539
      if self.lu.op.live is not None:
7540
        if self.lu.op.live:
7541
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
7542
        else:
7543
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
7544
        # reset the 'live' parameter to None so that repeated
7545
        # invocations of CheckPrereq do not raise an exception
7546
        self.lu.op.live = None
7547
      elif self.lu.op.mode is None:
7548
        # read the default value from the hypervisor
7549
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
7550
                                                skip_globals=False)
7551
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
7552

    
7553
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
7554
    else:
7555
      # Failover is never live
7556
      self.live = False
7557

    
7558
  def _RunAllocator(self):
7559
    """Run the allocator based on input opcode.
7560

7561
    """
7562
    ial = IAllocator(self.cfg, self.rpc,
7563
                     mode=constants.IALLOCATOR_MODE_RELOC,
7564
                     name=self.instance_name,
7565
                     # TODO See why hail breaks with a single node below
7566
                     relocate_from=[self.instance.primary_node,
7567
                                    self.instance.primary_node],
7568
                     )
7569

    
7570
    ial.Run(self.lu.op.iallocator)
7571

    
7572
    if not ial.success:
7573
      raise errors.OpPrereqError("Can't compute nodes using"
7574
                                 " iallocator '%s': %s" %
7575
                                 (self.lu.op.iallocator, ial.info),
7576
                                 errors.ECODE_NORES)
7577
    if len(ial.result) != ial.required_nodes:
7578
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7579
                                 " of nodes (%s), required %s" %
7580
                                 (self.lu.op.iallocator, len(ial.result),
7581
                                  ial.required_nodes), errors.ECODE_FAULT)
7582
    self.target_node = ial.result[0]
7583
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7584
                 self.instance_name, self.lu.op.iallocator,
7585
                 utils.CommaJoin(ial.result))
7586

    
7587
  def _WaitUntilSync(self):
7588
    """Poll with custom rpc for disk sync.
7589

7590
    This uses our own step-based rpc call.
7591

7592
    """
7593
    self.feedback_fn("* wait until resync is done")
7594
    all_done = False
7595
    while not all_done:
7596
      all_done = True
7597
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
7598
                                            self.nodes_ip,
7599
                                            self.instance.disks)
7600
      min_percent = 100
7601
      for node, nres in result.items():
7602
        nres.Raise("Cannot resync disks on node %s" % node)
7603
        node_done, node_percent = nres.payload
7604
        all_done = all_done and node_done
7605
        if node_percent is not None:
7606
          min_percent = min(min_percent, node_percent)
7607
      if not all_done:
7608
        if min_percent < 100:
7609
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
7610
        time.sleep(2)
7611

    
7612
  def _EnsureSecondary(self, node):
7613
    """Demote a node to secondary.
7614

7615
    """
7616
    self.feedback_fn("* switching node %s to secondary mode" % node)
7617

    
7618
    for dev in self.instance.disks:
7619
      self.cfg.SetDiskID(dev, node)
7620

    
7621
    result = self.rpc.call_blockdev_close(node, self.instance.name,
7622
                                          self.instance.disks)
7623
    result.Raise("Cannot change disk to secondary on node %s" % node)
7624

    
7625
  def _GoStandalone(self):
7626
    """Disconnect from the network.
7627

7628
    """
7629
    self.feedback_fn("* changing into standalone mode")
7630
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
7631
                                               self.instance.disks)
7632
    for node, nres in result.items():
7633
      nres.Raise("Cannot disconnect disks node %s" % node)
7634

    
7635
  def _GoReconnect(self, multimaster):
7636
    """Reconnect to the network.
7637

7638
    """
7639
    if multimaster:
7640
      msg = "dual-master"
7641
    else:
7642
      msg = "single-master"
7643
    self.feedback_fn("* changing disks into %s mode" % msg)
7644
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
7645
                                           self.instance.disks,
7646
                                           self.instance.name, multimaster)
7647
    for node, nres in result.items():
7648
      nres.Raise("Cannot change disks config on node %s" % node)
7649

    
7650
  def _ExecCleanup(self):
7651
    """Try to cleanup after a failed migration.
7652

7653
    The cleanup is done by:
7654
      - check that the instance is running only on one node
7655
        (and update the config if needed)
7656
      - change disks on its secondary node to secondary
7657
      - wait until disks are fully synchronized
7658
      - disconnect from the network
7659
      - change disks into single-master mode
7660
      - wait again until disks are fully synchronized
7661

7662
    """
7663
    instance = self.instance
7664
    target_node = self.target_node
7665
    source_node = self.source_node
7666

    
7667
    # check running on only one node
7668
    self.feedback_fn("* checking where the instance actually runs"
7669
                     " (if this hangs, the hypervisor might be in"
7670
                     " a bad state)")
7671
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
7672
    for node, result in ins_l.items():
7673
      result.Raise("Can't contact node %s" % node)
7674

    
7675
    runningon_source = instance.name in ins_l[source_node].payload
7676
    runningon_target = instance.name in ins_l[target_node].payload
7677

    
7678
    if runningon_source and runningon_target:
7679
      raise errors.OpExecError("Instance seems to be running on two nodes,"
7680
                               " or the hypervisor is confused; you will have"
7681
                               " to ensure manually that it runs only on one"
7682
                               " and restart this operation")
7683

    
7684
    if not (runningon_source or runningon_target):
7685
      raise errors.OpExecError("Instance does not seem to be running at all;"
7686
                               " in this case it's safer to repair by"
7687
                               " running 'gnt-instance stop' to ensure disk"
7688
                               " shutdown, and then restarting it")
7689

    
7690
    if runningon_target:
7691
      # the migration has actually succeeded, we need to update the config
7692
      self.feedback_fn("* instance running on secondary node (%s),"
7693
                       " updating config" % target_node)
7694
      instance.primary_node = target_node
7695
      self.cfg.Update(instance, self.feedback_fn)
7696
      demoted_node = source_node
7697
    else:
7698
      self.feedback_fn("* instance confirmed to be running on its"
7699
                       " primary node (%s)" % source_node)
7700
      demoted_node = target_node
7701

    
7702
    if instance.disk_template in constants.DTS_INT_MIRROR:
7703
      self._EnsureSecondary(demoted_node)
7704
      try:
7705
        self._WaitUntilSync()
7706
      except errors.OpExecError:
7707
        # we ignore here errors, since if the device is standalone, it
7708
        # won't be able to sync
7709
        pass
7710
      self._GoStandalone()
7711
      self._GoReconnect(False)
7712
      self._WaitUntilSync()
7713

    
7714
    self.feedback_fn("* done")
7715

    
7716
  def _RevertDiskStatus(self):
7717
    """Try to revert the disk status after a failed migration.
7718

7719
    """
7720
    target_node = self.target_node
7721
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7722
      return
7723

    
7724
    try:
7725
      self._EnsureSecondary(target_node)
7726
      self._GoStandalone()
7727
      self._GoReconnect(False)
7728
      self._WaitUntilSync()
7729
    except errors.OpExecError, err:
7730
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7731
                         " please try to recover the instance manually;"
7732
                         " error '%s'" % str(err))
7733

    
7734
  def _AbortMigration(self):
7735
    """Call the hypervisor code to abort a started migration.
7736

7737
    """
7738
    instance = self.instance
7739
    target_node = self.target_node
7740
    source_node = self.source_node
7741
    migration_info = self.migration_info
7742

    
7743
    abort_result = self.rpc.call_instance_finalize_migration_dst(target_node,
7744
                                                                 instance,
7745
                                                                 migration_info,
7746
                                                                 False)
7747
    abort_msg = abort_result.fail_msg
7748
    if abort_msg:
7749
      logging.error("Aborting migration failed on target node %s: %s",
7750
                    target_node, abort_msg)
7751
      # Don't raise an exception here, as we stil have to try to revert the
7752
      # disk status, even if this step failed.
7753

    
7754
    abort_result = self.rpc.call_instance_finalize_migration_src(source_node,
7755
        instance, False, self.live)
7756
    abort_msg = abort_result.fail_msg
7757
    if abort_msg:
7758
      logging.error("Aborting migration failed on source node %s: %s",
7759
                    source_node, abort_msg)
7760

    
7761
  def _ExecMigration(self):
7762
    """Migrate an instance.
7763

7764
    The migrate is done by:
7765
      - change the disks into dual-master mode
7766
      - wait until disks are fully synchronized again
7767
      - migrate the instance
7768
      - change disks on the new secondary node (the old primary) to secondary
7769
      - wait until disks are fully synchronized
7770
      - change disks into single-master mode
7771

7772
    """
7773
    instance = self.instance
7774
    target_node = self.target_node
7775
    source_node = self.source_node
7776

    
7777
    # Check for hypervisor version mismatch and warn the user.
7778
    nodeinfo = self.rpc.call_node_info([source_node, target_node],
7779
                                       None, [self.instance.hypervisor])
7780
    for ninfo in nodeinfo.values():
7781
      ninfo.Raise("Unable to retrieve node information from node '%s'" %
7782
                  ninfo.node)
7783
    (_, _, (src_info, )) = nodeinfo[source_node].payload
7784
    (_, _, (dst_info, )) = nodeinfo[target_node].payload
7785

    
7786
    if ((constants.HV_NODEINFO_KEY_VERSION in src_info) and
7787
        (constants.HV_NODEINFO_KEY_VERSION in dst_info)):
7788
      src_version = src_info[constants.HV_NODEINFO_KEY_VERSION]
7789
      dst_version = dst_info[constants.HV_NODEINFO_KEY_VERSION]
7790
      if src_version != dst_version:
7791
        self.feedback_fn("* warning: hypervisor version mismatch between"
7792
                         " source (%s) and target (%s) node" %
7793
                         (src_version, dst_version))
7794

    
7795
    self.feedback_fn("* checking disk consistency between source and target")
7796
    for dev in instance.disks:
7797
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7798
        raise errors.OpExecError("Disk %s is degraded or not fully"
7799
                                 " synchronized on target node,"
7800
                                 " aborting migration" % dev.iv_name)
7801

    
7802
    # First get the migration information from the remote node
7803
    result = self.rpc.call_migration_info(source_node, instance)
7804
    msg = result.fail_msg
7805
    if msg:
7806
      log_err = ("Failed fetching source migration information from %s: %s" %
7807
                 (source_node, msg))
7808
      logging.error(log_err)
7809
      raise errors.OpExecError(log_err)
7810

    
7811
    self.migration_info = migration_info = result.payload
7812

    
7813
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7814
      # Then switch the disks to master/master mode
7815
      self._EnsureSecondary(target_node)
7816
      self._GoStandalone()
7817
      self._GoReconnect(True)
7818
      self._WaitUntilSync()
7819

    
7820
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7821
    result = self.rpc.call_accept_instance(target_node,
7822
                                           instance,
7823
                                           migration_info,
7824
                                           self.nodes_ip[target_node])
7825

    
7826
    msg = result.fail_msg
7827
    if msg:
7828
      logging.error("Instance pre-migration failed, trying to revert"
7829
                    " disk status: %s", msg)
7830
      self.feedback_fn("Pre-migration failed, aborting")
7831
      self._AbortMigration()
7832
      self._RevertDiskStatus()
7833
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7834
                               (instance.name, msg))
7835

    
7836
    self.feedback_fn("* migrating instance to %s" % target_node)
7837
    result = self.rpc.call_instance_migrate(source_node, instance,
7838
                                            self.nodes_ip[target_node],
7839
                                            self.live)
7840
    msg = result.fail_msg
7841
    if msg:
7842
      logging.error("Instance migration failed, trying to revert"
7843
                    " disk status: %s", msg)
7844
      self.feedback_fn("Migration failed, aborting")
7845
      self._AbortMigration()
7846
      self._RevertDiskStatus()
7847
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7848
                               (instance.name, msg))
7849

    
7850
    self.feedback_fn("* starting memory transfer")
7851
    last_feedback = time.time()
7852
    while True:
7853
      result = self.rpc.call_instance_get_migration_status(source_node,
7854
                                                           instance)
7855
      msg = result.fail_msg
7856
      ms = result.payload   # MigrationStatus instance
7857
      if msg or (ms.status in constants.HV_MIGRATION_FAILED_STATUSES):
7858
        logging.error("Instance migration failed, trying to revert"
7859
                      " disk status: %s", msg)
7860
        self.feedback_fn("Migration failed, aborting")
7861
        self._AbortMigration()
7862
        self._RevertDiskStatus()
7863
        raise errors.OpExecError("Could not migrate instance %s: %s" %
7864
                                 (instance.name, msg))
7865

    
7866
      if result.payload.status != constants.HV_MIGRATION_ACTIVE:
7867
        self.feedback_fn("* memory transfer complete")
7868
        break
7869

    
7870
      if (utils.TimeoutExpired(last_feedback,
7871
                               self._MIGRATION_FEEDBACK_INTERVAL) and
7872
          ms.transferred_ram is not None):
7873
        mem_progress = 100 * float(ms.transferred_ram) / float(ms.total_ram)
7874
        self.feedback_fn("* memory transfer progress: %.2f %%" % mem_progress)
7875
        last_feedback = time.time()
7876

    
7877
      time.sleep(self._MIGRATION_POLL_INTERVAL)
7878

    
7879
    result = self.rpc.call_instance_finalize_migration_src(source_node,
7880
                                                           instance,
7881
                                                           True,
7882
                                                           self.live)
7883
    msg = result.fail_msg
7884
    if msg:
7885
      logging.error("Instance migration succeeded, but finalization failed"
7886
                    " on the source node: %s", msg)
7887
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7888
                               msg)
7889

    
7890
    instance.primary_node = target_node
7891

    
7892
    # distribute new instance config to the other nodes
7893
    self.cfg.Update(instance, self.feedback_fn)
7894

    
7895
    result = self.rpc.call_instance_finalize_migration_dst(target_node,
7896
                                                           instance,
7897
                                                           migration_info,
7898
                                                           True)
7899
    msg = result.fail_msg
7900
    if msg:
7901
      logging.error("Instance migration succeeded, but finalization failed"
7902
                    " on the target node: %s", msg)
7903
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7904
                               msg)
7905

    
7906
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7907
      self._EnsureSecondary(source_node)
7908
      self._WaitUntilSync()
7909
      self._GoStandalone()
7910
      self._GoReconnect(False)
7911
      self._WaitUntilSync()
7912

    
7913
    self.feedback_fn("* done")
7914

    
7915
  def _ExecFailover(self):
7916
    """Failover an instance.
7917

7918
    The failover is done by shutting it down on its present node and
7919
    starting it on the secondary.
7920

7921
    """
7922
    instance = self.instance
7923
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7924

    
7925
    source_node = instance.primary_node
7926
    target_node = self.target_node
7927

    
7928
    if instance.admin_state == constants.ADMINST_UP:
7929
      self.feedback_fn("* checking disk consistency between source and target")
7930
      for dev in instance.disks:
7931
        # for drbd, these are drbd over lvm
7932
        if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7933
          if primary_node.offline:
7934
            self.feedback_fn("Node %s is offline, ignoring degraded disk %s on"
7935
                             " target node %s" %
7936
                             (primary_node.name, dev.iv_name, target_node))
7937
          elif not self.ignore_consistency:
7938
            raise errors.OpExecError("Disk %s is degraded on target node,"
7939
                                     " aborting failover" % dev.iv_name)
7940
    else:
7941
      self.feedback_fn("* not checking disk consistency as instance is not"
7942
                       " running")
7943

    
7944
    self.feedback_fn("* shutting down instance on source node")
7945
    logging.info("Shutting down instance %s on node %s",
7946
                 instance.name, source_node)
7947

    
7948
    result = self.rpc.call_instance_shutdown(source_node, instance,
7949
                                             self.shutdown_timeout)
7950
    msg = result.fail_msg
7951
    if msg:
7952
      if self.ignore_consistency or primary_node.offline:
7953
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7954
                           " proceeding anyway; please make sure node"
7955
                           " %s is down; error details: %s",
7956
                           instance.name, source_node, source_node, msg)
7957
      else:
7958
        raise errors.OpExecError("Could not shutdown instance %s on"
7959
                                 " node %s: %s" %
7960
                                 (instance.name, source_node, msg))
7961

    
7962
    self.feedback_fn("* deactivating the instance's disks on source node")
7963
    if not _ShutdownInstanceDisks(self.lu, instance, ignore_primary=True):
7964
      raise errors.OpExecError("Can't shut down the instance's disks")
7965

    
7966
    instance.primary_node = target_node
7967
    # distribute new instance config to the other nodes
7968
    self.cfg.Update(instance, self.feedback_fn)
7969

    
7970
    # Only start the instance if it's marked as up
7971
    if instance.admin_state == constants.ADMINST_UP:
7972
      self.feedback_fn("* activating the instance's disks on target node %s" %
7973
                       target_node)
7974
      logging.info("Starting instance %s on node %s",
7975
                   instance.name, target_node)
7976

    
7977
      disks_ok, _ = _AssembleInstanceDisks(self.lu, instance,
7978
                                           ignore_secondaries=True)
7979
      if not disks_ok:
7980
        _ShutdownInstanceDisks(self.lu, instance)
7981
        raise errors.OpExecError("Can't activate the instance's disks")
7982

    
7983
      self.feedback_fn("* starting the instance on the target node %s" %
7984
                       target_node)
7985
      result = self.rpc.call_instance_start(target_node, (instance, None, None),
7986
                                            False)
7987
      msg = result.fail_msg
7988
      if msg:
7989
        _ShutdownInstanceDisks(self.lu, instance)
7990
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7991
                                 (instance.name, target_node, msg))
7992

    
7993
  def Exec(self, feedback_fn):
7994
    """Perform the migration.
7995

7996
    """
7997
    self.feedback_fn = feedback_fn
7998
    self.source_node = self.instance.primary_node
7999

    
8000
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
8001
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
8002
      self.target_node = self.instance.secondary_nodes[0]
8003
      # Otherwise self.target_node has been populated either
8004
      # directly, or through an iallocator.
8005

    
8006
    self.all_nodes = [self.source_node, self.target_node]
8007
    self.nodes_ip = dict((name, node.secondary_ip) for (name, node)
8008
                         in self.cfg.GetMultiNodeInfo(self.all_nodes))
8009

    
8010
    if self.failover:
8011
      feedback_fn("Failover instance %s" % self.instance.name)
8012
      self._ExecFailover()
8013
    else:
8014
      feedback_fn("Migrating instance %s" % self.instance.name)
8015

    
8016
      if self.cleanup:
8017
        return self._ExecCleanup()
8018
      else:
8019
        return self._ExecMigration()
8020

    
8021

    
8022
def _CreateBlockDev(lu, node, instance, device, force_create,
8023
                    info, force_open):
8024
  """Create a tree of block devices on a given node.
8025

8026
  If this device type has to be created on secondaries, create it and
8027
  all its children.
8028

8029
  If not, just recurse to children keeping the same 'force' value.
8030

8031
  @param lu: the lu on whose behalf we execute
8032
  @param node: the node on which to create the device
8033
  @type instance: L{objects.Instance}
8034
  @param instance: the instance which owns the device
8035
  @type device: L{objects.Disk}
8036
  @param device: the device to create
8037
  @type force_create: boolean
8038
  @param force_create: whether to force creation of this device; this
8039
      will be change to True whenever we find a device which has
8040
      CreateOnSecondary() attribute
8041
  @param info: the extra 'metadata' we should attach to the device
8042
      (this will be represented as a LVM tag)
8043
  @type force_open: boolean
8044
  @param force_open: this parameter will be passes to the
8045
      L{backend.BlockdevCreate} function where it specifies
8046
      whether we run on primary or not, and it affects both
8047
      the child assembly and the device own Open() execution
8048

8049
  """
8050
  if device.CreateOnSecondary():
8051
    force_create = True
8052

    
8053
  if device.children:
8054
    for child in device.children:
8055
      _CreateBlockDev(lu, node, instance, child, force_create,
8056
                      info, force_open)
8057

    
8058
  if not force_create:
8059
    return
8060

    
8061
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
8062

    
8063

    
8064
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
8065
  """Create a single block device on a given node.
8066

8067
  This will not recurse over children of the device, so they must be
8068
  created in advance.
8069

8070
  @param lu: the lu on whose behalf we execute
8071
  @param node: the node on which to create the device
8072
  @type instance: L{objects.Instance}
8073
  @param instance: the instance which owns the device
8074
  @type device: L{objects.Disk}
8075
  @param device: the device to create
8076
  @param info: the extra 'metadata' we should attach to the device
8077
      (this will be represented as a LVM tag)
8078
  @type force_open: boolean
8079
  @param force_open: this parameter will be passes to the
8080
      L{backend.BlockdevCreate} function where it specifies
8081
      whether we run on primary or not, and it affects both
8082
      the child assembly and the device own Open() execution
8083

8084
  """
8085
  lu.cfg.SetDiskID(device, node)
8086
  result = lu.rpc.call_blockdev_create(node, device, device.size,
8087
                                       instance.name, force_open, info)
8088
  result.Raise("Can't create block device %s on"
8089
               " node %s for instance %s" % (device, node, instance.name))
8090
  if device.physical_id is None:
8091
    device.physical_id = result.payload
8092

    
8093

    
8094
def _GenerateUniqueNames(lu, exts):
8095
  """Generate a suitable LV name.
8096

8097
  This will generate a logical volume name for the given instance.
8098

8099
  """
8100
  results = []
8101
  for val in exts:
8102
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
8103
    results.append("%s%s" % (new_id, val))
8104
  return results
8105

    
8106

    
8107
def _ComputeLDParams(disk_template, disk_params):
8108
  """Computes Logical Disk parameters from Disk Template parameters.
8109

8110
  @type disk_template: string
8111
  @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
8112
  @type disk_params: dict
8113
  @param disk_params: disk template parameters; dict(template_name -> parameters
8114
  @rtype: list(dict)
8115
  @return: a list of dicts, one for each node of the disk hierarchy. Each dict
8116
    contains the LD parameters of the node. The tree is flattened in-order.
8117

8118
  """
8119
  if disk_template not in constants.DISK_TEMPLATES:
8120
    raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
8121

    
8122
  result = list()
8123
  dt_params = disk_params[disk_template]
8124
  if disk_template == constants.DT_DRBD8:
8125
    drbd_params = {
8126
      constants.RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
8127
      constants.BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
8128
      constants.NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
8129
      }
8130

    
8131
    drbd_params = \
8132
      objects.FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8],
8133
                       drbd_params)
8134

    
8135
    result.append(drbd_params)
8136

    
8137
    # data LV
8138
    data_params = {
8139
      constants.STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
8140
      }
8141
    data_params = \
8142
      objects.FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
8143
                       data_params)
8144
    result.append(data_params)
8145

    
8146
    # metadata LV
8147
    meta_params = {
8148
      constants.STRIPES: dt_params[constants.DRBD_META_STRIPES],
8149
      }
8150
    meta_params = \
8151
      objects.FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
8152
                       meta_params)
8153
    result.append(meta_params)
8154

    
8155
  elif (disk_template == constants.DT_FILE or
8156
        disk_template == constants.DT_SHARED_FILE):
8157
    result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
8158

    
8159
  elif disk_template == constants.DT_PLAIN:
8160
    params = {
8161
      constants.STRIPES: dt_params[constants.LV_STRIPES],
8162
      }
8163
    params = \
8164
      objects.FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
8165
                       params)
8166
    result.append(params)
8167

    
8168
  elif disk_template == constants.DT_BLOCK:
8169
    result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
8170

    
8171
  return result
8172

    
8173

    
8174
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
8175
                         iv_name, p_minor, s_minor, drbd_params, data_params,
8176
                         meta_params):
8177
  """Generate a drbd8 device complete with its children.
8178

8179
  """
8180
  assert len(vgnames) == len(names) == 2
8181
  port = lu.cfg.AllocatePort()
8182
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
8183

    
8184
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
8185
                          logical_id=(vgnames[0], names[0]),
8186
                          params=data_params)
8187
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=DRBD_META_SIZE,
8188
                          logical_id=(vgnames[1], names[1]),
8189
                          params=meta_params)
8190
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
8191
                          logical_id=(primary, secondary, port,
8192
                                      p_minor, s_minor,
8193
                                      shared_secret),
8194
                          children=[dev_data, dev_meta],
8195
                          iv_name=iv_name, params=drbd_params)
8196
  return drbd_dev
8197

    
8198

    
8199
def _GenerateDiskTemplate(lu, template_name,
8200
                          instance_name, primary_node,
8201
                          secondary_nodes, disk_info,
8202
                          file_storage_dir, file_driver,
8203
                          base_index, feedback_fn, disk_params):
8204
  """Generate the entire disk layout for a given template type.
8205

8206
  """
8207
  #TODO: compute space requirements
8208

    
8209
  vgname = lu.cfg.GetVGName()
8210
  disk_count = len(disk_info)
8211
  disks = []
8212
  ld_params = _ComputeLDParams(template_name, disk_params)
8213
  if template_name == constants.DT_DISKLESS:
8214
    pass
8215
  elif template_name == constants.DT_PLAIN:
8216
    if len(secondary_nodes) != 0:
8217
      raise errors.ProgrammerError("Wrong template configuration")
8218

    
8219
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
8220
                                      for i in range(disk_count)])
8221
    for idx, disk in enumerate(disk_info):
8222
      disk_index = idx + base_index
8223
      vg = disk.get(constants.IDISK_VG, vgname)
8224
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
8225
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
8226
                              size=disk[constants.IDISK_SIZE],
8227
                              logical_id=(vg, names[idx]),
8228
                              iv_name="disk/%d" % disk_index,
8229
                              mode=disk[constants.IDISK_MODE],
8230
                              params=ld_params[0])
8231
      disks.append(disk_dev)
8232
  elif template_name == constants.DT_DRBD8:
8233
    drbd_params, data_params, meta_params = ld_params
8234
    if len(secondary_nodes) != 1:
8235
      raise errors.ProgrammerError("Wrong template configuration")
8236
    remote_node = secondary_nodes[0]
8237
    minors = lu.cfg.AllocateDRBDMinor(
8238
      [primary_node, remote_node] * len(disk_info), instance_name)
8239

    
8240
    names = []
8241
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
8242
                                               for i in range(disk_count)]):
8243
      names.append(lv_prefix + "_data")
8244
      names.append(lv_prefix + "_meta")
8245
    for idx, disk in enumerate(disk_info):
8246
      disk_index = idx + base_index
8247
      data_vg = disk.get(constants.IDISK_VG, vgname)
8248
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
8249
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
8250
                                      disk[constants.IDISK_SIZE],
8251
                                      [data_vg, meta_vg],
8252
                                      names[idx * 2:idx * 2 + 2],
8253
                                      "disk/%d" % disk_index,
8254
                                      minors[idx * 2], minors[idx * 2 + 1],
8255
                                      drbd_params, data_params, meta_params)
8256
      disk_dev.mode = disk[constants.IDISK_MODE]
8257
      disks.append(disk_dev)
8258
  elif template_name == constants.DT_FILE:
8259
    if len(secondary_nodes) != 0:
8260
      raise errors.ProgrammerError("Wrong template configuration")
8261

    
8262
    opcodes.RequireFileStorage()
8263

    
8264
    for idx, disk in enumerate(disk_info):
8265
      disk_index = idx + base_index
8266
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
8267
                              size=disk[constants.IDISK_SIZE],
8268
                              iv_name="disk/%d" % disk_index,
8269
                              logical_id=(file_driver,
8270
                                          "%s/disk%d" % (file_storage_dir,
8271
                                                         disk_index)),
8272
                              mode=disk[constants.IDISK_MODE],
8273
                              params=ld_params[0])
8274
      disks.append(disk_dev)
8275
  elif template_name == constants.DT_SHARED_FILE:
8276
    if len(secondary_nodes) != 0:
8277
      raise errors.ProgrammerError("Wrong template configuration")
8278

    
8279
    opcodes.RequireSharedFileStorage()
8280

    
8281
    for idx, disk in enumerate(disk_info):
8282
      disk_index = idx + base_index
8283
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
8284
                              size=disk[constants.IDISK_SIZE],
8285
                              iv_name="disk/%d" % disk_index,
8286
                              logical_id=(file_driver,
8287
                                          "%s/disk%d" % (file_storage_dir,
8288
                                                         disk_index)),
8289
                              mode=disk[constants.IDISK_MODE],
8290
                              params=ld_params[0])
8291
      disks.append(disk_dev)
8292
  elif template_name == constants.DT_BLOCK:
8293
    if len(secondary_nodes) != 0:
8294
      raise errors.ProgrammerError("Wrong template configuration")
8295

    
8296
    for idx, disk in enumerate(disk_info):
8297
      disk_index = idx + base_index
8298
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
8299
                              size=disk[constants.IDISK_SIZE],
8300
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
8301
                                          disk[constants.IDISK_ADOPT]),
8302
                              iv_name="disk/%d" % disk_index,
8303
                              mode=disk[constants.IDISK_MODE],
8304
                              params=ld_params[0])
8305
      disks.append(disk_dev)
8306

    
8307
  else:
8308
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
8309
  return disks
8310

    
8311

    
8312
def _GetInstanceInfoText(instance):
8313
  """Compute that text that should be added to the disk's metadata.
8314

8315
  """
8316
  return "originstname+%s" % instance.name
8317

    
8318

    
8319
def _CalcEta(time_taken, written, total_size):
8320
  """Calculates the ETA based on size written and total size.
8321

8322
  @param time_taken: The time taken so far
8323
  @param written: amount written so far
8324
  @param total_size: The total size of data to be written
8325
  @return: The remaining time in seconds
8326

8327
  """
8328
  avg_time = time_taken / float(written)
8329
  return (total_size - written) * avg_time
8330

    
8331

    
8332
def _WipeDisks(lu, instance):
8333
  """Wipes instance disks.
8334

8335
  @type lu: L{LogicalUnit}
8336
  @param lu: the logical unit on whose behalf we execute
8337
  @type instance: L{objects.Instance}
8338
  @param instance: the instance whose disks we should create
8339
  @return: the success of the wipe
8340

8341
  """
8342
  node = instance.primary_node
8343

    
8344
  for device in instance.disks:
8345
    lu.cfg.SetDiskID(device, node)
8346

    
8347
  logging.info("Pause sync of instance %s disks", instance.name)
8348
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
8349

    
8350
  for idx, success in enumerate(result.payload):
8351
    if not success:
8352
      logging.warn("pause-sync of instance %s for disks %d failed",
8353
                   instance.name, idx)
8354

    
8355
  try:
8356
    for idx, device in enumerate(instance.disks):
8357
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
8358
      # MAX_WIPE_CHUNK at max
8359
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
8360
                            constants.MIN_WIPE_CHUNK_PERCENT)
8361
      # we _must_ make this an int, otherwise rounding errors will
8362
      # occur
8363
      wipe_chunk_size = int(wipe_chunk_size)
8364

    
8365
      lu.LogInfo("* Wiping disk %d", idx)
8366
      logging.info("Wiping disk %d for instance %s, node %s using"
8367
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
8368

    
8369
      offset = 0
8370
      size = device.size
8371
      last_output = 0
8372
      start_time = time.time()
8373

    
8374
      while offset < size:
8375
        wipe_size = min(wipe_chunk_size, size - offset)
8376
        logging.debug("Wiping disk %d, offset %s, chunk %s",
8377
                      idx, offset, wipe_size)
8378
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
8379
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
8380
                     (idx, offset, wipe_size))
8381
        now = time.time()
8382
        offset += wipe_size
8383
        if now - last_output >= 60:
8384
          eta = _CalcEta(now - start_time, offset, size)
8385
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
8386
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
8387
          last_output = now
8388
  finally:
8389
    logging.info("Resume sync of instance %s disks", instance.name)
8390

    
8391
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
8392

    
8393
    for idx, success in enumerate(result.payload):
8394
      if not success:
8395
        lu.LogWarning("Resume sync of disk %d failed, please have a"
8396
                      " look at the status and troubleshoot the issue", idx)
8397
        logging.warn("resume-sync of instance %s for disks %d failed",
8398
                     instance.name, idx)
8399

    
8400

    
8401
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
8402
  """Create all disks for an instance.
8403

8404
  This abstracts away some work from AddInstance.
8405

8406
  @type lu: L{LogicalUnit}
8407
  @param lu: the logical unit on whose behalf we execute
8408
  @type instance: L{objects.Instance}
8409
  @param instance: the instance whose disks we should create
8410
  @type to_skip: list
8411
  @param to_skip: list of indices to skip
8412
  @type target_node: string
8413
  @param target_node: if passed, overrides the target node for creation
8414
  @rtype: boolean
8415
  @return: the success of the creation
8416

8417
  """
8418
  info = _GetInstanceInfoText(instance)
8419
  if target_node is None:
8420
    pnode = instance.primary_node
8421
    all_nodes = instance.all_nodes
8422
  else:
8423
    pnode = target_node
8424
    all_nodes = [pnode]
8425

    
8426
  if instance.disk_template in constants.DTS_FILEBASED:
8427
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
8428
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
8429

    
8430
    result.Raise("Failed to create directory '%s' on"
8431
                 " node %s" % (file_storage_dir, pnode))
8432

    
8433
  # Note: this needs to be kept in sync with adding of disks in
8434
  # LUInstanceSetParams
8435
  for idx, device in enumerate(instance.disks):
8436
    if to_skip and idx in to_skip:
8437
      continue
8438
    logging.info("Creating volume %s for instance %s",
8439
                 device.iv_name, instance.name)
8440
    #HARDCODE
8441
    for node in all_nodes:
8442
      f_create = node == pnode
8443
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
8444

    
8445

    
8446
def _RemoveDisks(lu, instance, target_node=None):
8447
  """Remove all disks for an instance.
8448

8449
  This abstracts away some work from `AddInstance()` and
8450
  `RemoveInstance()`. Note that in case some of the devices couldn't
8451
  be removed, the removal will continue with the other ones (compare
8452
  with `_CreateDisks()`).
8453

8454
  @type lu: L{LogicalUnit}
8455
  @param lu: the logical unit on whose behalf we execute
8456
  @type instance: L{objects.Instance}
8457
  @param instance: the instance whose disks we should remove
8458
  @type target_node: string
8459
  @param target_node: used to override the node on which to remove the disks
8460
  @rtype: boolean
8461
  @return: the success of the removal
8462

8463
  """
8464
  logging.info("Removing block devices for instance %s", instance.name)
8465

    
8466
  all_result = True
8467
  for device in instance.disks:
8468
    if target_node:
8469
      edata = [(target_node, device)]
8470
    else:
8471
      edata = device.ComputeNodeTree(instance.primary_node)
8472
    for node, disk in edata:
8473
      lu.cfg.SetDiskID(disk, node)
8474
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
8475
      if msg:
8476
        lu.LogWarning("Could not remove block device %s on node %s,"
8477
                      " continuing anyway: %s", device.iv_name, node, msg)
8478
        all_result = False
8479

    
8480
    # if this is a DRBD disk, return its port to the pool
8481
    if device.dev_type in constants.LDS_DRBD:
8482
      tcp_port = device.logical_id[2]
8483
      lu.cfg.AddTcpUdpPort(tcp_port)
8484

    
8485
  if instance.disk_template == constants.DT_FILE:
8486
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
8487
    if target_node:
8488
      tgt = target_node
8489
    else:
8490
      tgt = instance.primary_node
8491
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
8492
    if result.fail_msg:
8493
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
8494
                    file_storage_dir, instance.primary_node, result.fail_msg)
8495
      all_result = False
8496

    
8497
  return all_result
8498

    
8499

    
8500
def _ComputeDiskSizePerVG(disk_template, disks):
8501
  """Compute disk size requirements in the volume group
8502

8503
  """
8504
  def _compute(disks, payload):
8505
    """Universal algorithm.
8506

8507
    """
8508
    vgs = {}
8509
    for disk in disks:
8510
      vgs[disk[constants.IDISK_VG]] = \
8511
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
8512

    
8513
    return vgs
8514

    
8515
  # Required free disk space as a function of disk and swap space
8516
  req_size_dict = {
8517
    constants.DT_DISKLESS: {},
8518
    constants.DT_PLAIN: _compute(disks, 0),
8519
    # 128 MB are added for drbd metadata for each disk
8520
    constants.DT_DRBD8: _compute(disks, DRBD_META_SIZE),
8521
    constants.DT_FILE: {},
8522
    constants.DT_SHARED_FILE: {},
8523
  }
8524

    
8525
  if disk_template not in req_size_dict:
8526
    raise errors.ProgrammerError("Disk template '%s' size requirement"
8527
                                 " is unknown" % disk_template)
8528

    
8529
  return req_size_dict[disk_template]
8530

    
8531

    
8532
def _ComputeDiskSize(disk_template, disks):
8533
  """Compute disk size requirements in the volume group
8534

8535
  """
8536
  # Required free disk space as a function of disk and swap space
8537
  req_size_dict = {
8538
    constants.DT_DISKLESS: None,
8539
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
8540
    # 128 MB are added for drbd metadata for each disk
8541
    constants.DT_DRBD8:
8542
      sum(d[constants.IDISK_SIZE] + DRBD_META_SIZE for d in disks),
8543
    constants.DT_FILE: None,
8544
    constants.DT_SHARED_FILE: 0,
8545
    constants.DT_BLOCK: 0,
8546
  }
8547

    
8548
  if disk_template not in req_size_dict:
8549
    raise errors.ProgrammerError("Disk template '%s' size requirement"
8550
                                 " is unknown" % disk_template)
8551

    
8552
  return req_size_dict[disk_template]
8553

    
8554

    
8555
def _FilterVmNodes(lu, nodenames):
8556
  """Filters out non-vm_capable nodes from a list.
8557

8558
  @type lu: L{LogicalUnit}
8559
  @param lu: the logical unit for which we check
8560
  @type nodenames: list
8561
  @param nodenames: the list of nodes on which we should check
8562
  @rtype: list
8563
  @return: the list of vm-capable nodes
8564

8565
  """
8566
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
8567
  return [name for name in nodenames if name not in vm_nodes]
8568

    
8569

    
8570
def _CheckHVParams(lu, nodenames, hvname, hvparams):
8571
  """Hypervisor parameter validation.
8572

8573
  This function abstract the hypervisor parameter validation to be
8574
  used in both instance create and instance modify.
8575

8576
  @type lu: L{LogicalUnit}
8577
  @param lu: the logical unit for which we check
8578
  @type nodenames: list
8579
  @param nodenames: the list of nodes on which we should check
8580
  @type hvname: string
8581
  @param hvname: the name of the hypervisor we should use
8582
  @type hvparams: dict
8583
  @param hvparams: the parameters which we need to check
8584
  @raise errors.OpPrereqError: if the parameters are not valid
8585

8586
  """
8587
  nodenames = _FilterVmNodes(lu, nodenames)
8588

    
8589
  cluster = lu.cfg.GetClusterInfo()
8590
  hvfull = objects.FillDict(cluster.hvparams.get(hvname, {}), hvparams)
8591

    
8592
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames, hvname, hvfull)
8593
  for node in nodenames:
8594
    info = hvinfo[node]
8595
    if info.offline:
8596
      continue
8597
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
8598

    
8599

    
8600
def _CheckOSParams(lu, required, nodenames, osname, osparams):
8601
  """OS parameters validation.
8602

8603
  @type lu: L{LogicalUnit}
8604
  @param lu: the logical unit for which we check
8605
  @type required: boolean
8606
  @param required: whether the validation should fail if the OS is not
8607
      found
8608
  @type nodenames: list
8609
  @param nodenames: the list of nodes on which we should check
8610
  @type osname: string
8611
  @param osname: the name of the hypervisor we should use
8612
  @type osparams: dict
8613
  @param osparams: the parameters which we need to check
8614
  @raise errors.OpPrereqError: if the parameters are not valid
8615

8616
  """
8617
  nodenames = _FilterVmNodes(lu, nodenames)
8618
  result = lu.rpc.call_os_validate(nodenames, required, osname,
8619
                                   [constants.OS_VALIDATE_PARAMETERS],
8620
                                   osparams)
8621
  for node, nres in result.items():
8622
    # we don't check for offline cases since this should be run only
8623
    # against the master node and/or an instance's nodes
8624
    nres.Raise("OS Parameters validation failed on node %s" % node)
8625
    if not nres.payload:
8626
      lu.LogInfo("OS %s not found on node %s, validation skipped",
8627
                 osname, node)
8628

    
8629

    
8630
class LUInstanceCreate(LogicalUnit):
8631
  """Create an instance.
8632

8633
  """
8634
  HPATH = "instance-add"
8635
  HTYPE = constants.HTYPE_INSTANCE
8636
  REQ_BGL = False
8637

    
8638
  def CheckArguments(self):
8639
    """Check arguments.
8640

8641
    """
8642
    # do not require name_check to ease forward/backward compatibility
8643
    # for tools
8644
    if self.op.no_install and self.op.start:
8645
      self.LogInfo("No-installation mode selected, disabling startup")
8646
      self.op.start = False
8647
    # validate/normalize the instance name
8648
    self.op.instance_name = \
8649
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
8650

    
8651
    if self.op.ip_check and not self.op.name_check:
8652
      # TODO: make the ip check more flexible and not depend on the name check
8653
      raise errors.OpPrereqError("Cannot do IP address check without a name"
8654
                                 " check", errors.ECODE_INVAL)
8655

    
8656
    # check nics' parameter names
8657
    for nic in self.op.nics:
8658
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
8659

    
8660
    # check disks. parameter names and consistent adopt/no-adopt strategy
8661
    has_adopt = has_no_adopt = False
8662
    for disk in self.op.disks:
8663
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
8664
      if constants.IDISK_ADOPT in disk:
8665
        has_adopt = True
8666
      else:
8667
        has_no_adopt = True
8668
    if has_adopt and has_no_adopt:
8669
      raise errors.OpPrereqError("Either all disks are adopted or none is",
8670
                                 errors.ECODE_INVAL)
8671
    if has_adopt:
8672
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
8673
        raise errors.OpPrereqError("Disk adoption is not supported for the"
8674
                                   " '%s' disk template" %
8675
                                   self.op.disk_template,
8676
                                   errors.ECODE_INVAL)
8677
      if self.op.iallocator is not None:
8678
        raise errors.OpPrereqError("Disk adoption not allowed with an"
8679
                                   " iallocator script", errors.ECODE_INVAL)
8680
      if self.op.mode == constants.INSTANCE_IMPORT:
8681
        raise errors.OpPrereqError("Disk adoption not allowed for"
8682
                                   " instance import", errors.ECODE_INVAL)
8683
    else:
8684
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
8685
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
8686
                                   " but no 'adopt' parameter given" %
8687
                                   self.op.disk_template,
8688
                                   errors.ECODE_INVAL)
8689

    
8690
    self.adopt_disks = has_adopt
8691

    
8692
    # instance name verification
8693
    if self.op.name_check:
8694
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
8695
      self.op.instance_name = self.hostname1.name
8696
      # used in CheckPrereq for ip ping check
8697
      self.check_ip = self.hostname1.ip
8698
    else:
8699
      self.check_ip = None
8700

    
8701
    # file storage checks
8702
    if (self.op.file_driver and
8703
        not self.op.file_driver in constants.FILE_DRIVER):
8704
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
8705
                                 self.op.file_driver, errors.ECODE_INVAL)
8706

    
8707
    if self.op.disk_template == constants.DT_FILE:
8708
      opcodes.RequireFileStorage()
8709
    elif self.op.disk_template == constants.DT_SHARED_FILE:
8710
      opcodes.RequireSharedFileStorage()
8711

    
8712
    ### Node/iallocator related checks
8713
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
8714

    
8715
    if self.op.pnode is not None:
8716
      if self.op.disk_template in constants.DTS_INT_MIRROR:
8717
        if self.op.snode is None:
8718
          raise errors.OpPrereqError("The networked disk templates need"
8719
                                     " a mirror node", errors.ECODE_INVAL)
8720
      elif self.op.snode:
8721
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
8722
                        " template")
8723
        self.op.snode = None
8724

    
8725
    self._cds = _GetClusterDomainSecret()
8726

    
8727
    if self.op.mode == constants.INSTANCE_IMPORT:
8728
      # On import force_variant must be True, because if we forced it at
8729
      # initial install, our only chance when importing it back is that it
8730
      # works again!
8731
      self.op.force_variant = True
8732

    
8733
      if self.op.no_install:
8734
        self.LogInfo("No-installation mode has no effect during import")
8735

    
8736
    elif self.op.mode == constants.INSTANCE_CREATE:
8737
      if self.op.os_type is None:
8738
        raise errors.OpPrereqError("No guest OS specified",
8739
                                   errors.ECODE_INVAL)
8740
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
8741
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
8742
                                   " installation" % self.op.os_type,
8743
                                   errors.ECODE_STATE)
8744
      if self.op.disk_template is None:
8745
        raise errors.OpPrereqError("No disk template specified",
8746
                                   errors.ECODE_INVAL)
8747

    
8748
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8749
      # Check handshake to ensure both clusters have the same domain secret
8750
      src_handshake = self.op.source_handshake
8751
      if not src_handshake:
8752
        raise errors.OpPrereqError("Missing source handshake",
8753
                                   errors.ECODE_INVAL)
8754

    
8755
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
8756
                                                           src_handshake)
8757
      if errmsg:
8758
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
8759
                                   errors.ECODE_INVAL)
8760

    
8761
      # Load and check source CA
8762
      self.source_x509_ca_pem = self.op.source_x509_ca
8763
      if not self.source_x509_ca_pem:
8764
        raise errors.OpPrereqError("Missing source X509 CA",
8765
                                   errors.ECODE_INVAL)
8766

    
8767
      try:
8768
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
8769
                                                    self._cds)
8770
      except OpenSSL.crypto.Error, err:
8771
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
8772
                                   (err, ), errors.ECODE_INVAL)
8773

    
8774
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
8775
      if errcode is not None:
8776
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
8777
                                   errors.ECODE_INVAL)
8778

    
8779
      self.source_x509_ca = cert
8780

    
8781
      src_instance_name = self.op.source_instance_name
8782
      if not src_instance_name:
8783
        raise errors.OpPrereqError("Missing source instance name",
8784
                                   errors.ECODE_INVAL)
8785

    
8786
      self.source_instance_name = \
8787
          netutils.GetHostname(name=src_instance_name).name
8788

    
8789
    else:
8790
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
8791
                                 self.op.mode, errors.ECODE_INVAL)
8792

    
8793
  def ExpandNames(self):
8794
    """ExpandNames for CreateInstance.
8795

8796
    Figure out the right locks for instance creation.
8797

8798
    """
8799
    self.needed_locks = {}
8800

    
8801
    instance_name = self.op.instance_name
8802
    # this is just a preventive check, but someone might still add this
8803
    # instance in the meantime, and creation will fail at lock-add time
8804
    if instance_name in self.cfg.GetInstanceList():
8805
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
8806
                                 instance_name, errors.ECODE_EXISTS)
8807

    
8808
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
8809

    
8810
    if self.op.iallocator:
8811
      # TODO: Find a solution to not lock all nodes in the cluster, e.g. by
8812
      # specifying a group on instance creation and then selecting nodes from
8813
      # that group
8814
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8815
      self.needed_locks[locking.LEVEL_NODE_RES] = locking.ALL_SET
8816
    else:
8817
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
8818
      nodelist = [self.op.pnode]
8819
      if self.op.snode is not None:
8820
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
8821
        nodelist.append(self.op.snode)
8822
      self.needed_locks[locking.LEVEL_NODE] = nodelist
8823
      # Lock resources of instance's primary and secondary nodes (copy to
8824
      # prevent accidential modification)
8825
      self.needed_locks[locking.LEVEL_NODE_RES] = list(nodelist)
8826

    
8827
    # in case of import lock the source node too
8828
    if self.op.mode == constants.INSTANCE_IMPORT:
8829
      src_node = self.op.src_node
8830
      src_path = self.op.src_path
8831

    
8832
      if src_path is None:
8833
        self.op.src_path = src_path = self.op.instance_name
8834

    
8835
      if src_node is None:
8836
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8837
        self.op.src_node = None
8838
        if os.path.isabs(src_path):
8839
          raise errors.OpPrereqError("Importing an instance from a path"
8840
                                     " requires a source node option",
8841
                                     errors.ECODE_INVAL)
8842
      else:
8843
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
8844
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
8845
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
8846
        if not os.path.isabs(src_path):
8847
          self.op.src_path = src_path = \
8848
            utils.PathJoin(constants.EXPORT_DIR, src_path)
8849

    
8850
  def _RunAllocator(self):
8851
    """Run the allocator based on input opcode.
8852

8853
    """
8854
    nics = [n.ToDict() for n in self.nics]
8855
    ial = IAllocator(self.cfg, self.rpc,
8856
                     mode=constants.IALLOCATOR_MODE_ALLOC,
8857
                     name=self.op.instance_name,
8858
                     disk_template=self.op.disk_template,
8859
                     tags=self.op.tags,
8860
                     os=self.op.os_type,
8861
                     vcpus=self.be_full[constants.BE_VCPUS],
8862
                     memory=self.be_full[constants.BE_MAXMEM],
8863
                     disks=self.disks,
8864
                     nics=nics,
8865
                     hypervisor=self.op.hypervisor,
8866
                     )
8867

    
8868
    ial.Run(self.op.iallocator)
8869

    
8870
    if not ial.success:
8871
      raise errors.OpPrereqError("Can't compute nodes using"
8872
                                 " iallocator '%s': %s" %
8873
                                 (self.op.iallocator, ial.info),
8874
                                 errors.ECODE_NORES)
8875
    if len(ial.result) != ial.required_nodes:
8876
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8877
                                 " of nodes (%s), required %s" %
8878
                                 (self.op.iallocator, len(ial.result),
8879
                                  ial.required_nodes), errors.ECODE_FAULT)
8880
    self.op.pnode = ial.result[0]
8881
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8882
                 self.op.instance_name, self.op.iallocator,
8883
                 utils.CommaJoin(ial.result))
8884
    if ial.required_nodes == 2:
8885
      self.op.snode = ial.result[1]
8886

    
8887
  def BuildHooksEnv(self):
8888
    """Build hooks env.
8889

8890
    This runs on master, primary and secondary nodes of the instance.
8891

8892
    """
8893
    env = {
8894
      "ADD_MODE": self.op.mode,
8895
      }
8896
    if self.op.mode == constants.INSTANCE_IMPORT:
8897
      env["SRC_NODE"] = self.op.src_node
8898
      env["SRC_PATH"] = self.op.src_path
8899
      env["SRC_IMAGES"] = self.src_images
8900

    
8901
    env.update(_BuildInstanceHookEnv(
8902
      name=self.op.instance_name,
8903
      primary_node=self.op.pnode,
8904
      secondary_nodes=self.secondaries,
8905
      status=self.op.start,
8906
      os_type=self.op.os_type,
8907
      minmem=self.be_full[constants.BE_MINMEM],
8908
      maxmem=self.be_full[constants.BE_MAXMEM],
8909
      vcpus=self.be_full[constants.BE_VCPUS],
8910
      nics=_NICListToTuple(self, self.nics),
8911
      disk_template=self.op.disk_template,
8912
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8913
             for d in self.disks],
8914
      bep=self.be_full,
8915
      hvp=self.hv_full,
8916
      hypervisor_name=self.op.hypervisor,
8917
      tags=self.op.tags,
8918
    ))
8919

    
8920
    return env
8921

    
8922
  def BuildHooksNodes(self):
8923
    """Build hooks nodes.
8924

8925
    """
8926
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8927
    return nl, nl
8928

    
8929
  def _ReadExportInfo(self):
8930
    """Reads the export information from disk.
8931

8932
    It will override the opcode source node and path with the actual
8933
    information, if these two were not specified before.
8934

8935
    @return: the export information
8936

8937
    """
8938
    assert self.op.mode == constants.INSTANCE_IMPORT
8939

    
8940
    src_node = self.op.src_node
8941
    src_path = self.op.src_path
8942

    
8943
    if src_node is None:
8944
      locked_nodes = self.owned_locks(locking.LEVEL_NODE)
8945
      exp_list = self.rpc.call_export_list(locked_nodes)
8946
      found = False
8947
      for node in exp_list:
8948
        if exp_list[node].fail_msg:
8949
          continue
8950
        if src_path in exp_list[node].payload:
8951
          found = True
8952
          self.op.src_node = src_node = node
8953
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8954
                                                       src_path)
8955
          break
8956
      if not found:
8957
        raise errors.OpPrereqError("No export found for relative path %s" %
8958
                                    src_path, errors.ECODE_INVAL)
8959

    
8960
    _CheckNodeOnline(self, src_node)
8961
    result = self.rpc.call_export_info(src_node, src_path)
8962
    result.Raise("No export or invalid export found in dir %s" % src_path)
8963

    
8964
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8965
    if not export_info.has_section(constants.INISECT_EXP):
8966
      raise errors.ProgrammerError("Corrupted export config",
8967
                                   errors.ECODE_ENVIRON)
8968

    
8969
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8970
    if (int(ei_version) != constants.EXPORT_VERSION):
8971
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8972
                                 (ei_version, constants.EXPORT_VERSION),
8973
                                 errors.ECODE_ENVIRON)
8974
    return export_info
8975

    
8976
  def _ReadExportParams(self, einfo):
8977
    """Use export parameters as defaults.
8978

8979
    In case the opcode doesn't specify (as in override) some instance
8980
    parameters, then try to use them from the export information, if
8981
    that declares them.
8982

8983
    """
8984
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8985

    
8986
    if self.op.disk_template is None:
8987
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8988
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8989
                                          "disk_template")
8990
        if self.op.disk_template not in constants.DISK_TEMPLATES:
8991
          raise errors.OpPrereqError("Disk template specified in configuration"
8992
                                     " file is not one of the allowed values:"
8993
                                     " %s" % " ".join(constants.DISK_TEMPLATES))
8994
      else:
8995
        raise errors.OpPrereqError("No disk template specified and the export"
8996
                                   " is missing the disk_template information",
8997
                                   errors.ECODE_INVAL)
8998

    
8999
    if not self.op.disks:
9000
      disks = []
9001
      # TODO: import the disk iv_name too
9002
      for idx in range(constants.MAX_DISKS):
9003
        if einfo.has_option(constants.INISECT_INS, "disk%d_size" % idx):
9004
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
9005
          disks.append({constants.IDISK_SIZE: disk_sz})
9006
      self.op.disks = disks
9007
      if not disks and self.op.disk_template != constants.DT_DISKLESS:
9008
        raise errors.OpPrereqError("No disk info specified and the export"
9009
                                   " is missing the disk information",
9010
                                   errors.ECODE_INVAL)
9011

    
9012
    if not self.op.nics:
9013
      nics = []
9014
      for idx in range(constants.MAX_NICS):
9015
        if einfo.has_option(constants.INISECT_INS, "nic%d_mac" % idx):
9016
          ndict = {}
9017
          for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
9018
            v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
9019
            ndict[name] = v
9020
          nics.append(ndict)
9021
        else:
9022
          break
9023
      self.op.nics = nics
9024

    
9025
    if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
9026
      self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
9027

    
9028
    if (self.op.hypervisor is None and
9029
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
9030
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
9031

    
9032
    if einfo.has_section(constants.INISECT_HYP):
9033
      # use the export parameters but do not override the ones
9034
      # specified by the user
9035
      for name, value in einfo.items(constants.INISECT_HYP):
9036
        if name not in self.op.hvparams:
9037
          self.op.hvparams[name] = value
9038

    
9039
    if einfo.has_section(constants.INISECT_BEP):
9040
      # use the parameters, without overriding
9041
      for name, value in einfo.items(constants.INISECT_BEP):
9042
        if name not in self.op.beparams:
9043
          self.op.beparams[name] = value
9044
        # Compatibility for the old "memory" be param
9045
        if name == constants.BE_MEMORY:
9046
          if constants.BE_MAXMEM not in self.op.beparams:
9047
            self.op.beparams[constants.BE_MAXMEM] = value
9048
          if constants.BE_MINMEM not in self.op.beparams:
9049
            self.op.beparams[constants.BE_MINMEM] = value
9050
    else:
9051
      # try to read the parameters old style, from the main section
9052
      for name in constants.BES_PARAMETERS:
9053
        if (name not in self.op.beparams and
9054
            einfo.has_option(constants.INISECT_INS, name)):
9055
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
9056

    
9057
    if einfo.has_section(constants.INISECT_OSP):
9058
      # use the parameters, without overriding
9059
      for name, value in einfo.items(constants.INISECT_OSP):
9060
        if name not in self.op.osparams:
9061
          self.op.osparams[name] = value
9062

    
9063
  def _RevertToDefaults(self, cluster):
9064
    """Revert the instance parameters to the default values.
9065

9066
    """
9067
    # hvparams
9068
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
9069
    for name in self.op.hvparams.keys():
9070
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
9071
        del self.op.hvparams[name]
9072
    # beparams
9073
    be_defs = cluster.SimpleFillBE({})
9074
    for name in self.op.beparams.keys():
9075
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
9076
        del self.op.beparams[name]
9077
    # nic params
9078
    nic_defs = cluster.SimpleFillNIC({})
9079
    for nic in self.op.nics:
9080
      for name in constants.NICS_PARAMETERS:
9081
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
9082
          del nic[name]
9083
    # osparams
9084
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
9085
    for name in self.op.osparams.keys():
9086
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
9087
        del self.op.osparams[name]
9088

    
9089
  def _CalculateFileStorageDir(self):
9090
    """Calculate final instance file storage dir.
9091

9092
    """
9093
    # file storage dir calculation/check
9094
    self.instance_file_storage_dir = None
9095
    if self.op.disk_template in constants.DTS_FILEBASED:
9096
      # build the full file storage dir path
9097
      joinargs = []
9098

    
9099
      if self.op.disk_template == constants.DT_SHARED_FILE:
9100
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
9101
      else:
9102
        get_fsd_fn = self.cfg.GetFileStorageDir
9103

    
9104
      cfg_storagedir = get_fsd_fn()
9105
      if not cfg_storagedir:
9106
        raise errors.OpPrereqError("Cluster file storage dir not defined")
9107
      joinargs.append(cfg_storagedir)
9108

    
9109
      if self.op.file_storage_dir is not None:
9110
        joinargs.append(self.op.file_storage_dir)
9111

    
9112
      joinargs.append(self.op.instance_name)
9113

    
9114
      # pylint: disable=W0142
9115
      self.instance_file_storage_dir = utils.PathJoin(*joinargs)
9116

    
9117
  def CheckPrereq(self):
9118
    """Check prerequisites.
9119

9120
    """
9121
    self._CalculateFileStorageDir()
9122

    
9123
    if self.op.mode == constants.INSTANCE_IMPORT:
9124
      export_info = self._ReadExportInfo()
9125
      self._ReadExportParams(export_info)
9126

    
9127
    if (not self.cfg.GetVGName() and
9128
        self.op.disk_template not in constants.DTS_NOT_LVM):
9129
      raise errors.OpPrereqError("Cluster does not support lvm-based"
9130
                                 " instances", errors.ECODE_STATE)
9131

    
9132
    if (self.op.hypervisor is None or
9133
        self.op.hypervisor == constants.VALUE_AUTO):
9134
      self.op.hypervisor = self.cfg.GetHypervisorType()
9135

    
9136
    cluster = self.cfg.GetClusterInfo()
9137
    enabled_hvs = cluster.enabled_hypervisors
9138
    if self.op.hypervisor not in enabled_hvs:
9139
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
9140
                                 " cluster (%s)" % (self.op.hypervisor,
9141
                                  ",".join(enabled_hvs)),
9142
                                 errors.ECODE_STATE)
9143

    
9144
    # Check tag validity
9145
    for tag in self.op.tags:
9146
      objects.TaggableObject.ValidateTag(tag)
9147

    
9148
    # check hypervisor parameter syntax (locally)
9149
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
9150
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
9151
                                      self.op.hvparams)
9152
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
9153
    hv_type.CheckParameterSyntax(filled_hvp)
9154
    self.hv_full = filled_hvp
9155
    # check that we don't specify global parameters on an instance
9156
    _CheckGlobalHvParams(self.op.hvparams)
9157

    
9158
    # fill and remember the beparams dict
9159
    default_beparams = cluster.beparams[constants.PP_DEFAULT]
9160
    for param, value in self.op.beparams.iteritems():
9161
      if value == constants.VALUE_AUTO:
9162
        self.op.beparams[param] = default_beparams[param]
9163
    objects.UpgradeBeParams(self.op.beparams)
9164
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
9165
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
9166

    
9167
    # build os parameters
9168
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
9169

    
9170
    # now that hvp/bep are in final format, let's reset to defaults,
9171
    # if told to do so
9172
    if self.op.identify_defaults:
9173
      self._RevertToDefaults(cluster)
9174

    
9175
    # NIC buildup
9176
    self.nics = []
9177
    for idx, nic in enumerate(self.op.nics):
9178
      nic_mode_req = nic.get(constants.INIC_MODE, None)
9179
      nic_mode = nic_mode_req
9180
      if nic_mode is None or nic_mode == constants.VALUE_AUTO:
9181
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
9182

    
9183
      # in routed mode, for the first nic, the default ip is 'auto'
9184
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
9185
        default_ip_mode = constants.VALUE_AUTO
9186
      else:
9187
        default_ip_mode = constants.VALUE_NONE
9188

    
9189
      # ip validity checks
9190
      ip = nic.get(constants.INIC_IP, default_ip_mode)
9191
      if ip is None or ip.lower() == constants.VALUE_NONE:
9192
        nic_ip = None
9193
      elif ip.lower() == constants.VALUE_AUTO:
9194
        if not self.op.name_check:
9195
          raise errors.OpPrereqError("IP address set to auto but name checks"
9196
                                     " have been skipped",
9197
                                     errors.ECODE_INVAL)
9198
        nic_ip = self.hostname1.ip
9199
      else:
9200
        if not netutils.IPAddress.IsValid(ip):
9201
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
9202
                                     errors.ECODE_INVAL)
9203
        nic_ip = ip
9204

    
9205
      # TODO: check the ip address for uniqueness
9206
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
9207
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
9208
                                   errors.ECODE_INVAL)
9209

    
9210
      # MAC address verification
9211
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
9212
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9213
        mac = utils.NormalizeAndValidateMac(mac)
9214

    
9215
        try:
9216
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
9217
        except errors.ReservationError:
9218
          raise errors.OpPrereqError("MAC address %s already in use"
9219
                                     " in cluster" % mac,
9220
                                     errors.ECODE_NOTUNIQUE)
9221

    
9222
      #  Build nic parameters
9223
      link = nic.get(constants.INIC_LINK, None)
9224
      if link == constants.VALUE_AUTO:
9225
        link = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_LINK]
9226
      nicparams = {}
9227
      if nic_mode_req:
9228
        nicparams[constants.NIC_MODE] = nic_mode
9229
      if link:
9230
        nicparams[constants.NIC_LINK] = link
9231

    
9232
      check_params = cluster.SimpleFillNIC(nicparams)
9233
      objects.NIC.CheckParameterSyntax(check_params)
9234
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
9235

    
9236
    # disk checks/pre-build
9237
    default_vg = self.cfg.GetVGName()
9238
    self.disks = []
9239
    for disk in self.op.disks:
9240
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
9241
      if mode not in constants.DISK_ACCESS_SET:
9242
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
9243
                                   mode, errors.ECODE_INVAL)
9244
      size = disk.get(constants.IDISK_SIZE, None)
9245
      if size is None:
9246
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
9247
      try:
9248
        size = int(size)
9249
      except (TypeError, ValueError):
9250
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
9251
                                   errors.ECODE_INVAL)
9252

    
9253
      data_vg = disk.get(constants.IDISK_VG, default_vg)
9254
      new_disk = {
9255
        constants.IDISK_SIZE: size,
9256
        constants.IDISK_MODE: mode,
9257
        constants.IDISK_VG: data_vg,
9258
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
9259
        }
9260
      if constants.IDISK_ADOPT in disk:
9261
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
9262
      self.disks.append(new_disk)
9263

    
9264
    if self.op.mode == constants.INSTANCE_IMPORT:
9265
      disk_images = []
9266
      for idx in range(len(self.disks)):
9267
        option = "disk%d_dump" % idx
9268
        if export_info.has_option(constants.INISECT_INS, option):
9269
          # FIXME: are the old os-es, disk sizes, etc. useful?
9270
          export_name = export_info.get(constants.INISECT_INS, option)
9271
          image = utils.PathJoin(self.op.src_path, export_name)
9272
          disk_images.append(image)
9273
        else:
9274
          disk_images.append(False)
9275

    
9276
      self.src_images = disk_images
9277

    
9278
      old_name = export_info.get(constants.INISECT_INS, "name")
9279
      if self.op.instance_name == old_name:
9280
        for idx, nic in enumerate(self.nics):
9281
          if nic.mac == constants.VALUE_AUTO:
9282
            nic_mac_ini = "nic%d_mac" % idx
9283
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
9284

    
9285
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
9286

    
9287
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
9288
    if self.op.ip_check:
9289
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
9290
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
9291
                                   (self.check_ip, self.op.instance_name),
9292
                                   errors.ECODE_NOTUNIQUE)
9293

    
9294
    #### mac address generation
9295
    # By generating here the mac address both the allocator and the hooks get
9296
    # the real final mac address rather than the 'auto' or 'generate' value.
9297
    # There is a race condition between the generation and the instance object
9298
    # creation, which means that we know the mac is valid now, but we're not
9299
    # sure it will be when we actually add the instance. If things go bad
9300
    # adding the instance will abort because of a duplicate mac, and the
9301
    # creation job will fail.
9302
    for nic in self.nics:
9303
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9304
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
9305

    
9306
    #### allocator run
9307

    
9308
    if self.op.iallocator is not None:
9309
      self._RunAllocator()
9310

    
9311
    # Release all unneeded node locks
9312
    _ReleaseLocks(self, locking.LEVEL_NODE,
9313
                  keep=filter(None, [self.op.pnode, self.op.snode,
9314
                                     self.op.src_node]))
9315

    
9316
    #### node related checks
9317

    
9318
    # check primary node
9319
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
9320
    assert self.pnode is not None, \
9321
      "Cannot retrieve locked node %s" % self.op.pnode
9322
    if pnode.offline:
9323
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
9324
                                 pnode.name, errors.ECODE_STATE)
9325
    if pnode.drained:
9326
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
9327
                                 pnode.name, errors.ECODE_STATE)
9328
    if not pnode.vm_capable:
9329
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
9330
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
9331

    
9332
    self.secondaries = []
9333

    
9334
    # mirror node verification
9335
    if self.op.disk_template in constants.DTS_INT_MIRROR:
9336
      if self.op.snode == pnode.name:
9337
        raise errors.OpPrereqError("The secondary node cannot be the"
9338
                                   " primary node", errors.ECODE_INVAL)
9339
      _CheckNodeOnline(self, self.op.snode)
9340
      _CheckNodeNotDrained(self, self.op.snode)
9341
      _CheckNodeVmCapable(self, self.op.snode)
9342
      self.secondaries.append(self.op.snode)
9343

    
9344
      snode = self.cfg.GetNodeInfo(self.op.snode)
9345
      if pnode.group != snode.group:
9346
        self.LogWarning("The primary and secondary nodes are in two"
9347
                        " different node groups; the disk parameters"
9348
                        " from the first disk's node group will be"
9349
                        " used")
9350

    
9351
    nodenames = [pnode.name] + self.secondaries
9352

    
9353
    # disk parameters (not customizable at instance or node level)
9354
    # just use the primary node parameters, ignoring the secondary.
9355
    self.diskparams = self.cfg.GetNodeGroup(pnode.group).diskparams
9356

    
9357
    if not self.adopt_disks:
9358
      # Check lv size requirements, if not adopting
9359
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
9360
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
9361

    
9362
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
9363
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
9364
                                disk[constants.IDISK_ADOPT])
9365
                     for disk in self.disks])
9366
      if len(all_lvs) != len(self.disks):
9367
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
9368
                                   errors.ECODE_INVAL)
9369
      for lv_name in all_lvs:
9370
        try:
9371
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
9372
          # to ReserveLV uses the same syntax
9373
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
9374
        except errors.ReservationError:
9375
          raise errors.OpPrereqError("LV named %s used by another instance" %
9376
                                     lv_name, errors.ECODE_NOTUNIQUE)
9377

    
9378
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
9379
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
9380

    
9381
      node_lvs = self.rpc.call_lv_list([pnode.name],
9382
                                       vg_names.payload.keys())[pnode.name]
9383
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
9384
      node_lvs = node_lvs.payload
9385

    
9386
      delta = all_lvs.difference(node_lvs.keys())
9387
      if delta:
9388
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
9389
                                   utils.CommaJoin(delta),
9390
                                   errors.ECODE_INVAL)
9391
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
9392
      if online_lvs:
9393
        raise errors.OpPrereqError("Online logical volumes found, cannot"
9394
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
9395
                                   errors.ECODE_STATE)
9396
      # update the size of disk based on what is found
9397
      for dsk in self.disks:
9398
        dsk[constants.IDISK_SIZE] = \
9399
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
9400
                                        dsk[constants.IDISK_ADOPT])][0]))
9401

    
9402
    elif self.op.disk_template == constants.DT_BLOCK:
9403
      # Normalize and de-duplicate device paths
9404
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
9405
                       for disk in self.disks])
9406
      if len(all_disks) != len(self.disks):
9407
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
9408
                                   errors.ECODE_INVAL)
9409
      baddisks = [d for d in all_disks
9410
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
9411
      if baddisks:
9412
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
9413
                                   " cannot be adopted" %
9414
                                   (", ".join(baddisks),
9415
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
9416
                                   errors.ECODE_INVAL)
9417

    
9418
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
9419
                                            list(all_disks))[pnode.name]
9420
      node_disks.Raise("Cannot get block device information from node %s" %
9421
                       pnode.name)
9422
      node_disks = node_disks.payload
9423
      delta = all_disks.difference(node_disks.keys())
9424
      if delta:
9425
        raise errors.OpPrereqError("Missing block device(s): %s" %
9426
                                   utils.CommaJoin(delta),
9427
                                   errors.ECODE_INVAL)
9428
      for dsk in self.disks:
9429
        dsk[constants.IDISK_SIZE] = \
9430
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
9431

    
9432
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
9433

    
9434
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
9435
    # check OS parameters (remotely)
9436
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
9437

    
9438
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
9439

    
9440
    # memory check on primary node
9441
    #TODO(dynmem): use MINMEM for checking
9442
    if self.op.start:
9443
      _CheckNodeFreeMemory(self, self.pnode.name,
9444
                           "creating instance %s" % self.op.instance_name,
9445
                           self.be_full[constants.BE_MAXMEM],
9446
                           self.op.hypervisor)
9447

    
9448
    self.dry_run_result = list(nodenames)
9449

    
9450
  def Exec(self, feedback_fn):
9451
    """Create and add the instance to the cluster.
9452

9453
    """
9454
    instance = self.op.instance_name
9455
    pnode_name = self.pnode.name
9456

    
9457
    assert not (self.owned_locks(locking.LEVEL_NODE_RES) -
9458
                self.owned_locks(locking.LEVEL_NODE)), \
9459
      "Node locks differ from node resource locks"
9460

    
9461
    ht_kind = self.op.hypervisor
9462
    if ht_kind in constants.HTS_REQ_PORT:
9463
      network_port = self.cfg.AllocatePort()
9464
    else:
9465
      network_port = None
9466

    
9467
    disks = _GenerateDiskTemplate(self,
9468
                                  self.op.disk_template,
9469
                                  instance, pnode_name,
9470
                                  self.secondaries,
9471
                                  self.disks,
9472
                                  self.instance_file_storage_dir,
9473
                                  self.op.file_driver,
9474
                                  0,
9475
                                  feedback_fn,
9476
                                  self.diskparams)
9477

    
9478
    iobj = objects.Instance(name=instance, os=self.op.os_type,
9479
                            primary_node=pnode_name,
9480
                            nics=self.nics, disks=disks,
9481
                            disk_template=self.op.disk_template,
9482
                            admin_state=constants.ADMINST_DOWN,
9483
                            network_port=network_port,
9484
                            beparams=self.op.beparams,
9485
                            hvparams=self.op.hvparams,
9486
                            hypervisor=self.op.hypervisor,
9487
                            osparams=self.op.osparams,
9488
                            )
9489

    
9490
    if self.op.tags:
9491
      for tag in self.op.tags:
9492
        iobj.AddTag(tag)
9493

    
9494
    if self.adopt_disks:
9495
      if self.op.disk_template == constants.DT_PLAIN:
9496
        # rename LVs to the newly-generated names; we need to construct
9497
        # 'fake' LV disks with the old data, plus the new unique_id
9498
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
9499
        rename_to = []
9500
        for t_dsk, a_dsk in zip(tmp_disks, self.disks):
9501
          rename_to.append(t_dsk.logical_id)
9502
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
9503
          self.cfg.SetDiskID(t_dsk, pnode_name)
9504
        result = self.rpc.call_blockdev_rename(pnode_name,
9505
                                               zip(tmp_disks, rename_to))
9506
        result.Raise("Failed to rename adoped LVs")
9507
    else:
9508
      feedback_fn("* creating instance disks...")
9509
      try:
9510
        _CreateDisks(self, iobj)
9511
      except errors.OpExecError:
9512
        self.LogWarning("Device creation failed, reverting...")
9513
        try:
9514
          _RemoveDisks(self, iobj)
9515
        finally:
9516
          self.cfg.ReleaseDRBDMinors(instance)
9517
          raise
9518

    
9519
    feedback_fn("adding instance %s to cluster config" % instance)
9520

    
9521
    self.cfg.AddInstance(iobj, self.proc.GetECId())
9522

    
9523
    # Declare that we don't want to remove the instance lock anymore, as we've
9524
    # added the instance to the config
9525
    del self.remove_locks[locking.LEVEL_INSTANCE]
9526

    
9527
    if self.op.mode == constants.INSTANCE_IMPORT:
9528
      # Release unused nodes
9529
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
9530
    else:
9531
      # Release all nodes
9532
      _ReleaseLocks(self, locking.LEVEL_NODE)
9533

    
9534
    disk_abort = False
9535
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
9536
      feedback_fn("* wiping instance disks...")
9537
      try:
9538
        _WipeDisks(self, iobj)
9539
      except errors.OpExecError, err:
9540
        logging.exception("Wiping disks failed")
9541
        self.LogWarning("Wiping instance disks failed (%s)", err)
9542
        disk_abort = True
9543

    
9544
    if disk_abort:
9545
      # Something is already wrong with the disks, don't do anything else
9546
      pass
9547
    elif self.op.wait_for_sync:
9548
      disk_abort = not _WaitForSync(self, iobj)
9549
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
9550
      # make sure the disks are not degraded (still sync-ing is ok)
9551
      feedback_fn("* checking mirrors status")
9552
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
9553
    else:
9554
      disk_abort = False
9555

    
9556
    if disk_abort:
9557
      _RemoveDisks(self, iobj)
9558
      self.cfg.RemoveInstance(iobj.name)
9559
      # Make sure the instance lock gets removed
9560
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
9561
      raise errors.OpExecError("There are some degraded disks for"
9562
                               " this instance")
9563

    
9564
    # Release all node resource locks
9565
    _ReleaseLocks(self, locking.LEVEL_NODE_RES)
9566

    
9567
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
9568
      if self.op.mode == constants.INSTANCE_CREATE:
9569
        if not self.op.no_install:
9570
          pause_sync = (iobj.disk_template in constants.DTS_INT_MIRROR and
9571
                        not self.op.wait_for_sync)
9572
          if pause_sync:
9573
            feedback_fn("* pausing disk sync to install instance OS")
9574
            result = self.rpc.call_blockdev_pause_resume_sync(pnode_name,
9575
                                                              iobj.disks, True)
9576
            for idx, success in enumerate(result.payload):
9577
              if not success:
9578
                logging.warn("pause-sync of instance %s for disk %d failed",
9579
                             instance, idx)
9580

    
9581
          feedback_fn("* running the instance OS create scripts...")
9582
          # FIXME: pass debug option from opcode to backend
9583
          os_add_result = \
9584
            self.rpc.call_instance_os_add(pnode_name, (iobj, None), False,
9585
                                          self.op.debug_level)
9586
          if pause_sync:
9587
            feedback_fn("* resuming disk sync")
9588
            result = self.rpc.call_blockdev_pause_resume_sync(pnode_name,
9589
                                                              iobj.disks, False)
9590
            for idx, success in enumerate(result.payload):
9591
              if not success:
9592
                logging.warn("resume-sync of instance %s for disk %d failed",
9593
                             instance, idx)
9594

    
9595
          os_add_result.Raise("Could not add os for instance %s"
9596
                              " on node %s" % (instance, pnode_name))
9597

    
9598
      elif self.op.mode == constants.INSTANCE_IMPORT:
9599
        feedback_fn("* running the instance OS import scripts...")
9600

    
9601
        transfers = []
9602

    
9603
        for idx, image in enumerate(self.src_images):
9604
          if not image:
9605
            continue
9606

    
9607
          # FIXME: pass debug option from opcode to backend
9608
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
9609
                                             constants.IEIO_FILE, (image, ),
9610
                                             constants.IEIO_SCRIPT,
9611
                                             (iobj.disks[idx], idx),
9612
                                             None)
9613
          transfers.append(dt)
9614

    
9615
        import_result = \
9616
          masterd.instance.TransferInstanceData(self, feedback_fn,
9617
                                                self.op.src_node, pnode_name,
9618
                                                self.pnode.secondary_ip,
9619
                                                iobj, transfers)
9620
        if not compat.all(import_result):
9621
          self.LogWarning("Some disks for instance %s on node %s were not"
9622
                          " imported successfully" % (instance, pnode_name))
9623

    
9624
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
9625
        feedback_fn("* preparing remote import...")
9626
        # The source cluster will stop the instance before attempting to make a
9627
        # connection. In some cases stopping an instance can take a long time,
9628
        # hence the shutdown timeout is added to the connection timeout.
9629
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
9630
                           self.op.source_shutdown_timeout)
9631
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9632

    
9633
        assert iobj.primary_node == self.pnode.name
9634
        disk_results = \
9635
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
9636
                                        self.source_x509_ca,
9637
                                        self._cds, timeouts)
9638
        if not compat.all(disk_results):
9639
          # TODO: Should the instance still be started, even if some disks
9640
          # failed to import (valid for local imports, too)?
9641
          self.LogWarning("Some disks for instance %s on node %s were not"
9642
                          " imported successfully" % (instance, pnode_name))
9643

    
9644
        # Run rename script on newly imported instance
9645
        assert iobj.name == instance
9646
        feedback_fn("Running rename script for %s" % instance)
9647
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
9648
                                                   self.source_instance_name,
9649
                                                   self.op.debug_level)
9650
        if result.fail_msg:
9651
          self.LogWarning("Failed to run rename script for %s on node"
9652
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
9653

    
9654
      else:
9655
        # also checked in the prereq part
9656
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
9657
                                     % self.op.mode)
9658

    
9659
    assert not self.owned_locks(locking.LEVEL_NODE_RES)
9660

    
9661
    if self.op.start:
9662
      iobj.admin_state = constants.ADMINST_UP
9663
      self.cfg.Update(iobj, feedback_fn)
9664
      logging.info("Starting instance %s on node %s", instance, pnode_name)
9665
      feedback_fn("* starting instance...")
9666
      result = self.rpc.call_instance_start(pnode_name, (iobj, None, None),
9667
                                            False)
9668
      result.Raise("Could not start instance")
9669

    
9670
    return list(iobj.all_nodes)
9671

    
9672

    
9673
class LUInstanceConsole(NoHooksLU):
9674
  """Connect to an instance's console.
9675

9676
  This is somewhat special in that it returns the command line that
9677
  you need to run on the master node in order to connect to the
9678
  console.
9679

9680
  """
9681
  REQ_BGL = False
9682

    
9683
  def ExpandNames(self):
9684
    self.share_locks = _ShareAll()
9685
    self._ExpandAndLockInstance()
9686

    
9687
  def CheckPrereq(self):
9688
    """Check prerequisites.
9689

9690
    This checks that the instance is in the cluster.
9691

9692
    """
9693
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9694
    assert self.instance is not None, \
9695
      "Cannot retrieve locked instance %s" % self.op.instance_name
9696
    _CheckNodeOnline(self, self.instance.primary_node)
9697

    
9698
  def Exec(self, feedback_fn):
9699
    """Connect to the console of an instance
9700

9701
    """
9702
    instance = self.instance
9703
    node = instance.primary_node
9704

    
9705
    node_insts = self.rpc.call_instance_list([node],
9706
                                             [instance.hypervisor])[node]
9707
    node_insts.Raise("Can't get node information from %s" % node)
9708

    
9709
    if instance.name not in node_insts.payload:
9710
      if instance.admin_state == constants.ADMINST_UP:
9711
        state = constants.INSTST_ERRORDOWN
9712
      elif instance.admin_state == constants.ADMINST_DOWN:
9713
        state = constants.INSTST_ADMINDOWN
9714
      else:
9715
        state = constants.INSTST_ADMINOFFLINE
9716
      raise errors.OpExecError("Instance %s is not running (state %s)" %
9717
                               (instance.name, state))
9718

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

    
9721
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
9722

    
9723

    
9724
def _GetInstanceConsole(cluster, instance):
9725
  """Returns console information for an instance.
9726

9727
  @type cluster: L{objects.Cluster}
9728
  @type instance: L{objects.Instance}
9729
  @rtype: dict
9730

9731
  """
9732
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
9733
  # beparams and hvparams are passed separately, to avoid editing the
9734
  # instance and then saving the defaults in the instance itself.
9735
  hvparams = cluster.FillHV(instance)
9736
  beparams = cluster.FillBE(instance)
9737
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
9738

    
9739
  assert console.instance == instance.name
9740
  assert console.Validate()
9741

    
9742
  return console.ToDict()
9743

    
9744

    
9745
class LUInstanceReplaceDisks(LogicalUnit):
9746
  """Replace the disks of an instance.
9747

9748
  """
9749
  HPATH = "mirrors-replace"
9750
  HTYPE = constants.HTYPE_INSTANCE
9751
  REQ_BGL = False
9752

    
9753
  def CheckArguments(self):
9754
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
9755
                                  self.op.iallocator)
9756

    
9757
  def ExpandNames(self):
9758
    self._ExpandAndLockInstance()
9759

    
9760
    assert locking.LEVEL_NODE not in self.needed_locks
9761
    assert locking.LEVEL_NODE_RES not in self.needed_locks
9762
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
9763

    
9764
    assert self.op.iallocator is None or self.op.remote_node is None, \
9765
      "Conflicting options"
9766

    
9767
    if self.op.remote_node is not None:
9768
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9769

    
9770
      # Warning: do not remove the locking of the new secondary here
9771
      # unless DRBD8.AddChildren is changed to work in parallel;
9772
      # currently it doesn't since parallel invocations of
9773
      # FindUnusedMinor will conflict
9774
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
9775
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
9776
    else:
9777
      self.needed_locks[locking.LEVEL_NODE] = []
9778
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9779

    
9780
      if self.op.iallocator is not None:
9781
        # iallocator will select a new node in the same group
9782
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
9783

    
9784
    self.needed_locks[locking.LEVEL_NODE_RES] = []
9785

    
9786
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
9787
                                   self.op.iallocator, self.op.remote_node,
9788
                                   self.op.disks, False, self.op.early_release)
9789

    
9790
    self.tasklets = [self.replacer]
9791

    
9792
  def DeclareLocks(self, level):
9793
    if level == locking.LEVEL_NODEGROUP:
9794
      assert self.op.remote_node is None
9795
      assert self.op.iallocator is not None
9796
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
9797

    
9798
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
9799
      # Lock all groups used by instance optimistically; this requires going
9800
      # via the node before it's locked, requiring verification later on
9801
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
9802
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
9803

    
9804
    elif level == locking.LEVEL_NODE:
9805
      if self.op.iallocator is not None:
9806
        assert self.op.remote_node is None
9807
        assert not self.needed_locks[locking.LEVEL_NODE]
9808

    
9809
        # Lock member nodes of all locked groups
9810
        self.needed_locks[locking.LEVEL_NODE] = [node_name
9811
          for group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
9812
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
9813
      else:
9814
        self._LockInstancesNodes()
9815
    elif level == locking.LEVEL_NODE_RES:
9816
      # Reuse node locks
9817
      self.needed_locks[locking.LEVEL_NODE_RES] = \
9818
        self.needed_locks[locking.LEVEL_NODE]
9819

    
9820
  def BuildHooksEnv(self):
9821
    """Build hooks env.
9822

9823
    This runs on the master, the primary and all the secondaries.
9824

9825
    """
9826
    instance = self.replacer.instance
9827
    env = {
9828
      "MODE": self.op.mode,
9829
      "NEW_SECONDARY": self.op.remote_node,
9830
      "OLD_SECONDARY": instance.secondary_nodes[0],
9831
      }
9832
    env.update(_BuildInstanceHookEnvByObject(self, instance))
9833
    return env
9834

    
9835
  def BuildHooksNodes(self):
9836
    """Build hooks nodes.
9837

9838
    """
9839
    instance = self.replacer.instance
9840
    nl = [
9841
      self.cfg.GetMasterNode(),
9842
      instance.primary_node,
9843
      ]
9844
    if self.op.remote_node is not None:
9845
      nl.append(self.op.remote_node)
9846
    return nl, nl
9847

    
9848
  def CheckPrereq(self):
9849
    """Check prerequisites.
9850

9851
    """
9852
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
9853
            self.op.iallocator is None)
9854

    
9855
    # Verify if node group locks are still correct
9856
    owned_groups = self.owned_locks(locking.LEVEL_NODEGROUP)
9857
    if owned_groups:
9858
      _CheckInstanceNodeGroups(self.cfg, self.op.instance_name, owned_groups)
9859

    
9860
    return LogicalUnit.CheckPrereq(self)
9861

    
9862

    
9863
class TLReplaceDisks(Tasklet):
9864
  """Replaces disks for an instance.
9865

9866
  Note: Locking is not within the scope of this class.
9867

9868
  """
9869
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
9870
               disks, delay_iallocator, early_release):
9871
    """Initializes this class.
9872

9873
    """
9874
    Tasklet.__init__(self, lu)
9875

    
9876
    # Parameters
9877
    self.instance_name = instance_name
9878
    self.mode = mode
9879
    self.iallocator_name = iallocator_name
9880
    self.remote_node = remote_node
9881
    self.disks = disks
9882
    self.delay_iallocator = delay_iallocator
9883
    self.early_release = early_release
9884

    
9885
    # Runtime data
9886
    self.instance = None
9887
    self.new_node = None
9888
    self.target_node = None
9889
    self.other_node = None
9890
    self.remote_node_info = None
9891
    self.node_secondary_ip = None
9892

    
9893
  @staticmethod
9894
  def CheckArguments(mode, remote_node, iallocator):
9895
    """Helper function for users of this class.
9896

9897
    """
9898
    # check for valid parameter combination
9899
    if mode == constants.REPLACE_DISK_CHG:
9900
      if remote_node is None and iallocator is None:
9901
        raise errors.OpPrereqError("When changing the secondary either an"
9902
                                   " iallocator script must be used or the"
9903
                                   " new node given", errors.ECODE_INVAL)
9904

    
9905
      if remote_node is not None and iallocator is not None:
9906
        raise errors.OpPrereqError("Give either the iallocator or the new"
9907
                                   " secondary, not both", errors.ECODE_INVAL)
9908

    
9909
    elif remote_node is not None or iallocator is not None:
9910
      # Not replacing the secondary
9911
      raise errors.OpPrereqError("The iallocator and new node options can"
9912
                                 " only be used when changing the"
9913
                                 " secondary node", errors.ECODE_INVAL)
9914

    
9915
  @staticmethod
9916
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
9917
    """Compute a new secondary node using an IAllocator.
9918

9919
    """
9920
    ial = IAllocator(lu.cfg, lu.rpc,
9921
                     mode=constants.IALLOCATOR_MODE_RELOC,
9922
                     name=instance_name,
9923
                     relocate_from=list(relocate_from))
9924

    
9925
    ial.Run(iallocator_name)
9926

    
9927
    if not ial.success:
9928
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
9929
                                 " %s" % (iallocator_name, ial.info),
9930
                                 errors.ECODE_NORES)
9931

    
9932
    if len(ial.result) != ial.required_nodes:
9933
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9934
                                 " of nodes (%s), required %s" %
9935
                                 (iallocator_name,
9936
                                  len(ial.result), ial.required_nodes),
9937
                                 errors.ECODE_FAULT)
9938

    
9939
    remote_node_name = ial.result[0]
9940

    
9941
    lu.LogInfo("Selected new secondary for instance '%s': %s",
9942
               instance_name, remote_node_name)
9943

    
9944
    return remote_node_name
9945

    
9946
  def _FindFaultyDisks(self, node_name):
9947
    """Wrapper for L{_FindFaultyInstanceDisks}.
9948

9949
    """
9950
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9951
                                    node_name, True)
9952

    
9953
  def _CheckDisksActivated(self, instance):
9954
    """Checks if the instance disks are activated.
9955

9956
    @param instance: The instance to check disks
9957
    @return: True if they are activated, False otherwise
9958

9959
    """
9960
    nodes = instance.all_nodes
9961

    
9962
    for idx, dev in enumerate(instance.disks):
9963
      for node in nodes:
9964
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9965
        self.cfg.SetDiskID(dev, node)
9966

    
9967
        result = self.rpc.call_blockdev_find(node, dev)
9968

    
9969
        if result.offline:
9970
          continue
9971
        elif result.fail_msg or not result.payload:
9972
          return False
9973

    
9974
    return True
9975

    
9976
  def CheckPrereq(self):
9977
    """Check prerequisites.
9978

9979
    This checks that the instance is in the cluster.
9980

9981
    """
9982
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9983
    assert instance is not None, \
9984
      "Cannot retrieve locked instance %s" % self.instance_name
9985

    
9986
    if instance.disk_template != constants.DT_DRBD8:
9987
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9988
                                 " instances", errors.ECODE_INVAL)
9989

    
9990
    if len(instance.secondary_nodes) != 1:
9991
      raise errors.OpPrereqError("The instance has a strange layout,"
9992
                                 " expected one secondary but found %d" %
9993
                                 len(instance.secondary_nodes),
9994
                                 errors.ECODE_FAULT)
9995

    
9996
    if not self.delay_iallocator:
9997
      self._CheckPrereq2()
9998

    
9999
  def _CheckPrereq2(self):
10000
    """Check prerequisites, second part.
10001

10002
    This function should always be part of CheckPrereq. It was separated and is
10003
    now called from Exec because during node evacuation iallocator was only
10004
    called with an unmodified cluster model, not taking planned changes into
10005
    account.
10006

10007
    """
10008
    instance = self.instance
10009
    secondary_node = instance.secondary_nodes[0]
10010

    
10011
    if self.iallocator_name is None:
10012
      remote_node = self.remote_node
10013
    else:
10014
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
10015
                                       instance.name, instance.secondary_nodes)
10016

    
10017
    if remote_node is None:
10018
      self.remote_node_info = None
10019
    else:
10020
      assert remote_node in self.lu.owned_locks(locking.LEVEL_NODE), \
10021
             "Remote node '%s' is not locked" % remote_node
10022

    
10023
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
10024
      assert self.remote_node_info is not None, \
10025
        "Cannot retrieve locked node %s" % remote_node
10026

    
10027
    if remote_node == self.instance.primary_node:
10028
      raise errors.OpPrereqError("The specified node is the primary node of"
10029
                                 " the instance", errors.ECODE_INVAL)
10030

    
10031
    if remote_node == secondary_node:
10032
      raise errors.OpPrereqError("The specified node is already the"
10033
                                 " secondary node of the instance",
10034
                                 errors.ECODE_INVAL)
10035

    
10036
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
10037
                                    constants.REPLACE_DISK_CHG):
10038
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
10039
                                 errors.ECODE_INVAL)
10040

    
10041
    if self.mode == constants.REPLACE_DISK_AUTO:
10042
      if not self._CheckDisksActivated(instance):
10043
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
10044
                                   " first" % self.instance_name,
10045
                                   errors.ECODE_STATE)
10046
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
10047
      faulty_secondary = self._FindFaultyDisks(secondary_node)
10048

    
10049
      if faulty_primary and faulty_secondary:
10050
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
10051
                                   " one node and can not be repaired"
10052
                                   " automatically" % self.instance_name,
10053
                                   errors.ECODE_STATE)
10054

    
10055
      if faulty_primary:
10056
        self.disks = faulty_primary
10057
        self.target_node = instance.primary_node
10058
        self.other_node = secondary_node
10059
        check_nodes = [self.target_node, self.other_node]
10060
      elif faulty_secondary:
10061
        self.disks = faulty_secondary
10062
        self.target_node = secondary_node
10063
        self.other_node = instance.primary_node
10064
        check_nodes = [self.target_node, self.other_node]
10065
      else:
10066
        self.disks = []
10067
        check_nodes = []
10068

    
10069
    else:
10070
      # Non-automatic modes
10071
      if self.mode == constants.REPLACE_DISK_PRI:
10072
        self.target_node = instance.primary_node
10073
        self.other_node = secondary_node
10074
        check_nodes = [self.target_node, self.other_node]
10075

    
10076
      elif self.mode == constants.REPLACE_DISK_SEC:
10077
        self.target_node = secondary_node
10078
        self.other_node = instance.primary_node
10079
        check_nodes = [self.target_node, self.other_node]
10080

    
10081
      elif self.mode == constants.REPLACE_DISK_CHG:
10082
        self.new_node = remote_node
10083
        self.other_node = instance.primary_node
10084
        self.target_node = secondary_node
10085
        check_nodes = [self.new_node, self.other_node]
10086

    
10087
        _CheckNodeNotDrained(self.lu, remote_node)
10088
        _CheckNodeVmCapable(self.lu, remote_node)
10089

    
10090
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
10091
        assert old_node_info is not None
10092
        if old_node_info.offline and not self.early_release:
10093
          # doesn't make sense to delay the release
10094
          self.early_release = True
10095
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
10096
                          " early-release mode", secondary_node)
10097

    
10098
      else:
10099
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
10100
                                     self.mode)
10101

    
10102
      # If not specified all disks should be replaced
10103
      if not self.disks:
10104
        self.disks = range(len(self.instance.disks))
10105

    
10106
    # TODO: compute disk parameters
10107
    primary_node_info = self.cfg.GetNodeInfo(instance.primary_node)
10108
    secondary_node_info = self.cfg.GetNodeInfo(secondary_node)
10109
    if primary_node_info.group != secondary_node_info.group:
10110
      self.lu.LogInfo("The instance primary and secondary nodes are in two"
10111
                      " different node groups; the disk parameters of the"
10112
                      " primary node's group will be applied.")
10113

    
10114
    self.diskparams = self.cfg.GetNodeGroup(primary_node_info.group).diskparams
10115

    
10116
    for node in check_nodes:
10117
      _CheckNodeOnline(self.lu, node)
10118

    
10119
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
10120
                                                          self.other_node,
10121
                                                          self.target_node]
10122
                              if node_name is not None)
10123

    
10124
    # Release unneeded node and node resource locks
10125
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
10126
    _ReleaseLocks(self.lu, locking.LEVEL_NODE_RES, keep=touched_nodes)
10127

    
10128
    # Release any owned node group
10129
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
10130
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
10131

    
10132
    # Check whether disks are valid
10133
    for disk_idx in self.disks:
10134
      instance.FindDisk(disk_idx)
10135

    
10136
    # Get secondary node IP addresses
10137
    self.node_secondary_ip = dict((name, node.secondary_ip) for (name, node)
10138
                                  in self.cfg.GetMultiNodeInfo(touched_nodes))
10139

    
10140
  def Exec(self, feedback_fn):
10141
    """Execute disk replacement.
10142

10143
    This dispatches the disk replacement to the appropriate handler.
10144

10145
    """
10146
    if self.delay_iallocator:
10147
      self._CheckPrereq2()
10148

    
10149
    if __debug__:
10150
      # Verify owned locks before starting operation
10151
      owned_nodes = self.lu.owned_locks(locking.LEVEL_NODE)
10152
      assert set(owned_nodes) == set(self.node_secondary_ip), \
10153
          ("Incorrect node locks, owning %s, expected %s" %
10154
           (owned_nodes, self.node_secondary_ip.keys()))
10155
      assert (self.lu.owned_locks(locking.LEVEL_NODE) ==
10156
              self.lu.owned_locks(locking.LEVEL_NODE_RES))
10157

    
10158
      owned_instances = self.lu.owned_locks(locking.LEVEL_INSTANCE)
10159
      assert list(owned_instances) == [self.instance_name], \
10160
          "Instance '%s' not locked" % self.instance_name
10161

    
10162
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
10163
          "Should not own any node group lock at this point"
10164

    
10165
    if not self.disks:
10166
      feedback_fn("No disks need replacement")
10167
      return
10168

    
10169
    feedback_fn("Replacing disk(s) %s for %s" %
10170
                (utils.CommaJoin(self.disks), self.instance.name))
10171

    
10172
    activate_disks = (self.instance.admin_state != constants.ADMINST_UP)
10173

    
10174
    # Activate the instance disks if we're replacing them on a down instance
10175
    if activate_disks:
10176
      _StartInstanceDisks(self.lu, self.instance, True)
10177

    
10178
    try:
10179
      # Should we replace the secondary node?
10180
      if self.new_node is not None:
10181
        fn = self._ExecDrbd8Secondary
10182
      else:
10183
        fn = self._ExecDrbd8DiskOnly
10184

    
10185
      result = fn(feedback_fn)
10186
    finally:
10187
      # Deactivate the instance disks if we're replacing them on a
10188
      # down instance
10189
      if activate_disks:
10190
        _SafeShutdownInstanceDisks(self.lu, self.instance)
10191

    
10192
    assert not self.lu.owned_locks(locking.LEVEL_NODE)
10193

    
10194
    if __debug__:
10195
      # Verify owned locks
10196
      owned_nodes = self.lu.owned_locks(locking.LEVEL_NODE_RES)
10197
      nodes = frozenset(self.node_secondary_ip)
10198
      assert ((self.early_release and not owned_nodes) or
10199
              (not self.early_release and not (set(owned_nodes) - nodes))), \
10200
        ("Not owning the correct locks, early_release=%s, owned=%r,"
10201
         " nodes=%r" % (self.early_release, owned_nodes, nodes))
10202

    
10203
    return result
10204

    
10205
  def _CheckVolumeGroup(self, nodes):
10206
    self.lu.LogInfo("Checking volume groups")
10207

    
10208
    vgname = self.cfg.GetVGName()
10209

    
10210
    # Make sure volume group exists on all involved nodes
10211
    results = self.rpc.call_vg_list(nodes)
10212
    if not results:
10213
      raise errors.OpExecError("Can't list volume groups on the nodes")
10214

    
10215
    for node in nodes:
10216
      res = results[node]
10217
      res.Raise("Error checking node %s" % node)
10218
      if vgname not in res.payload:
10219
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
10220
                                 (vgname, node))
10221

    
10222
  def _CheckDisksExistence(self, nodes):
10223
    # Check disk existence
10224
    for idx, dev in enumerate(self.instance.disks):
10225
      if idx not in self.disks:
10226
        continue
10227

    
10228
      for node in nodes:
10229
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
10230
        self.cfg.SetDiskID(dev, node)
10231

    
10232
        result = self.rpc.call_blockdev_find(node, dev)
10233

    
10234
        msg = result.fail_msg
10235
        if msg or not result.payload:
10236
          if not msg:
10237
            msg = "disk not found"
10238
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
10239
                                   (idx, node, msg))
10240

    
10241
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
10242
    for idx, dev in enumerate(self.instance.disks):
10243
      if idx not in self.disks:
10244
        continue
10245

    
10246
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
10247
                      (idx, node_name))
10248

    
10249
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
10250
                                   ldisk=ldisk):
10251
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
10252
                                 " replace disks for instance %s" %
10253
                                 (node_name, self.instance.name))
10254

    
10255
  def _CreateNewStorage(self, node_name):
10256
    """Create new storage on the primary or secondary node.
10257

10258
    This is only used for same-node replaces, not for changing the
10259
    secondary node, hence we don't want to modify the existing disk.
10260

10261
    """
10262
    iv_names = {}
10263

    
10264
    for idx, dev in enumerate(self.instance.disks):
10265
      if idx not in self.disks:
10266
        continue
10267

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

    
10270
      self.cfg.SetDiskID(dev, node_name)
10271

    
10272
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
10273
      names = _GenerateUniqueNames(self.lu, lv_names)
10274

    
10275
      _, data_p, meta_p = _ComputeLDParams(constants.DT_DRBD8, self.diskparams)
10276

    
10277
      vg_data = dev.children[0].logical_id[0]
10278
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
10279
                             logical_id=(vg_data, names[0]), params=data_p)
10280
      vg_meta = dev.children[1].logical_id[0]
10281
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=DRBD_META_SIZE,
10282
                             logical_id=(vg_meta, names[1]), params=meta_p)
10283

    
10284
      new_lvs = [lv_data, lv_meta]
10285
      old_lvs = [child.Copy() for child in dev.children]
10286
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
10287

    
10288
      # we pass force_create=True to force the LVM creation
10289
      for new_lv in new_lvs:
10290
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
10291
                        _GetInstanceInfoText(self.instance), False)
10292

    
10293
    return iv_names
10294

    
10295
  def _CheckDevices(self, node_name, iv_names):
10296
    for name, (dev, _, _) in iv_names.iteritems():
10297
      self.cfg.SetDiskID(dev, node_name)
10298

    
10299
      result = self.rpc.call_blockdev_find(node_name, dev)
10300

    
10301
      msg = result.fail_msg
10302
      if msg or not result.payload:
10303
        if not msg:
10304
          msg = "disk not found"
10305
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
10306
                                 (name, msg))
10307

    
10308
      if result.payload.is_degraded:
10309
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
10310

    
10311
  def _RemoveOldStorage(self, node_name, iv_names):
10312
    for name, (_, old_lvs, _) in iv_names.iteritems():
10313
      self.lu.LogInfo("Remove logical volumes for %s" % name)
10314

    
10315
      for lv in old_lvs:
10316
        self.cfg.SetDiskID(lv, node_name)
10317

    
10318
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
10319
        if msg:
10320
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
10321
                             hint="remove unused LVs manually")
10322

    
10323
  def _ExecDrbd8DiskOnly(self, feedback_fn): # pylint: disable=W0613
10324
    """Replace a disk on the primary or secondary for DRBD 8.
10325

10326
    The algorithm for replace is quite complicated:
10327

10328
      1. for each disk to be replaced:
10329

10330
        1. create new LVs on the target node with unique names
10331
        1. detach old LVs from the drbd device
10332
        1. rename old LVs to name_replaced.<time_t>
10333
        1. rename new LVs to old LVs
10334
        1. attach the new LVs (with the old names now) to the drbd device
10335

10336
      1. wait for sync across all devices
10337

10338
      1. for each modified disk:
10339

10340
        1. remove old LVs (which have the name name_replaces.<time_t>)
10341

10342
    Failures are not very well handled.
10343

10344
    """
10345
    steps_total = 6
10346

    
10347
    # Step: check device activation
10348
    self.lu.LogStep(1, steps_total, "Check device existence")
10349
    self._CheckDisksExistence([self.other_node, self.target_node])
10350
    self._CheckVolumeGroup([self.target_node, self.other_node])
10351

    
10352
    # Step: check other node consistency
10353
    self.lu.LogStep(2, steps_total, "Check peer consistency")
10354
    self._CheckDisksConsistency(self.other_node,
10355
                                self.other_node == self.instance.primary_node,
10356
                                False)
10357

    
10358
    # Step: create new storage
10359
    self.lu.LogStep(3, steps_total, "Allocate new storage")
10360
    iv_names = self._CreateNewStorage(self.target_node)
10361

    
10362
    # Step: for each lv, detach+rename*2+attach
10363
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
10364
    for dev, old_lvs, new_lvs in iv_names.itervalues():
10365
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
10366

    
10367
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
10368
                                                     old_lvs)
10369
      result.Raise("Can't detach drbd from local storage on node"
10370
                   " %s for device %s" % (self.target_node, dev.iv_name))
10371
      #dev.children = []
10372
      #cfg.Update(instance)
10373

    
10374
      # ok, we created the new LVs, so now we know we have the needed
10375
      # storage; as such, we proceed on the target node to rename
10376
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
10377
      # using the assumption that logical_id == physical_id (which in
10378
      # turn is the unique_id on that node)
10379

    
10380
      # FIXME(iustin): use a better name for the replaced LVs
10381
      temp_suffix = int(time.time())
10382
      ren_fn = lambda d, suff: (d.physical_id[0],
10383
                                d.physical_id[1] + "_replaced-%s" % suff)
10384

    
10385
      # Build the rename list based on what LVs exist on the node
10386
      rename_old_to_new = []
10387
      for to_ren in old_lvs:
10388
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
10389
        if not result.fail_msg and result.payload:
10390
          # device exists
10391
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
10392

    
10393
      self.lu.LogInfo("Renaming the old LVs on the target node")
10394
      result = self.rpc.call_blockdev_rename(self.target_node,
10395
                                             rename_old_to_new)
10396
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
10397

    
10398
      # Now we rename the new LVs to the old LVs
10399
      self.lu.LogInfo("Renaming the new LVs on the target node")
10400
      rename_new_to_old = [(new, old.physical_id)
10401
                           for old, new in zip(old_lvs, new_lvs)]
10402
      result = self.rpc.call_blockdev_rename(self.target_node,
10403
                                             rename_new_to_old)
10404
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
10405

    
10406
      # Intermediate steps of in memory modifications
10407
      for old, new in zip(old_lvs, new_lvs):
10408
        new.logical_id = old.logical_id
10409
        self.cfg.SetDiskID(new, self.target_node)
10410

    
10411
      # We need to modify old_lvs so that removal later removes the
10412
      # right LVs, not the newly added ones; note that old_lvs is a
10413
      # copy here
10414
      for disk in old_lvs:
10415
        disk.logical_id = ren_fn(disk, temp_suffix)
10416
        self.cfg.SetDiskID(disk, self.target_node)
10417

    
10418
      # Now that the new lvs have the old name, we can add them to the device
10419
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
10420
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
10421
                                                  new_lvs)
10422
      msg = result.fail_msg
10423
      if msg:
10424
        for new_lv in new_lvs:
10425
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
10426
                                               new_lv).fail_msg
10427
          if msg2:
10428
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
10429
                               hint=("cleanup manually the unused logical"
10430
                                     "volumes"))
10431
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
10432

    
10433
    cstep = itertools.count(5)
10434

    
10435
    if self.early_release:
10436
      self.lu.LogStep(cstep.next(), steps_total, "Removing old storage")
10437
      self._RemoveOldStorage(self.target_node, iv_names)
10438
      # TODO: Check if releasing locks early still makes sense
10439
      _ReleaseLocks(self.lu, locking.LEVEL_NODE_RES)
10440
    else:
10441
      # Release all resource locks except those used by the instance
10442
      _ReleaseLocks(self.lu, locking.LEVEL_NODE_RES,
10443
                    keep=self.node_secondary_ip.keys())
10444

    
10445
    # Release all node locks while waiting for sync
10446
    _ReleaseLocks(self.lu, locking.LEVEL_NODE)
10447

    
10448
    # TODO: Can the instance lock be downgraded here? Take the optional disk
10449
    # shutdown in the caller into consideration.
10450

    
10451
    # Wait for sync
10452
    # This can fail as the old devices are degraded and _WaitForSync
10453
    # does a combined result over all disks, so we don't check its return value
10454
    self.lu.LogStep(cstep.next(), steps_total, "Sync devices")
10455
    _WaitForSync(self.lu, self.instance)
10456

    
10457
    # Check all devices manually
10458
    self._CheckDevices(self.instance.primary_node, iv_names)
10459

    
10460
    # Step: remove old storage
10461
    if not self.early_release:
10462
      self.lu.LogStep(cstep.next(), steps_total, "Removing old storage")
10463
      self._RemoveOldStorage(self.target_node, iv_names)
10464

    
10465
  def _ExecDrbd8Secondary(self, feedback_fn):
10466
    """Replace the secondary node for DRBD 8.
10467

10468
    The algorithm for replace is quite complicated:
10469
      - for all disks of the instance:
10470
        - create new LVs on the new node with same names
10471
        - shutdown the drbd device on the old secondary
10472
        - disconnect the drbd network on the primary
10473
        - create the drbd device on the new secondary
10474
        - network attach the drbd on the primary, using an artifice:
10475
          the drbd code for Attach() will connect to the network if it
10476
          finds a device which is connected to the good local disks but
10477
          not network enabled
10478
      - wait for sync across all devices
10479
      - remove all disks from the old secondary
10480

10481
    Failures are not very well handled.
10482

10483
    """
10484
    steps_total = 6
10485

    
10486
    pnode = self.instance.primary_node
10487

    
10488
    # Step: check device activation
10489
    self.lu.LogStep(1, steps_total, "Check device existence")
10490
    self._CheckDisksExistence([self.instance.primary_node])
10491
    self._CheckVolumeGroup([self.instance.primary_node])
10492

    
10493
    # Step: check other node consistency
10494
    self.lu.LogStep(2, steps_total, "Check peer consistency")
10495
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
10496

    
10497
    # Step: create new storage
10498
    self.lu.LogStep(3, steps_total, "Allocate new storage")
10499
    for idx, dev in enumerate(self.instance.disks):
10500
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
10501
                      (self.new_node, idx))
10502
      # we pass force_create=True to force LVM creation
10503
      for new_lv in dev.children:
10504
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
10505
                        _GetInstanceInfoText(self.instance), False)
10506

    
10507
    # Step 4: dbrd minors and drbd setups changes
10508
    # after this, we must manually remove the drbd minors on both the
10509
    # error and the success paths
10510
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
10511
    minors = self.cfg.AllocateDRBDMinor([self.new_node
10512
                                         for dev in self.instance.disks],
10513
                                        self.instance.name)
10514
    logging.debug("Allocated minors %r", minors)
10515

    
10516
    iv_names = {}
10517
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
10518
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
10519
                      (self.new_node, idx))
10520
      # create new devices on new_node; note that we create two IDs:
10521
      # one without port, so the drbd will be activated without
10522
      # networking information on the new node at this stage, and one
10523
      # with network, for the latter activation in step 4
10524
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
10525
      if self.instance.primary_node == o_node1:
10526
        p_minor = o_minor1
10527
      else:
10528
        assert self.instance.primary_node == o_node2, "Three-node instance?"
10529
        p_minor = o_minor2
10530

    
10531
      new_alone_id = (self.instance.primary_node, self.new_node, None,
10532
                      p_minor, new_minor, o_secret)
10533
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
10534
                    p_minor, new_minor, o_secret)
10535

    
10536
      iv_names[idx] = (dev, dev.children, new_net_id)
10537
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
10538
                    new_net_id)
10539
      drbd_params, _, _ = _ComputeLDParams(constants.DT_DRBD8, self.diskparams)
10540
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
10541
                              logical_id=new_alone_id,
10542
                              children=dev.children,
10543
                              size=dev.size,
10544
                              params=drbd_params)
10545
      try:
10546
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
10547
                              _GetInstanceInfoText(self.instance), False)
10548
      except errors.GenericError:
10549
        self.cfg.ReleaseDRBDMinors(self.instance.name)
10550
        raise
10551

    
10552
    # We have new devices, shutdown the drbd on the old secondary
10553
    for idx, dev in enumerate(self.instance.disks):
10554
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
10555
      self.cfg.SetDiskID(dev, self.target_node)
10556
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
10557
      if msg:
10558
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
10559
                           "node: %s" % (idx, msg),
10560
                           hint=("Please cleanup this device manually as"
10561
                                 " soon as possible"))
10562

    
10563
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
10564
    result = self.rpc.call_drbd_disconnect_net([pnode], self.node_secondary_ip,
10565
                                               self.instance.disks)[pnode]
10566

    
10567
    msg = result.fail_msg
10568
    if msg:
10569
      # detaches didn't succeed (unlikely)
10570
      self.cfg.ReleaseDRBDMinors(self.instance.name)
10571
      raise errors.OpExecError("Can't detach the disks from the network on"
10572
                               " old node: %s" % (msg,))
10573

    
10574
    # if we managed to detach at least one, we update all the disks of
10575
    # the instance to point to the new secondary
10576
    self.lu.LogInfo("Updating instance configuration")
10577
    for dev, _, new_logical_id in iv_names.itervalues():
10578
      dev.logical_id = new_logical_id
10579
      self.cfg.SetDiskID(dev, self.instance.primary_node)
10580

    
10581
    self.cfg.Update(self.instance, feedback_fn)
10582

    
10583
    # Release all node locks (the configuration has been updated)
10584
    _ReleaseLocks(self.lu, locking.LEVEL_NODE)
10585

    
10586
    # and now perform the drbd attach
10587
    self.lu.LogInfo("Attaching primary drbds to new secondary"
10588
                    " (standalone => connected)")
10589
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
10590
                                            self.new_node],
10591
                                           self.node_secondary_ip,
10592
                                           self.instance.disks,
10593
                                           self.instance.name,
10594
                                           False)
10595
    for to_node, to_result in result.items():
10596
      msg = to_result.fail_msg
10597
      if msg:
10598
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
10599
                           to_node, msg,
10600
                           hint=("please do a gnt-instance info to see the"
10601
                                 " status of disks"))
10602

    
10603
    cstep = itertools.count(5)
10604

    
10605
    if self.early_release:
10606
      self.lu.LogStep(cstep.next(), steps_total, "Removing old storage")
10607
      self._RemoveOldStorage(self.target_node, iv_names)
10608
      # TODO: Check if releasing locks early still makes sense
10609
      _ReleaseLocks(self.lu, locking.LEVEL_NODE_RES)
10610
    else:
10611
      # Release all resource locks except those used by the instance
10612
      _ReleaseLocks(self.lu, locking.LEVEL_NODE_RES,
10613
                    keep=self.node_secondary_ip.keys())
10614

    
10615
    # TODO: Can the instance lock be downgraded here? Take the optional disk
10616
    # shutdown in the caller into consideration.
10617

    
10618
    # Wait for sync
10619
    # This can fail as the old devices are degraded and _WaitForSync
10620
    # does a combined result over all disks, so we don't check its return value
10621
    self.lu.LogStep(cstep.next(), steps_total, "Sync devices")
10622
    _WaitForSync(self.lu, self.instance)
10623

    
10624
    # Check all devices manually
10625
    self._CheckDevices(self.instance.primary_node, iv_names)
10626

    
10627
    # Step: remove old storage
10628
    if not self.early_release:
10629
      self.lu.LogStep(cstep.next(), steps_total, "Removing old storage")
10630
      self._RemoveOldStorage(self.target_node, iv_names)
10631

    
10632

    
10633
class LURepairNodeStorage(NoHooksLU):
10634
  """Repairs the volume group on a node.
10635

10636
  """
10637
  REQ_BGL = False
10638

    
10639
  def CheckArguments(self):
10640
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
10641

    
10642
    storage_type = self.op.storage_type
10643

    
10644
    if (constants.SO_FIX_CONSISTENCY not in
10645
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
10646
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
10647
                                 " repaired" % storage_type,
10648
                                 errors.ECODE_INVAL)
10649

    
10650
  def ExpandNames(self):
10651
    self.needed_locks = {
10652
      locking.LEVEL_NODE: [self.op.node_name],
10653
      }
10654

    
10655
  def _CheckFaultyDisks(self, instance, node_name):
10656
    """Ensure faulty disks abort the opcode or at least warn."""
10657
    try:
10658
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
10659
                                  node_name, True):
10660
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
10661
                                   " node '%s'" % (instance.name, node_name),
10662
                                   errors.ECODE_STATE)
10663
    except errors.OpPrereqError, err:
10664
      if self.op.ignore_consistency:
10665
        self.proc.LogWarning(str(err.args[0]))
10666
      else:
10667
        raise
10668

    
10669
  def CheckPrereq(self):
10670
    """Check prerequisites.
10671

10672
    """
10673
    # Check whether any instance on this node has faulty disks
10674
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
10675
      if inst.admin_state != constants.ADMINST_UP:
10676
        continue
10677
      check_nodes = set(inst.all_nodes)
10678
      check_nodes.discard(self.op.node_name)
10679
      for inst_node_name in check_nodes:
10680
        self._CheckFaultyDisks(inst, inst_node_name)
10681

    
10682
  def Exec(self, feedback_fn):
10683
    feedback_fn("Repairing storage unit '%s' on %s ..." %
10684
                (self.op.name, self.op.node_name))
10685

    
10686
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
10687
    result = self.rpc.call_storage_execute(self.op.node_name,
10688
                                           self.op.storage_type, st_args,
10689
                                           self.op.name,
10690
                                           constants.SO_FIX_CONSISTENCY)
10691
    result.Raise("Failed to repair storage unit '%s' on %s" %
10692
                 (self.op.name, self.op.node_name))
10693

    
10694

    
10695
class LUNodeEvacuate(NoHooksLU):
10696
  """Evacuates instances off a list of nodes.
10697

10698
  """
10699
  REQ_BGL = False
10700

    
10701
  _MODE2IALLOCATOR = {
10702
    constants.NODE_EVAC_PRI: constants.IALLOCATOR_NEVAC_PRI,
10703
    constants.NODE_EVAC_SEC: constants.IALLOCATOR_NEVAC_SEC,
10704
    constants.NODE_EVAC_ALL: constants.IALLOCATOR_NEVAC_ALL,
10705
    }
10706
  assert frozenset(_MODE2IALLOCATOR.keys()) == constants.NODE_EVAC_MODES
10707
  assert (frozenset(_MODE2IALLOCATOR.values()) ==
10708
          constants.IALLOCATOR_NEVAC_MODES)
10709

    
10710
  def CheckArguments(self):
10711
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
10712

    
10713
  def ExpandNames(self):
10714
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
10715

    
10716
    if self.op.remote_node is not None:
10717
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10718
      assert self.op.remote_node
10719

    
10720
      if self.op.remote_node == self.op.node_name:
10721
        raise errors.OpPrereqError("Can not use evacuated node as a new"
10722
                                   " secondary node", errors.ECODE_INVAL)
10723

    
10724
      if self.op.mode != constants.NODE_EVAC_SEC:
10725
        raise errors.OpPrereqError("Without the use of an iallocator only"
10726
                                   " secondary instances can be evacuated",
10727
                                   errors.ECODE_INVAL)
10728

    
10729
    # Declare locks
10730
    self.share_locks = _ShareAll()
10731
    self.needed_locks = {
10732
      locking.LEVEL_INSTANCE: [],
10733
      locking.LEVEL_NODEGROUP: [],
10734
      locking.LEVEL_NODE: [],
10735
      }
10736

    
10737
    # Determine nodes (via group) optimistically, needs verification once locks
10738
    # have been acquired
10739
    self.lock_nodes = self._DetermineNodes()
10740

    
10741
  def _DetermineNodes(self):
10742
    """Gets the list of nodes to operate on.
10743

10744
    """
10745
    if self.op.remote_node is None:
10746
      # Iallocator will choose any node(s) in the same group
10747
      group_nodes = self.cfg.GetNodeGroupMembersByNodes([self.op.node_name])
10748
    else:
10749
      group_nodes = frozenset([self.op.remote_node])
10750

    
10751
    # Determine nodes to be locked
10752
    return set([self.op.node_name]) | group_nodes
10753

    
10754
  def _DetermineInstances(self):
10755
    """Builds list of instances to operate on.
10756

10757
    """
10758
    assert self.op.mode in constants.NODE_EVAC_MODES
10759

    
10760
    if self.op.mode == constants.NODE_EVAC_PRI:
10761
      # Primary instances only
10762
      inst_fn = _GetNodePrimaryInstances
10763
      assert self.op.remote_node is None, \
10764
        "Evacuating primary instances requires iallocator"
10765
    elif self.op.mode == constants.NODE_EVAC_SEC:
10766
      # Secondary instances only
10767
      inst_fn = _GetNodeSecondaryInstances
10768
    else:
10769
      # All instances
10770
      assert self.op.mode == constants.NODE_EVAC_ALL
10771
      inst_fn = _GetNodeInstances
10772
      # TODO: In 2.6, change the iallocator interface to take an evacuation mode
10773
      # per instance
10774
      raise errors.OpPrereqError("Due to an issue with the iallocator"
10775
                                 " interface it is not possible to evacuate"
10776
                                 " all instances at once; specify explicitly"
10777
                                 " whether to evacuate primary or secondary"
10778
                                 " instances",
10779
                                 errors.ECODE_INVAL)
10780

    
10781
    return inst_fn(self.cfg, self.op.node_name)
10782

    
10783
  def DeclareLocks(self, level):
10784
    if level == locking.LEVEL_INSTANCE:
10785
      # Lock instances optimistically, needs verification once node and group
10786
      # locks have been acquired
10787
      self.needed_locks[locking.LEVEL_INSTANCE] = \
10788
        set(i.name for i in self._DetermineInstances())
10789

    
10790
    elif level == locking.LEVEL_NODEGROUP:
10791
      # Lock node groups for all potential target nodes optimistically, needs
10792
      # verification once nodes have been acquired
10793
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
10794
        self.cfg.GetNodeGroupsFromNodes(self.lock_nodes)
10795

    
10796
    elif level == locking.LEVEL_NODE:
10797
      self.needed_locks[locking.LEVEL_NODE] = self.lock_nodes
10798

    
10799
  def CheckPrereq(self):
10800
    # Verify locks
10801
    owned_instances = self.owned_locks(locking.LEVEL_INSTANCE)
10802
    owned_nodes = self.owned_locks(locking.LEVEL_NODE)
10803
    owned_groups = self.owned_locks(locking.LEVEL_NODEGROUP)
10804

    
10805
    need_nodes = self._DetermineNodes()
10806

    
10807
    if not owned_nodes.issuperset(need_nodes):
10808
      raise errors.OpPrereqError("Nodes in same group as '%s' changed since"
10809
                                 " locks were acquired, current nodes are"
10810
                                 " are '%s', used to be '%s'; retry the"
10811
                                 " operation" %
10812
                                 (self.op.node_name,
10813
                                  utils.CommaJoin(need_nodes),
10814
                                  utils.CommaJoin(owned_nodes)),
10815
                                 errors.ECODE_STATE)
10816

    
10817
    wanted_groups = self.cfg.GetNodeGroupsFromNodes(owned_nodes)
10818
    if owned_groups != wanted_groups:
10819
      raise errors.OpExecError("Node groups changed since locks were acquired,"
10820
                               " current groups are '%s', used to be '%s';"
10821
                               " retry the operation" %
10822
                               (utils.CommaJoin(wanted_groups),
10823
                                utils.CommaJoin(owned_groups)))
10824

    
10825
    # Determine affected instances
10826
    self.instances = self._DetermineInstances()
10827
    self.instance_names = [i.name for i in self.instances]
10828

    
10829
    if set(self.instance_names) != owned_instances:
10830
      raise errors.OpExecError("Instances on node '%s' changed since locks"
10831
                               " were acquired, current instances are '%s',"
10832
                               " used to be '%s'; retry the operation" %
10833
                               (self.op.node_name,
10834
                                utils.CommaJoin(self.instance_names),
10835
                                utils.CommaJoin(owned_instances)))
10836

    
10837
    if self.instance_names:
10838
      self.LogInfo("Evacuating instances from node '%s': %s",
10839
                   self.op.node_name,
10840
                   utils.CommaJoin(utils.NiceSort(self.instance_names)))
10841
    else:
10842
      self.LogInfo("No instances to evacuate from node '%s'",
10843
                   self.op.node_name)
10844

    
10845
    if self.op.remote_node is not None:
10846
      for i in self.instances:
10847
        if i.primary_node == self.op.remote_node:
10848
          raise errors.OpPrereqError("Node %s is the primary node of"
10849
                                     " instance %s, cannot use it as"
10850
                                     " secondary" %
10851
                                     (self.op.remote_node, i.name),
10852
                                     errors.ECODE_INVAL)
10853

    
10854
  def Exec(self, feedback_fn):
10855
    assert (self.op.iallocator is not None) ^ (self.op.remote_node is not None)
10856

    
10857
    if not self.instance_names:
10858
      # No instances to evacuate
10859
      jobs = []
10860

    
10861
    elif self.op.iallocator is not None:
10862
      # TODO: Implement relocation to other group
10863
      ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_NODE_EVAC,
10864
                       evac_mode=self._MODE2IALLOCATOR[self.op.mode],
10865
                       instances=list(self.instance_names))
10866

    
10867
      ial.Run(self.op.iallocator)
10868

    
10869
      if not ial.success:
10870
        raise errors.OpPrereqError("Can't compute node evacuation using"
10871
                                   " iallocator '%s': %s" %
10872
                                   (self.op.iallocator, ial.info),
10873
                                   errors.ECODE_NORES)
10874

    
10875
      jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, True)
10876

    
10877
    elif self.op.remote_node is not None:
10878
      assert self.op.mode == constants.NODE_EVAC_SEC
10879
      jobs = [
10880
        [opcodes.OpInstanceReplaceDisks(instance_name=instance_name,
10881
                                        remote_node=self.op.remote_node,
10882
                                        disks=[],
10883
                                        mode=constants.REPLACE_DISK_CHG,
10884
                                        early_release=self.op.early_release)]
10885
        for instance_name in self.instance_names
10886
        ]
10887

    
10888
    else:
10889
      raise errors.ProgrammerError("No iallocator or remote node")
10890

    
10891
    return ResultWithJobs(jobs)
10892

    
10893

    
10894
def _SetOpEarlyRelease(early_release, op):
10895
  """Sets C{early_release} flag on opcodes if available.
10896

10897
  """
10898
  try:
10899
    op.early_release = early_release
10900
  except AttributeError:
10901
    assert not isinstance(op, opcodes.OpInstanceReplaceDisks)
10902

    
10903
  return op
10904

    
10905

    
10906
def _NodeEvacDest(use_nodes, group, nodes):
10907
  """Returns group or nodes depending on caller's choice.
10908

10909
  """
10910
  if use_nodes:
10911
    return utils.CommaJoin(nodes)
10912
  else:
10913
    return group
10914

    
10915

    
10916
def _LoadNodeEvacResult(lu, alloc_result, early_release, use_nodes):
10917
  """Unpacks the result of change-group and node-evacuate iallocator requests.
10918

10919
  Iallocator modes L{constants.IALLOCATOR_MODE_NODE_EVAC} and
10920
  L{constants.IALLOCATOR_MODE_CHG_GROUP}.
10921

10922
  @type lu: L{LogicalUnit}
10923
  @param lu: Logical unit instance
10924
  @type alloc_result: tuple/list
10925
  @param alloc_result: Result from iallocator
10926
  @type early_release: bool
10927
  @param early_release: Whether to release locks early if possible
10928
  @type use_nodes: bool
10929
  @param use_nodes: Whether to display node names instead of groups
10930

10931
  """
10932
  (moved, failed, jobs) = alloc_result
10933

    
10934
  if failed:
10935
    failreason = utils.CommaJoin("%s (%s)" % (name, reason)
10936
                                 for (name, reason) in failed)
10937
    lu.LogWarning("Unable to evacuate instances %s", failreason)
10938
    raise errors.OpExecError("Unable to evacuate instances %s" % failreason)
10939

    
10940
  if moved:
10941
    lu.LogInfo("Instances to be moved: %s",
10942
               utils.CommaJoin("%s (to %s)" %
10943
                               (name, _NodeEvacDest(use_nodes, group, nodes))
10944
                               for (name, group, nodes) in moved))
10945

    
10946
  return [map(compat.partial(_SetOpEarlyRelease, early_release),
10947
              map(opcodes.OpCode.LoadOpCode, ops))
10948
          for ops in jobs]
10949

    
10950

    
10951
class LUInstanceGrowDisk(LogicalUnit):
10952
  """Grow a disk of an instance.
10953

10954
  """
10955
  HPATH = "disk-grow"
10956
  HTYPE = constants.HTYPE_INSTANCE
10957
  REQ_BGL = False
10958

    
10959
  def ExpandNames(self):
10960
    self._ExpandAndLockInstance()
10961
    self.needed_locks[locking.LEVEL_NODE] = []
10962
    self.needed_locks[locking.LEVEL_NODE_RES] = []
10963
    self.recalculate_locks[locking.LEVEL_NODE_RES] = constants.LOCKS_REPLACE
10964

    
10965
  def DeclareLocks(self, level):
10966
    if level == locking.LEVEL_NODE:
10967
      self._LockInstancesNodes()
10968
    elif level == locking.LEVEL_NODE_RES:
10969
      # Copy node locks
10970
      self.needed_locks[locking.LEVEL_NODE_RES] = \
10971
        self.needed_locks[locking.LEVEL_NODE][:]
10972

    
10973
  def BuildHooksEnv(self):
10974
    """Build hooks env.
10975

10976
    This runs on the master, the primary and all the secondaries.
10977

10978
    """
10979
    env = {
10980
      "DISK": self.op.disk,
10981
      "AMOUNT": self.op.amount,
10982
      }
10983
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10984
    return env
10985

    
10986
  def BuildHooksNodes(self):
10987
    """Build hooks nodes.
10988

10989
    """
10990
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10991
    return (nl, nl)
10992

    
10993
  def CheckPrereq(self):
10994
    """Check prerequisites.
10995

10996
    This checks that the instance is in the cluster.
10997

10998
    """
10999
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
11000
    assert instance is not None, \
11001
      "Cannot retrieve locked instance %s" % self.op.instance_name
11002
    nodenames = list(instance.all_nodes)
11003
    for node in nodenames:
11004
      _CheckNodeOnline(self, node)
11005

    
11006
    self.instance = instance
11007

    
11008
    if instance.disk_template not in constants.DTS_GROWABLE:
11009
      raise errors.OpPrereqError("Instance's disk layout does not support"
11010
                                 " growing", errors.ECODE_INVAL)
11011

    
11012
    self.disk = instance.FindDisk(self.op.disk)
11013

    
11014
    if instance.disk_template not in (constants.DT_FILE,
11015
                                      constants.DT_SHARED_FILE):
11016
      # TODO: check the free disk space for file, when that feature will be
11017
      # supported
11018
      _CheckNodesFreeDiskPerVG(self, nodenames,
11019
                               self.disk.ComputeGrowth(self.op.amount))
11020

    
11021
  def Exec(self, feedback_fn):
11022
    """Execute disk grow.
11023

11024
    """
11025
    instance = self.instance
11026
    disk = self.disk
11027

    
11028
    assert set([instance.name]) == self.owned_locks(locking.LEVEL_INSTANCE)
11029
    assert (self.owned_locks(locking.LEVEL_NODE) ==
11030
            self.owned_locks(locking.LEVEL_NODE_RES))
11031

    
11032
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
11033
    if not disks_ok:
11034
      raise errors.OpExecError("Cannot activate block device to grow")
11035

    
11036
    feedback_fn("Growing disk %s of instance '%s' by %s" %
11037
                (self.op.disk, instance.name,
11038
                 utils.FormatUnit(self.op.amount, "h")))
11039

    
11040
    # First run all grow ops in dry-run mode
11041
    for node in instance.all_nodes:
11042
      self.cfg.SetDiskID(disk, node)
11043
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
11044
      result.Raise("Grow request failed to node %s" % node)
11045

    
11046
    # We know that (as far as we can test) operations across different
11047
    # nodes will succeed, time to run it for real
11048
    for node in instance.all_nodes:
11049
      self.cfg.SetDiskID(disk, node)
11050
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
11051
      result.Raise("Grow request failed to node %s" % node)
11052

    
11053
      # TODO: Rewrite code to work properly
11054
      # DRBD goes into sync mode for a short amount of time after executing the
11055
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
11056
      # calling "resize" in sync mode fails. Sleeping for a short amount of
11057
      # time is a work-around.
11058
      time.sleep(5)
11059

    
11060
    disk.RecordGrow(self.op.amount)
11061
    self.cfg.Update(instance, feedback_fn)
11062

    
11063
    # Changes have been recorded, release node lock
11064
    _ReleaseLocks(self, locking.LEVEL_NODE)
11065

    
11066
    # Downgrade lock while waiting for sync
11067
    self.glm.downgrade(locking.LEVEL_INSTANCE)
11068

    
11069
    if self.op.wait_for_sync:
11070
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
11071
      if disk_abort:
11072
        self.proc.LogWarning("Disk sync-ing has not returned a good"
11073
                             " status; please check the instance")
11074
      if instance.admin_state != constants.ADMINST_UP:
11075
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
11076
    elif instance.admin_state != constants.ADMINST_UP:
11077
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
11078
                           " not supposed to be running because no wait for"
11079
                           " sync mode was requested")
11080

    
11081
    assert self.owned_locks(locking.LEVEL_NODE_RES)
11082
    assert set([instance.name]) == self.owned_locks(locking.LEVEL_INSTANCE)
11083

    
11084

    
11085
class LUInstanceQueryData(NoHooksLU):
11086
  """Query runtime instance data.
11087

11088
  """
11089
  REQ_BGL = False
11090

    
11091
  def ExpandNames(self):
11092
    self.needed_locks = {}
11093

    
11094
    # Use locking if requested or when non-static information is wanted
11095
    if not (self.op.static or self.op.use_locking):
11096
      self.LogWarning("Non-static data requested, locks need to be acquired")
11097
      self.op.use_locking = True
11098

    
11099
    if self.op.instances or not self.op.use_locking:
11100
      # Expand instance names right here
11101
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
11102
    else:
11103
      # Will use acquired locks
11104
      self.wanted_names = None
11105

    
11106
    if self.op.use_locking:
11107
      self.share_locks = _ShareAll()
11108

    
11109
      if self.wanted_names is None:
11110
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
11111
      else:
11112
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
11113

    
11114
      self.needed_locks[locking.LEVEL_NODE] = []
11115
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
11116

    
11117
  def DeclareLocks(self, level):
11118
    if self.op.use_locking and level == locking.LEVEL_NODE:
11119
      self._LockInstancesNodes()
11120

    
11121
  def CheckPrereq(self):
11122
    """Check prerequisites.
11123

11124
    This only checks the optional instance list against the existing names.
11125

11126
    """
11127
    if self.wanted_names is None:
11128
      assert self.op.use_locking, "Locking was not used"
11129
      self.wanted_names = self.owned_locks(locking.LEVEL_INSTANCE)
11130

    
11131
    self.wanted_instances = \
11132
        map(compat.snd, self.cfg.GetMultiInstanceInfo(self.wanted_names))
11133

    
11134
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
11135
    """Returns the status of a block device
11136

11137
    """
11138
    if self.op.static or not node:
11139
      return None
11140

    
11141
    self.cfg.SetDiskID(dev, node)
11142

    
11143
    result = self.rpc.call_blockdev_find(node, dev)
11144
    if result.offline:
11145
      return None
11146

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

    
11149
    status = result.payload
11150
    if status is None:
11151
      return None
11152

    
11153
    return (status.dev_path, status.major, status.minor,
11154
            status.sync_percent, status.estimated_time,
11155
            status.is_degraded, status.ldisk_status)
11156

    
11157
  def _ComputeDiskStatus(self, instance, snode, dev):
11158
    """Compute block device status.
11159

11160
    """
11161
    if dev.dev_type in constants.LDS_DRBD:
11162
      # we change the snode then (otherwise we use the one passed in)
11163
      if dev.logical_id[0] == instance.primary_node:
11164
        snode = dev.logical_id[1]
11165
      else:
11166
        snode = dev.logical_id[0]
11167

    
11168
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
11169
                                              instance.name, dev)
11170
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
11171

    
11172
    if dev.children:
11173
      dev_children = map(compat.partial(self._ComputeDiskStatus,
11174
                                        instance, snode),
11175
                         dev.children)
11176
    else:
11177
      dev_children = []
11178

    
11179
    return {
11180
      "iv_name": dev.iv_name,
11181
      "dev_type": dev.dev_type,
11182
      "logical_id": dev.logical_id,
11183
      "physical_id": dev.physical_id,
11184
      "pstatus": dev_pstatus,
11185
      "sstatus": dev_sstatus,
11186
      "children": dev_children,
11187
      "mode": dev.mode,
11188
      "size": dev.size,
11189
      }
11190

    
11191
  def Exec(self, feedback_fn):
11192
    """Gather and return data"""
11193
    result = {}
11194

    
11195
    cluster = self.cfg.GetClusterInfo()
11196

    
11197
    pri_nodes = self.cfg.GetMultiNodeInfo(i.primary_node
11198
                                          for i in self.wanted_instances)
11199
    for instance, (_, pnode) in zip(self.wanted_instances, pri_nodes):
11200
      if self.op.static or pnode.offline:
11201
        remote_state = None
11202
        if pnode.offline:
11203
          self.LogWarning("Primary node %s is marked offline, returning static"
11204
                          " information only for instance %s" %
11205
                          (pnode.name, instance.name))
11206
      else:
11207
        remote_info = self.rpc.call_instance_info(instance.primary_node,
11208
                                                  instance.name,
11209
                                                  instance.hypervisor)
11210
        remote_info.Raise("Error checking node %s" % instance.primary_node)
11211
        remote_info = remote_info.payload
11212
        if remote_info and "state" in remote_info:
11213
          remote_state = "up"
11214
        else:
11215
          if instance.admin_state == constants.ADMINST_UP:
11216
            remote_state = "down"
11217
          else:
11218
            remote_state = instance.admin_state
11219

    
11220
      disks = map(compat.partial(self._ComputeDiskStatus, instance, None),
11221
                  instance.disks)
11222

    
11223
      result[instance.name] = {
11224
        "name": instance.name,
11225
        "config_state": instance.admin_state,
11226
        "run_state": remote_state,
11227
        "pnode": instance.primary_node,
11228
        "snodes": instance.secondary_nodes,
11229
        "os": instance.os,
11230
        # this happens to be the same format used for hooks
11231
        "nics": _NICListToTuple(self, instance.nics),
11232
        "disk_template": instance.disk_template,
11233
        "disks": disks,
11234
        "hypervisor": instance.hypervisor,
11235
        "network_port": instance.network_port,
11236
        "hv_instance": instance.hvparams,
11237
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
11238
        "be_instance": instance.beparams,
11239
        "be_actual": cluster.FillBE(instance),
11240
        "os_instance": instance.osparams,
11241
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
11242
        "serial_no": instance.serial_no,
11243
        "mtime": instance.mtime,
11244
        "ctime": instance.ctime,
11245
        "uuid": instance.uuid,
11246
        }
11247

    
11248
    return result
11249

    
11250

    
11251
class LUInstanceSetParams(LogicalUnit):
11252
  """Modifies an instances's parameters.
11253

11254
  """
11255
  HPATH = "instance-modify"
11256
  HTYPE = constants.HTYPE_INSTANCE
11257
  REQ_BGL = False
11258

    
11259
  def CheckArguments(self):
11260
    if not (self.op.nics or self.op.disks or self.op.disk_template or
11261
            self.op.hvparams or self.op.beparams or self.op.os_name or
11262
            self.op.online_inst or self.op.offline_inst):
11263
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
11264

    
11265
    if self.op.hvparams:
11266
      _CheckGlobalHvParams(self.op.hvparams)
11267

    
11268
    # Disk validation
11269
    disk_addremove = 0
11270
    for disk_op, disk_dict in self.op.disks:
11271
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
11272
      if disk_op == constants.DDM_REMOVE:
11273
        disk_addremove += 1
11274
        continue
11275
      elif disk_op == constants.DDM_ADD:
11276
        disk_addremove += 1
11277
      else:
11278
        if not isinstance(disk_op, int):
11279
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
11280
        if not isinstance(disk_dict, dict):
11281
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
11282
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
11283

    
11284
      if disk_op == constants.DDM_ADD:
11285
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
11286
        if mode not in constants.DISK_ACCESS_SET:
11287
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
11288
                                     errors.ECODE_INVAL)
11289
        size = disk_dict.get(constants.IDISK_SIZE, None)
11290
        if size is None:
11291
          raise errors.OpPrereqError("Required disk parameter size missing",
11292
                                     errors.ECODE_INVAL)
11293
        try:
11294
          size = int(size)
11295
        except (TypeError, ValueError), err:
11296
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
11297
                                     str(err), errors.ECODE_INVAL)
11298
        disk_dict[constants.IDISK_SIZE] = size
11299
      else:
11300
        # modification of disk
11301
        if constants.IDISK_SIZE in disk_dict:
11302
          raise errors.OpPrereqError("Disk size change not possible, use"
11303
                                     " grow-disk", errors.ECODE_INVAL)
11304

    
11305
    if disk_addremove > 1:
11306
      raise errors.OpPrereqError("Only one disk add or remove operation"
11307
                                 " supported at a time", errors.ECODE_INVAL)
11308

    
11309
    if self.op.disks and self.op.disk_template is not None:
11310
      raise errors.OpPrereqError("Disk template conversion and other disk"
11311
                                 " changes not supported at the same time",
11312
                                 errors.ECODE_INVAL)
11313

    
11314
    if (self.op.disk_template and
11315
        self.op.disk_template in constants.DTS_INT_MIRROR and
11316
        self.op.remote_node is None):
11317
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
11318
                                 " one requires specifying a secondary node",
11319
                                 errors.ECODE_INVAL)
11320

    
11321
    # NIC validation
11322
    nic_addremove = 0
11323
    for nic_op, nic_dict in self.op.nics:
11324
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
11325
      if nic_op == constants.DDM_REMOVE:
11326
        nic_addremove += 1
11327
        continue
11328
      elif nic_op == constants.DDM_ADD:
11329
        nic_addremove += 1
11330
      else:
11331
        if not isinstance(nic_op, int):
11332
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
11333
        if not isinstance(nic_dict, dict):
11334
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
11335
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
11336

    
11337
      # nic_dict should be a dict
11338
      nic_ip = nic_dict.get(constants.INIC_IP, None)
11339
      if nic_ip is not None:
11340
        if nic_ip.lower() == constants.VALUE_NONE:
11341
          nic_dict[constants.INIC_IP] = None
11342
        else:
11343
          if not netutils.IPAddress.IsValid(nic_ip):
11344
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
11345
                                       errors.ECODE_INVAL)
11346

    
11347
      nic_bridge = nic_dict.get("bridge", None)
11348
      nic_link = nic_dict.get(constants.INIC_LINK, None)
11349
      if nic_bridge and nic_link:
11350
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
11351
                                   " at the same time", errors.ECODE_INVAL)
11352
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
11353
        nic_dict["bridge"] = None
11354
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
11355
        nic_dict[constants.INIC_LINK] = None
11356

    
11357
      if nic_op == constants.DDM_ADD:
11358
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
11359
        if nic_mac is None:
11360
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
11361

    
11362
      if constants.INIC_MAC in nic_dict:
11363
        nic_mac = nic_dict[constants.INIC_MAC]
11364
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
11365
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
11366

    
11367
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
11368
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
11369
                                     " modifying an existing nic",
11370
                                     errors.ECODE_INVAL)
11371

    
11372
    if nic_addremove > 1:
11373
      raise errors.OpPrereqError("Only one NIC add or remove operation"
11374
                                 " supported at a time", errors.ECODE_INVAL)
11375

    
11376
  def ExpandNames(self):
11377
    self._ExpandAndLockInstance()
11378
    # Can't even acquire node locks in shared mode as upcoming changes in
11379
    # Ganeti 2.6 will start to modify the node object on disk conversion
11380
    self.needed_locks[locking.LEVEL_NODE] = []
11381
    self.needed_locks[locking.LEVEL_NODE_RES] = []
11382
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
11383

    
11384
  def DeclareLocks(self, level):
11385
    if level == locking.LEVEL_NODE:
11386
      self._LockInstancesNodes()
11387
      if self.op.disk_template and self.op.remote_node:
11388
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
11389
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
11390
    elif level == locking.LEVEL_NODE_RES and self.op.disk_template:
11391
      # Copy node locks
11392
      self.needed_locks[locking.LEVEL_NODE_RES] = \
11393
        self.needed_locks[locking.LEVEL_NODE][:]
11394

    
11395
  def BuildHooksEnv(self):
11396
    """Build hooks env.
11397

11398
    This runs on the master, primary and secondaries.
11399

11400
    """
11401
    args = dict()
11402
    if constants.BE_MINMEM in self.be_new:
11403
      args["minmem"] = self.be_new[constants.BE_MINMEM]
11404
    if constants.BE_MAXMEM in self.be_new:
11405
      args["maxmem"] = self.be_new[constants.BE_MAXMEM]
11406
    if constants.BE_VCPUS in self.be_new:
11407
      args["vcpus"] = self.be_new[constants.BE_VCPUS]
11408
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
11409
    # information at all.
11410
    if self.op.nics:
11411
      args["nics"] = []
11412
      nic_override = dict(self.op.nics)
11413
      for idx, nic in enumerate(self.instance.nics):
11414
        if idx in nic_override:
11415
          this_nic_override = nic_override[idx]
11416
        else:
11417
          this_nic_override = {}
11418
        if constants.INIC_IP in this_nic_override:
11419
          ip = this_nic_override[constants.INIC_IP]
11420
        else:
11421
          ip = nic.ip
11422
        if constants.INIC_MAC in this_nic_override:
11423
          mac = this_nic_override[constants.INIC_MAC]
11424
        else:
11425
          mac = nic.mac
11426
        if idx in self.nic_pnew:
11427
          nicparams = self.nic_pnew[idx]
11428
        else:
11429
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
11430
        mode = nicparams[constants.NIC_MODE]
11431
        link = nicparams[constants.NIC_LINK]
11432
        args["nics"].append((ip, mac, mode, link))
11433
      if constants.DDM_ADD in nic_override:
11434
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
11435
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
11436
        nicparams = self.nic_pnew[constants.DDM_ADD]
11437
        mode = nicparams[constants.NIC_MODE]
11438
        link = nicparams[constants.NIC_LINK]
11439
        args["nics"].append((ip, mac, mode, link))
11440
      elif constants.DDM_REMOVE in nic_override:
11441
        del args["nics"][-1]
11442

    
11443
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
11444
    if self.op.disk_template:
11445
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
11446

    
11447
    return env
11448

    
11449
  def BuildHooksNodes(self):
11450
    """Build hooks nodes.
11451

11452
    """
11453
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
11454
    return (nl, nl)
11455

    
11456
  def CheckPrereq(self):
11457
    """Check prerequisites.
11458

11459
    This only checks the instance list against the existing names.
11460

11461
    """
11462
    # checking the new params on the primary/secondary nodes
11463

    
11464
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
11465
    cluster = self.cluster = self.cfg.GetClusterInfo()
11466
    assert self.instance is not None, \
11467
      "Cannot retrieve locked instance %s" % self.op.instance_name
11468
    pnode = instance.primary_node
11469
    nodelist = list(instance.all_nodes)
11470
    pnode_info = self.cfg.GetNodeInfo(pnode)
11471
    self.diskparams = self.cfg.GetNodeGroup(pnode_info.group).diskparams
11472

    
11473
    # OS change
11474
    if self.op.os_name and not self.op.force:
11475
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
11476
                      self.op.force_variant)
11477
      instance_os = self.op.os_name
11478
    else:
11479
      instance_os = instance.os
11480

    
11481
    if self.op.disk_template:
11482
      if instance.disk_template == self.op.disk_template:
11483
        raise errors.OpPrereqError("Instance already has disk template %s" %
11484
                                   instance.disk_template, errors.ECODE_INVAL)
11485

    
11486
      if (instance.disk_template,
11487
          self.op.disk_template) not in self._DISK_CONVERSIONS:
11488
        raise errors.OpPrereqError("Unsupported disk template conversion from"
11489
                                   " %s to %s" % (instance.disk_template,
11490
                                                  self.op.disk_template),
11491
                                   errors.ECODE_INVAL)
11492
      _CheckInstanceState(self, instance, INSTANCE_DOWN,
11493
                          msg="cannot change disk template")
11494
      if self.op.disk_template in constants.DTS_INT_MIRROR:
11495
        if self.op.remote_node == pnode:
11496
          raise errors.OpPrereqError("Given new secondary node %s is the same"
11497
                                     " as the primary node of the instance" %
11498
                                     self.op.remote_node, errors.ECODE_STATE)
11499
        _CheckNodeOnline(self, self.op.remote_node)
11500
        _CheckNodeNotDrained(self, self.op.remote_node)
11501
        # FIXME: here we assume that the old instance type is DT_PLAIN
11502
        assert instance.disk_template == constants.DT_PLAIN
11503
        disks = [{constants.IDISK_SIZE: d.size,
11504
                  constants.IDISK_VG: d.logical_id[0]}
11505
                 for d in instance.disks]
11506
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
11507
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
11508

    
11509
        snode_info = self.cfg.GetNodeInfo(self.op.remote_node)
11510
        if pnode_info.group != snode_info.group:
11511
          self.LogWarning("The primary and secondary nodes are in two"
11512
                          " different node groups; the disk parameters"
11513
                          " from the first disk's node group will be"
11514
                          " used")
11515

    
11516
    # hvparams processing
11517
    if self.op.hvparams:
11518
      hv_type = instance.hypervisor
11519
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
11520
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
11521
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
11522

    
11523
      # local check
11524
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
11525
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
11526
      self.hv_proposed = self.hv_new = hv_new # the new actual values
11527
      self.hv_inst = i_hvdict # the new dict (without defaults)
11528
    else:
11529
      self.hv_proposed = cluster.SimpleFillHV(instance.hypervisor, instance.os,
11530
                                              instance.hvparams)
11531
      self.hv_new = self.hv_inst = {}
11532

    
11533
    # beparams processing
11534
    if self.op.beparams:
11535
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
11536
                                   use_none=True)
11537
      objects.UpgradeBeParams(i_bedict)
11538
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
11539
      be_new = cluster.SimpleFillBE(i_bedict)
11540
      self.be_proposed = self.be_new = be_new # the new actual values
11541
      self.be_inst = i_bedict # the new dict (without defaults)
11542
    else:
11543
      self.be_new = self.be_inst = {}
11544
      self.be_proposed = cluster.SimpleFillBE(instance.beparams)
11545
    be_old = cluster.FillBE(instance)
11546

    
11547
    # CPU param validation -- checking every time a paramtere is
11548
    # changed to cover all cases where either CPU mask or vcpus have
11549
    # changed
11550
    if (constants.BE_VCPUS in self.be_proposed and
11551
        constants.HV_CPU_MASK in self.hv_proposed):
11552
      cpu_list = \
11553
        utils.ParseMultiCpuMask(self.hv_proposed[constants.HV_CPU_MASK])
11554
      # Verify mask is consistent with number of vCPUs. Can skip this
11555
      # test if only 1 entry in the CPU mask, which means same mask
11556
      # is applied to all vCPUs.
11557
      if (len(cpu_list) > 1 and
11558
          len(cpu_list) != self.be_proposed[constants.BE_VCPUS]):
11559
        raise errors.OpPrereqError("Number of vCPUs [%d] does not match the"
11560
                                   " CPU mask [%s]" %
11561
                                   (self.be_proposed[constants.BE_VCPUS],
11562
                                    self.hv_proposed[constants.HV_CPU_MASK]),
11563
                                   errors.ECODE_INVAL)
11564

    
11565
      # Only perform this test if a new CPU mask is given
11566
      if constants.HV_CPU_MASK in self.hv_new:
11567
        # Calculate the largest CPU number requested
11568
        max_requested_cpu = max(map(max, cpu_list))
11569
        # Check that all of the instance's nodes have enough physical CPUs to
11570
        # satisfy the requested CPU mask
11571
        _CheckNodesPhysicalCPUs(self, instance.all_nodes,
11572
                                max_requested_cpu + 1, instance.hypervisor)
11573

    
11574
    # osparams processing
11575
    if self.op.osparams:
11576
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
11577
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
11578
      self.os_inst = i_osdict # the new dict (without defaults)
11579
    else:
11580
      self.os_inst = {}
11581

    
11582
    self.warn = []
11583

    
11584
    #TODO(dynmem): do the appropriate check involving MINMEM
11585
    if (constants.BE_MAXMEM in self.op.beparams and not self.op.force and
11586
        be_new[constants.BE_MAXMEM] > be_old[constants.BE_MAXMEM]):
11587
      mem_check_list = [pnode]
11588
      if be_new[constants.BE_AUTO_BALANCE]:
11589
        # either we changed auto_balance to yes or it was from before
11590
        mem_check_list.extend(instance.secondary_nodes)
11591
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
11592
                                                  instance.hypervisor)
11593
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
11594
                                         [instance.hypervisor])
11595
      pninfo = nodeinfo[pnode]
11596
      msg = pninfo.fail_msg
11597
      if msg:
11598
        # Assume the primary node is unreachable and go ahead
11599
        self.warn.append("Can't get info from primary node %s: %s" %
11600
                         (pnode, msg))
11601
      else:
11602
        (_, _, (pnhvinfo, )) = pninfo.payload
11603
        if not isinstance(pnhvinfo.get("memory_free", None), int):
11604
          self.warn.append("Node data from primary node %s doesn't contain"
11605
                           " free memory information" % pnode)
11606
        elif instance_info.fail_msg:
11607
          self.warn.append("Can't get instance runtime information: %s" %
11608
                          instance_info.fail_msg)
11609
        else:
11610
          if instance_info.payload:
11611
            current_mem = int(instance_info.payload["memory"])
11612
          else:
11613
            # Assume instance not running
11614
            # (there is a slight race condition here, but it's not very
11615
            # probable, and we have no other way to check)
11616
            # TODO: Describe race condition
11617
            current_mem = 0
11618
          #TODO(dynmem): do the appropriate check involving MINMEM
11619
          miss_mem = (be_new[constants.BE_MAXMEM] - current_mem -
11620
                      pnhvinfo["memory_free"])
11621
          if miss_mem > 0:
11622
            raise errors.OpPrereqError("This change will prevent the instance"
11623
                                       " from starting, due to %d MB of memory"
11624
                                       " missing on its primary node" %
11625
                                       miss_mem,
11626
                                       errors.ECODE_NORES)
11627

    
11628
      if be_new[constants.BE_AUTO_BALANCE]:
11629
        for node, nres in nodeinfo.items():
11630
          if node not in instance.secondary_nodes:
11631
            continue
11632
          nres.Raise("Can't get info from secondary node %s" % node,
11633
                     prereq=True, ecode=errors.ECODE_STATE)
11634
          (_, _, (nhvinfo, )) = nres.payload
11635
          if not isinstance(nhvinfo.get("memory_free", None), int):
11636
            raise errors.OpPrereqError("Secondary node %s didn't return free"
11637
                                       " memory information" % node,
11638
                                       errors.ECODE_STATE)
11639
          #TODO(dynmem): do the appropriate check involving MINMEM
11640
          elif be_new[constants.BE_MAXMEM] > nhvinfo["memory_free"]:
11641
            raise errors.OpPrereqError("This change will prevent the instance"
11642
                                       " from failover to its secondary node"
11643
                                       " %s, due to not enough memory" % node,
11644
                                       errors.ECODE_STATE)
11645

    
11646
    # NIC processing
11647
    self.nic_pnew = {}
11648
    self.nic_pinst = {}
11649
    for nic_op, nic_dict in self.op.nics:
11650
      if nic_op == constants.DDM_REMOVE:
11651
        if not instance.nics:
11652
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
11653
                                     errors.ECODE_INVAL)
11654
        continue
11655
      if nic_op != constants.DDM_ADD:
11656
        # an existing nic
11657
        if not instance.nics:
11658
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
11659
                                     " no NICs" % nic_op,
11660
                                     errors.ECODE_INVAL)
11661
        if nic_op < 0 or nic_op >= len(instance.nics):
11662
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
11663
                                     " are 0 to %d" %
11664
                                     (nic_op, len(instance.nics) - 1),
11665
                                     errors.ECODE_INVAL)
11666
        old_nic_params = instance.nics[nic_op].nicparams
11667
        old_nic_ip = instance.nics[nic_op].ip
11668
      else:
11669
        old_nic_params = {}
11670
        old_nic_ip = None
11671

    
11672
      update_params_dict = dict([(key, nic_dict[key])
11673
                                 for key in constants.NICS_PARAMETERS
11674
                                 if key in nic_dict])
11675

    
11676
      if "bridge" in nic_dict:
11677
        update_params_dict[constants.NIC_LINK] = nic_dict["bridge"]
11678

    
11679
      new_nic_params = _GetUpdatedParams(old_nic_params,
11680
                                         update_params_dict)
11681
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
11682
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
11683
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
11684
      self.nic_pinst[nic_op] = new_nic_params
11685
      self.nic_pnew[nic_op] = new_filled_nic_params
11686
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
11687

    
11688
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
11689
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
11690
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
11691
        if msg:
11692
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
11693
          if self.op.force:
11694
            self.warn.append(msg)
11695
          else:
11696
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
11697
      if new_nic_mode == constants.NIC_MODE_ROUTED:
11698
        if constants.INIC_IP in nic_dict:
11699
          nic_ip = nic_dict[constants.INIC_IP]
11700
        else:
11701
          nic_ip = old_nic_ip
11702
        if nic_ip is None:
11703
          raise errors.OpPrereqError("Cannot set the nic ip to None"
11704
                                     " on a routed nic", errors.ECODE_INVAL)
11705
      if constants.INIC_MAC in nic_dict:
11706
        nic_mac = nic_dict[constants.INIC_MAC]
11707
        if nic_mac is None:
11708
          raise errors.OpPrereqError("Cannot set the nic mac to None",
11709
                                     errors.ECODE_INVAL)
11710
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
11711
          # otherwise generate the mac
11712
          nic_dict[constants.INIC_MAC] = \
11713
            self.cfg.GenerateMAC(self.proc.GetECId())
11714
        else:
11715
          # or validate/reserve the current one
11716
          try:
11717
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
11718
          except errors.ReservationError:
11719
            raise errors.OpPrereqError("MAC address %s already in use"
11720
                                       " in cluster" % nic_mac,
11721
                                       errors.ECODE_NOTUNIQUE)
11722

    
11723
    # DISK processing
11724
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
11725
      raise errors.OpPrereqError("Disk operations not supported for"
11726
                                 " diskless instances",
11727
                                 errors.ECODE_INVAL)
11728
    for disk_op, _ in self.op.disks:
11729
      if disk_op == constants.DDM_REMOVE:
11730
        if len(instance.disks) == 1:
11731
          raise errors.OpPrereqError("Cannot remove the last disk of"
11732
                                     " an instance", errors.ECODE_INVAL)
11733
        _CheckInstanceState(self, instance, INSTANCE_DOWN,
11734
                            msg="cannot remove disks")
11735

    
11736
      if (disk_op == constants.DDM_ADD and
11737
          len(instance.disks) >= constants.MAX_DISKS):
11738
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
11739
                                   " add more" % constants.MAX_DISKS,
11740
                                   errors.ECODE_STATE)
11741
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
11742
        # an existing disk
11743
        if disk_op < 0 or disk_op >= len(instance.disks):
11744
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
11745
                                     " are 0 to %d" %
11746
                                     (disk_op, len(instance.disks)),
11747
                                     errors.ECODE_INVAL)
11748

    
11749
    # disabling the instance
11750
    if self.op.offline_inst:
11751
      _CheckInstanceState(self, instance, INSTANCE_DOWN,
11752
                          msg="cannot change instance state to offline")
11753

    
11754
    # enabling the instance
11755
    if self.op.online_inst:
11756
      _CheckInstanceState(self, instance, INSTANCE_OFFLINE,
11757
                          msg="cannot make instance go online")
11758

    
11759
  def _ConvertPlainToDrbd(self, feedback_fn):
11760
    """Converts an instance from plain to drbd.
11761

11762
    """
11763
    feedback_fn("Converting template to drbd")
11764
    instance = self.instance
11765
    pnode = instance.primary_node
11766
    snode = self.op.remote_node
11767

    
11768
    assert instance.disk_template == constants.DT_PLAIN
11769

    
11770
    # create a fake disk info for _GenerateDiskTemplate
11771
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
11772
                  constants.IDISK_VG: d.logical_id[0]}
11773
                 for d in instance.disks]
11774
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
11775
                                      instance.name, pnode, [snode],
11776
                                      disk_info, None, None, 0, feedback_fn,
11777
                                      self.diskparams)
11778
    info = _GetInstanceInfoText(instance)
11779
    feedback_fn("Creating aditional volumes...")
11780
    # first, create the missing data and meta devices
11781
    for disk in new_disks:
11782
      # unfortunately this is... not too nice
11783
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
11784
                            info, True)
11785
      for child in disk.children:
11786
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
11787
    # at this stage, all new LVs have been created, we can rename the
11788
    # old ones
11789
    feedback_fn("Renaming original volumes...")
11790
    rename_list = [(o, n.children[0].logical_id)
11791
                   for (o, n) in zip(instance.disks, new_disks)]
11792
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
11793
    result.Raise("Failed to rename original LVs")
11794

    
11795
    feedback_fn("Initializing DRBD devices...")
11796
    # all child devices are in place, we can now create the DRBD devices
11797
    for disk in new_disks:
11798
      for node in [pnode, snode]:
11799
        f_create = node == pnode
11800
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
11801

    
11802
    # at this point, the instance has been modified
11803
    instance.disk_template = constants.DT_DRBD8
11804
    instance.disks = new_disks
11805
    self.cfg.Update(instance, feedback_fn)
11806

    
11807
    # Release node locks while waiting for sync
11808
    _ReleaseLocks(self, locking.LEVEL_NODE)
11809

    
11810
    # disks are created, waiting for sync
11811
    disk_abort = not _WaitForSync(self, instance,
11812
                                  oneshot=not self.op.wait_for_sync)
11813
    if disk_abort:
11814
      raise errors.OpExecError("There are some degraded disks for"
11815
                               " this instance, please cleanup manually")
11816

    
11817
    # Node resource locks will be released by caller
11818

    
11819
  def _ConvertDrbdToPlain(self, feedback_fn):
11820
    """Converts an instance from drbd to plain.
11821

11822
    """
11823
    instance = self.instance
11824

    
11825
    assert len(instance.secondary_nodes) == 1
11826
    assert instance.disk_template == constants.DT_DRBD8
11827

    
11828
    pnode = instance.primary_node
11829
    snode = instance.secondary_nodes[0]
11830
    feedback_fn("Converting template to plain")
11831

    
11832
    old_disks = instance.disks
11833
    new_disks = [d.children[0] for d in old_disks]
11834

    
11835
    # copy over size and mode
11836
    for parent, child in zip(old_disks, new_disks):
11837
      child.size = parent.size
11838
      child.mode = parent.mode
11839

    
11840
    # update instance structure
11841
    instance.disks = new_disks
11842
    instance.disk_template = constants.DT_PLAIN
11843
    self.cfg.Update(instance, feedback_fn)
11844

    
11845
    # Release locks in case removing disks takes a while
11846
    _ReleaseLocks(self, locking.LEVEL_NODE)
11847

    
11848
    feedback_fn("Removing volumes on the secondary node...")
11849
    for disk in old_disks:
11850
      self.cfg.SetDiskID(disk, snode)
11851
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
11852
      if msg:
11853
        self.LogWarning("Could not remove block device %s on node %s,"
11854
                        " continuing anyway: %s", disk.iv_name, snode, msg)
11855

    
11856
    feedback_fn("Removing unneeded volumes on the primary node...")
11857
    for idx, disk in enumerate(old_disks):
11858
      meta = disk.children[1]
11859
      self.cfg.SetDiskID(meta, pnode)
11860
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
11861
      if msg:
11862
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
11863
                        " continuing anyway: %s", idx, pnode, msg)
11864

    
11865
    # this is a DRBD disk, return its port to the pool
11866
    for disk in old_disks:
11867
      tcp_port = disk.logical_id[2]
11868
      self.cfg.AddTcpUdpPort(tcp_port)
11869

    
11870
    # Node resource locks will be released by caller
11871

    
11872
  def Exec(self, feedback_fn):
11873
    """Modifies an instance.
11874

11875
    All parameters take effect only at the next restart of the instance.
11876

11877
    """
11878
    # Process here the warnings from CheckPrereq, as we don't have a
11879
    # feedback_fn there.
11880
    for warn in self.warn:
11881
      feedback_fn("WARNING: %s" % warn)
11882

    
11883
    assert ((self.op.disk_template is None) ^
11884
            bool(self.owned_locks(locking.LEVEL_NODE_RES))), \
11885
      "Not owning any node resource locks"
11886

    
11887
    result = []
11888
    instance = self.instance
11889
    # disk changes
11890
    for disk_op, disk_dict in self.op.disks:
11891
      if disk_op == constants.DDM_REMOVE:
11892
        # remove the last disk
11893
        device = instance.disks.pop()
11894
        device_idx = len(instance.disks)
11895
        for node, disk in device.ComputeNodeTree(instance.primary_node):
11896
          self.cfg.SetDiskID(disk, node)
11897
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
11898
          if msg:
11899
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
11900
                            " continuing anyway", device_idx, node, msg)
11901
        result.append(("disk/%d" % device_idx, "remove"))
11902

    
11903
        # if this is a DRBD disk, return its port to the pool
11904
        if device.dev_type in constants.LDS_DRBD:
11905
          tcp_port = device.logical_id[2]
11906
          self.cfg.AddTcpUdpPort(tcp_port)
11907
      elif disk_op == constants.DDM_ADD:
11908
        # add a new disk
11909
        if instance.disk_template in (constants.DT_FILE,
11910
                                        constants.DT_SHARED_FILE):
11911
          file_driver, file_path = instance.disks[0].logical_id
11912
          file_path = os.path.dirname(file_path)
11913
        else:
11914
          file_driver = file_path = None
11915
        disk_idx_base = len(instance.disks)
11916
        new_disk = _GenerateDiskTemplate(self,
11917
                                         instance.disk_template,
11918
                                         instance.name, instance.primary_node,
11919
                                         instance.secondary_nodes,
11920
                                         [disk_dict],
11921
                                         file_path,
11922
                                         file_driver,
11923
                                         disk_idx_base,
11924
                                         feedback_fn,
11925
                                         self.diskparams)[0]
11926
        instance.disks.append(new_disk)
11927
        info = _GetInstanceInfoText(instance)
11928

    
11929
        logging.info("Creating volume %s for instance %s",
11930
                     new_disk.iv_name, instance.name)
11931
        # Note: this needs to be kept in sync with _CreateDisks
11932
        #HARDCODE
11933
        for node in instance.all_nodes:
11934
          f_create = node == instance.primary_node
11935
          try:
11936
            _CreateBlockDev(self, node, instance, new_disk,
11937
                            f_create, info, f_create)
11938
          except errors.OpExecError, err:
11939
            self.LogWarning("Failed to create volume %s (%s) on"
11940
                            " node %s: %s",
11941
                            new_disk.iv_name, new_disk, node, err)
11942
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
11943
                       (new_disk.size, new_disk.mode)))
11944
      else:
11945
        # change a given disk
11946
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
11947
        result.append(("disk.mode/%d" % disk_op,
11948
                       disk_dict[constants.IDISK_MODE]))
11949

    
11950
    if self.op.disk_template:
11951
      if __debug__:
11952
        check_nodes = set(instance.all_nodes)
11953
        if self.op.remote_node:
11954
          check_nodes.add(self.op.remote_node)
11955
        for level in [locking.LEVEL_NODE, locking.LEVEL_NODE_RES]:
11956
          owned = self.owned_locks(level)
11957
          assert not (check_nodes - owned), \
11958
            ("Not owning the correct locks, owning %r, expected at least %r" %
11959
             (owned, check_nodes))
11960

    
11961
      r_shut = _ShutdownInstanceDisks(self, instance)
11962
      if not r_shut:
11963
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
11964
                                 " proceed with disk template conversion")
11965
      mode = (instance.disk_template, self.op.disk_template)
11966
      try:
11967
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
11968
      except:
11969
        self.cfg.ReleaseDRBDMinors(instance.name)
11970
        raise
11971
      result.append(("disk_template", self.op.disk_template))
11972

    
11973
      assert instance.disk_template == self.op.disk_template, \
11974
        ("Expected disk template '%s', found '%s'" %
11975
         (self.op.disk_template, instance.disk_template))
11976

    
11977
    # Release node and resource locks if there are any (they might already have
11978
    # been released during disk conversion)
11979
    _ReleaseLocks(self, locking.LEVEL_NODE)
11980
    _ReleaseLocks(self, locking.LEVEL_NODE_RES)
11981

    
11982
    # NIC changes
11983
    for nic_op, nic_dict in self.op.nics:
11984
      if nic_op == constants.DDM_REMOVE:
11985
        # remove the last nic
11986
        del instance.nics[-1]
11987
        result.append(("nic.%d" % len(instance.nics), "remove"))
11988
      elif nic_op == constants.DDM_ADD:
11989
        # mac and bridge should be set, by now
11990
        mac = nic_dict[constants.INIC_MAC]
11991
        ip = nic_dict.get(constants.INIC_IP, None)
11992
        nicparams = self.nic_pinst[constants.DDM_ADD]
11993
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
11994
        instance.nics.append(new_nic)
11995
        result.append(("nic.%d" % (len(instance.nics) - 1),
11996
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
11997
                       (new_nic.mac, new_nic.ip,
11998
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
11999
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
12000
                       )))
12001
      else:
12002
        for key in (constants.INIC_MAC, constants.INIC_IP):
12003
          if key in nic_dict:
12004
            setattr(instance.nics[nic_op], key, nic_dict[key])
12005
        if nic_op in self.nic_pinst:
12006
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
12007
        for key, val in nic_dict.iteritems():
12008
          result.append(("nic.%s/%d" % (key, nic_op), val))
12009

    
12010
    # hvparams changes
12011
    if self.op.hvparams:
12012
      instance.hvparams = self.hv_inst
12013
      for key, val in self.op.hvparams.iteritems():
12014
        result.append(("hv/%s" % key, val))
12015

    
12016
    # beparams changes
12017
    if self.op.beparams:
12018
      instance.beparams = self.be_inst
12019
      for key, val in self.op.beparams.iteritems():
12020
        result.append(("be/%s" % key, val))
12021

    
12022
    # OS change
12023
    if self.op.os_name:
12024
      instance.os = self.op.os_name
12025

    
12026
    # osparams changes
12027
    if self.op.osparams:
12028
      instance.osparams = self.os_inst
12029
      for key, val in self.op.osparams.iteritems():
12030
        result.append(("os/%s" % key, val))
12031

    
12032
    # online/offline instance
12033
    if self.op.online_inst:
12034
      self.cfg.MarkInstanceDown(instance.name)
12035
      result.append(("admin_state", constants.ADMINST_DOWN))
12036
    if self.op.offline_inst:
12037
      self.cfg.MarkInstanceOffline(instance.name)
12038
      result.append(("admin_state", constants.ADMINST_OFFLINE))
12039

    
12040
    self.cfg.Update(instance, feedback_fn)
12041

    
12042
    assert not (self.owned_locks(locking.LEVEL_NODE_RES) or
12043
                self.owned_locks(locking.LEVEL_NODE)), \
12044
      "All node locks should have been released by now"
12045

    
12046
    return result
12047

    
12048
  _DISK_CONVERSIONS = {
12049
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
12050
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
12051
    }
12052

    
12053

    
12054
class LUInstanceChangeGroup(LogicalUnit):
12055
  HPATH = "instance-change-group"
12056
  HTYPE = constants.HTYPE_INSTANCE
12057
  REQ_BGL = False
12058

    
12059
  def ExpandNames(self):
12060
    self.share_locks = _ShareAll()
12061
    self.needed_locks = {
12062
      locking.LEVEL_NODEGROUP: [],
12063
      locking.LEVEL_NODE: [],
12064
      }
12065

    
12066
    self._ExpandAndLockInstance()
12067

    
12068
    if self.op.target_groups:
12069
      self.req_target_uuids = map(self.cfg.LookupNodeGroup,
12070
                                  self.op.target_groups)
12071
    else:
12072
      self.req_target_uuids = None
12073

    
12074
    self.op.iallocator = _GetDefaultIAllocator(self.cfg, self.op.iallocator)
12075

    
12076
  def DeclareLocks(self, level):
12077
    if level == locking.LEVEL_NODEGROUP:
12078
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
12079

    
12080
      if self.req_target_uuids:
12081
        lock_groups = set(self.req_target_uuids)
12082

    
12083
        # Lock all groups used by instance optimistically; this requires going
12084
        # via the node before it's locked, requiring verification later on
12085
        instance_groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
12086
        lock_groups.update(instance_groups)
12087
      else:
12088
        # No target groups, need to lock all of them
12089
        lock_groups = locking.ALL_SET
12090

    
12091
      self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
12092

    
12093
    elif level == locking.LEVEL_NODE:
12094
      if self.req_target_uuids:
12095
        # Lock all nodes used by instances
12096
        self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
12097
        self._LockInstancesNodes()
12098

    
12099
        # Lock all nodes in all potential target groups
12100
        lock_groups = (frozenset(self.owned_locks(locking.LEVEL_NODEGROUP)) -
12101
                       self.cfg.GetInstanceNodeGroups(self.op.instance_name))
12102
        member_nodes = [node_name
12103
                        for group in lock_groups
12104
                        for node_name in self.cfg.GetNodeGroup(group).members]
12105
        self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
12106
      else:
12107
        # Lock all nodes as all groups are potential targets
12108
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
12109

    
12110
  def CheckPrereq(self):
12111
    owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
12112
    owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
12113
    owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
12114

    
12115
    assert (self.req_target_uuids is None or
12116
            owned_groups.issuperset(self.req_target_uuids))
12117
    assert owned_instances == set([self.op.instance_name])
12118

    
12119
    # Get instance information
12120
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
12121

    
12122
    # Check if node groups for locked instance are still correct
12123
    assert owned_nodes.issuperset(self.instance.all_nodes), \
12124
      ("Instance %s's nodes changed while we kept the lock" %
12125
       self.op.instance_name)
12126

    
12127
    inst_groups = _CheckInstanceNodeGroups(self.cfg, self.op.instance_name,
12128
                                           owned_groups)
12129

    
12130
    if self.req_target_uuids:
12131
      # User requested specific target groups
12132
      self.target_uuids = self.req_target_uuids
12133
    else:
12134
      # All groups except those used by the instance are potential targets
12135
      self.target_uuids = owned_groups - inst_groups
12136

    
12137
    conflicting_groups = self.target_uuids & inst_groups
12138
    if conflicting_groups:
12139
      raise errors.OpPrereqError("Can't use group(s) '%s' as targets, they are"
12140
                                 " used by the instance '%s'" %
12141
                                 (utils.CommaJoin(conflicting_groups),
12142
                                  self.op.instance_name),
12143
                                 errors.ECODE_INVAL)
12144

    
12145
    if not self.target_uuids:
12146
      raise errors.OpPrereqError("There are no possible target groups",
12147
                                 errors.ECODE_INVAL)
12148

    
12149
  def BuildHooksEnv(self):
12150
    """Build hooks env.
12151

12152
    """
12153
    assert self.target_uuids
12154

    
12155
    env = {
12156
      "TARGET_GROUPS": " ".join(self.target_uuids),
12157
      }
12158

    
12159
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
12160

    
12161
    return env
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
    instances = list(self.owned_locks(locking.LEVEL_INSTANCE))
12172

    
12173
    assert instances == [self.op.instance_name], "Instance not locked"
12174

    
12175
    ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
12176
                     instances=instances, target_groups=list(self.target_uuids))
12177

    
12178
    ial.Run(self.op.iallocator)
12179

    
12180
    if not ial.success:
12181
      raise errors.OpPrereqError("Can't compute solution for changing group of"
12182
                                 " instance '%s' using iallocator '%s': %s" %
12183
                                 (self.op.instance_name, self.op.iallocator,
12184
                                  ial.info),
12185
                                 errors.ECODE_NORES)
12186

    
12187
    jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
12188

    
12189
    self.LogInfo("Iallocator returned %s job(s) for changing group of"
12190
                 " instance '%s'", len(jobs), self.op.instance_name)
12191

    
12192
    return ResultWithJobs(jobs)
12193

    
12194

    
12195
class LUBackupQuery(NoHooksLU):
12196
  """Query the exports list
12197

12198
  """
12199
  REQ_BGL = False
12200

    
12201
  def ExpandNames(self):
12202
    self.needed_locks = {}
12203
    self.share_locks[locking.LEVEL_NODE] = 1
12204
    if not self.op.nodes:
12205
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
12206
    else:
12207
      self.needed_locks[locking.LEVEL_NODE] = \
12208
        _GetWantedNodes(self, self.op.nodes)
12209

    
12210
  def Exec(self, feedback_fn):
12211
    """Compute the list of all the exported system images.
12212

12213
    @rtype: dict
12214
    @return: a dictionary with the structure node->(export-list)
12215
        where export-list is a list of the instances exported on
12216
        that node.
12217

12218
    """
12219
    self.nodes = self.owned_locks(locking.LEVEL_NODE)
12220
    rpcresult = self.rpc.call_export_list(self.nodes)
12221
    result = {}
12222
    for node in rpcresult:
12223
      if rpcresult[node].fail_msg:
12224
        result[node] = False
12225
      else:
12226
        result[node] = rpcresult[node].payload
12227

    
12228
    return result
12229

    
12230

    
12231
class LUBackupPrepare(NoHooksLU):
12232
  """Prepares an instance for an export and returns useful information.
12233

12234
  """
12235
  REQ_BGL = False
12236

    
12237
  def ExpandNames(self):
12238
    self._ExpandAndLockInstance()
12239

    
12240
  def CheckPrereq(self):
12241
    """Check prerequisites.
12242

12243
    """
12244
    instance_name = self.op.instance_name
12245

    
12246
    self.instance = self.cfg.GetInstanceInfo(instance_name)
12247
    assert self.instance is not None, \
12248
          "Cannot retrieve locked instance %s" % self.op.instance_name
12249
    _CheckNodeOnline(self, self.instance.primary_node)
12250

    
12251
    self._cds = _GetClusterDomainSecret()
12252

    
12253
  def Exec(self, feedback_fn):
12254
    """Prepares an instance for an export.
12255

12256
    """
12257
    instance = self.instance
12258

    
12259
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
12260
      salt = utils.GenerateSecret(8)
12261

    
12262
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
12263
      result = self.rpc.call_x509_cert_create(instance.primary_node,
12264
                                              constants.RIE_CERT_VALIDITY)
12265
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
12266

    
12267
      (name, cert_pem) = result.payload
12268

    
12269
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
12270
                                             cert_pem)
12271

    
12272
      return {
12273
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
12274
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
12275
                          salt),
12276
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
12277
        }
12278

    
12279
    return None
12280

    
12281

    
12282
class LUBackupExport(LogicalUnit):
12283
  """Export an instance to an image in the cluster.
12284

12285
  """
12286
  HPATH = "instance-export"
12287
  HTYPE = constants.HTYPE_INSTANCE
12288
  REQ_BGL = False
12289

    
12290
  def CheckArguments(self):
12291
    """Check the arguments.
12292

12293
    """
12294
    self.x509_key_name = self.op.x509_key_name
12295
    self.dest_x509_ca_pem = self.op.destination_x509_ca
12296

    
12297
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
12298
      if not self.x509_key_name:
12299
        raise errors.OpPrereqError("Missing X509 key name for encryption",
12300
                                   errors.ECODE_INVAL)
12301

    
12302
      if not self.dest_x509_ca_pem:
12303
        raise errors.OpPrereqError("Missing destination X509 CA",
12304
                                   errors.ECODE_INVAL)
12305

    
12306
  def ExpandNames(self):
12307
    self._ExpandAndLockInstance()
12308

    
12309
    # Lock all nodes for local exports
12310
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
12311
      # FIXME: lock only instance primary and destination node
12312
      #
12313
      # Sad but true, for now we have do lock all nodes, as we don't know where
12314
      # the previous export might be, and in this LU we search for it and
12315
      # remove it from its current node. In the future we could fix this by:
12316
      #  - making a tasklet to search (share-lock all), then create the
12317
      #    new one, then one to remove, after
12318
      #  - removing the removal operation altogether
12319
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
12320

    
12321
  def DeclareLocks(self, level):
12322
    """Last minute lock declaration."""
12323
    # All nodes are locked anyway, so nothing to do here.
12324

    
12325
  def BuildHooksEnv(self):
12326
    """Build hooks env.
12327

12328
    This will run on the master, primary node and target node.
12329

12330
    """
12331
    env = {
12332
      "EXPORT_MODE": self.op.mode,
12333
      "EXPORT_NODE": self.op.target_node,
12334
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
12335
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
12336
      # TODO: Generic function for boolean env variables
12337
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
12338
      }
12339

    
12340
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
12341

    
12342
    return env
12343

    
12344
  def BuildHooksNodes(self):
12345
    """Build hooks nodes.
12346

12347
    """
12348
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
12349

    
12350
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
12351
      nl.append(self.op.target_node)
12352

    
12353
    return (nl, nl)
12354

    
12355
  def CheckPrereq(self):
12356
    """Check prerequisites.
12357

12358
    This checks that the instance and node names are valid.
12359

12360
    """
12361
    instance_name = self.op.instance_name
12362

    
12363
    self.instance = self.cfg.GetInstanceInfo(instance_name)
12364
    assert self.instance is not None, \
12365
          "Cannot retrieve locked instance %s" % self.op.instance_name
12366
    _CheckNodeOnline(self, self.instance.primary_node)
12367

    
12368
    if (self.op.remove_instance and
12369
        self.instance.admin_state == constants.ADMINST_UP and
12370
        not self.op.shutdown):
12371
      raise errors.OpPrereqError("Can not remove instance without shutting it"
12372
                                 " down before")
12373

    
12374
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
12375
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
12376
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
12377
      assert self.dst_node is not None
12378

    
12379
      _CheckNodeOnline(self, self.dst_node.name)
12380
      _CheckNodeNotDrained(self, self.dst_node.name)
12381

    
12382
      self._cds = None
12383
      self.dest_disk_info = None
12384
      self.dest_x509_ca = None
12385

    
12386
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
12387
      self.dst_node = None
12388

    
12389
      if len(self.op.target_node) != len(self.instance.disks):
12390
        raise errors.OpPrereqError(("Received destination information for %s"
12391
                                    " disks, but instance %s has %s disks") %
12392
                                   (len(self.op.target_node), instance_name,
12393
                                    len(self.instance.disks)),
12394
                                   errors.ECODE_INVAL)
12395

    
12396
      cds = _GetClusterDomainSecret()
12397

    
12398
      # Check X509 key name
12399
      try:
12400
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
12401
      except (TypeError, ValueError), err:
12402
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
12403

    
12404
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
12405
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
12406
                                   errors.ECODE_INVAL)
12407

    
12408
      # Load and verify CA
12409
      try:
12410
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
12411
      except OpenSSL.crypto.Error, err:
12412
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
12413
                                   (err, ), errors.ECODE_INVAL)
12414

    
12415
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
12416
      if errcode is not None:
12417
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
12418
                                   (msg, ), errors.ECODE_INVAL)
12419

    
12420
      self.dest_x509_ca = cert
12421

    
12422
      # Verify target information
12423
      disk_info = []
12424
      for idx, disk_data in enumerate(self.op.target_node):
12425
        try:
12426
          (host, port, magic) = \
12427
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
12428
        except errors.GenericError, err:
12429
          raise errors.OpPrereqError("Target info for disk %s: %s" %
12430
                                     (idx, err), errors.ECODE_INVAL)
12431

    
12432
        disk_info.append((host, port, magic))
12433

    
12434
      assert len(disk_info) == len(self.op.target_node)
12435
      self.dest_disk_info = disk_info
12436

    
12437
    else:
12438
      raise errors.ProgrammerError("Unhandled export mode %r" %
12439
                                   self.op.mode)
12440

    
12441
    # instance disk type verification
12442
    # TODO: Implement export support for file-based disks
12443
    for disk in self.instance.disks:
12444
      if disk.dev_type == constants.LD_FILE:
12445
        raise errors.OpPrereqError("Export not supported for instances with"
12446
                                   " file-based disks", errors.ECODE_INVAL)
12447

    
12448
  def _CleanupExports(self, feedback_fn):
12449
    """Removes exports of current instance from all other nodes.
12450

12451
    If an instance in a cluster with nodes A..D was exported to node C, its
12452
    exports will be removed from the nodes A, B and D.
12453

12454
    """
12455
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
12456

    
12457
    nodelist = self.cfg.GetNodeList()
12458
    nodelist.remove(self.dst_node.name)
12459

    
12460
    # on one-node clusters nodelist will be empty after the removal
12461
    # if we proceed the backup would be removed because OpBackupQuery
12462
    # substitutes an empty list with the full cluster node list.
12463
    iname = self.instance.name
12464
    if nodelist:
12465
      feedback_fn("Removing old exports for instance %s" % iname)
12466
      exportlist = self.rpc.call_export_list(nodelist)
12467
      for node in exportlist:
12468
        if exportlist[node].fail_msg:
12469
          continue
12470
        if iname in exportlist[node].payload:
12471
          msg = self.rpc.call_export_remove(node, iname).fail_msg
12472
          if msg:
12473
            self.LogWarning("Could not remove older export for instance %s"
12474
                            " on node %s: %s", iname, node, msg)
12475

    
12476
  def Exec(self, feedback_fn):
12477
    """Export an instance to an image in the cluster.
12478

12479
    """
12480
    assert self.op.mode in constants.EXPORT_MODES
12481

    
12482
    instance = self.instance
12483
    src_node = instance.primary_node
12484

    
12485
    if self.op.shutdown:
12486
      # shutdown the instance, but not the disks
12487
      feedback_fn("Shutting down instance %s" % instance.name)
12488
      result = self.rpc.call_instance_shutdown(src_node, instance,
12489
                                               self.op.shutdown_timeout)
12490
      # TODO: Maybe ignore failures if ignore_remove_failures is set
12491
      result.Raise("Could not shutdown instance %s on"
12492
                   " node %s" % (instance.name, src_node))
12493

    
12494
    # set the disks ID correctly since call_instance_start needs the
12495
    # correct drbd minor to create the symlinks
12496
    for disk in instance.disks:
12497
      self.cfg.SetDiskID(disk, src_node)
12498

    
12499
    activate_disks = (instance.admin_state != constants.ADMINST_UP)
12500

    
12501
    if activate_disks:
12502
      # Activate the instance disks if we'exporting a stopped instance
12503
      feedback_fn("Activating disks for %s" % instance.name)
12504
      _StartInstanceDisks(self, instance, None)
12505

    
12506
    try:
12507
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
12508
                                                     instance)
12509

    
12510
      helper.CreateSnapshots()
12511
      try:
12512
        if (self.op.shutdown and
12513
            instance.admin_state == constants.ADMINST_UP and
12514
            not self.op.remove_instance):
12515
          assert not activate_disks
12516
          feedback_fn("Starting instance %s" % instance.name)
12517
          result = self.rpc.call_instance_start(src_node,
12518
                                                (instance, None, None), False)
12519
          msg = result.fail_msg
12520
          if msg:
12521
            feedback_fn("Failed to start instance: %s" % msg)
12522
            _ShutdownInstanceDisks(self, instance)
12523
            raise errors.OpExecError("Could not start instance: %s" % msg)
12524

    
12525
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
12526
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
12527
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
12528
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
12529
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
12530

    
12531
          (key_name, _, _) = self.x509_key_name
12532

    
12533
          dest_ca_pem = \
12534
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
12535
                                            self.dest_x509_ca)
12536

    
12537
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
12538
                                                     key_name, dest_ca_pem,
12539
                                                     timeouts)
12540
      finally:
12541
        helper.Cleanup()
12542

    
12543
      # Check for backwards compatibility
12544
      assert len(dresults) == len(instance.disks)
12545
      assert compat.all(isinstance(i, bool) for i in dresults), \
12546
             "Not all results are boolean: %r" % dresults
12547

    
12548
    finally:
12549
      if activate_disks:
12550
        feedback_fn("Deactivating disks for %s" % instance.name)
12551
        _ShutdownInstanceDisks(self, instance)
12552

    
12553
    if not (compat.all(dresults) and fin_resu):
12554
      failures = []
12555
      if not fin_resu:
12556
        failures.append("export finalization")
12557
      if not compat.all(dresults):
12558
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
12559
                               if not dsk)
12560
        failures.append("disk export: disk(s) %s" % fdsk)
12561

    
12562
      raise errors.OpExecError("Export failed, errors in %s" %
12563
                               utils.CommaJoin(failures))
12564

    
12565
    # At this point, the export was successful, we can cleanup/finish
12566

    
12567
    # Remove instance if requested
12568
    if self.op.remove_instance:
12569
      feedback_fn("Removing instance %s" % instance.name)
12570
      _RemoveInstance(self, feedback_fn, instance,
12571
                      self.op.ignore_remove_failures)
12572

    
12573
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
12574
      self._CleanupExports(feedback_fn)
12575

    
12576
    return fin_resu, dresults
12577

    
12578

    
12579
class LUBackupRemove(NoHooksLU):
12580
  """Remove exports related to the named instance.
12581

12582
  """
12583
  REQ_BGL = False
12584

    
12585
  def ExpandNames(self):
12586
    self.needed_locks = {}
12587
    # We need all nodes to be locked in order for RemoveExport to work, but we
12588
    # don't need to lock the instance itself, as nothing will happen to it (and
12589
    # we can remove exports also for a removed instance)
12590
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
12591

    
12592
  def Exec(self, feedback_fn):
12593
    """Remove any export.
12594

12595
    """
12596
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
12597
    # If the instance was not found we'll try with the name that was passed in.
12598
    # This will only work if it was an FQDN, though.
12599
    fqdn_warn = False
12600
    if not instance_name:
12601
      fqdn_warn = True
12602
      instance_name = self.op.instance_name
12603

    
12604
    locked_nodes = self.owned_locks(locking.LEVEL_NODE)
12605
    exportlist = self.rpc.call_export_list(locked_nodes)
12606
    found = False
12607
    for node in exportlist:
12608
      msg = exportlist[node].fail_msg
12609
      if msg:
12610
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
12611
        continue
12612
      if instance_name in exportlist[node].payload:
12613
        found = True
12614
        result = self.rpc.call_export_remove(node, instance_name)
12615
        msg = result.fail_msg
12616
        if msg:
12617
          logging.error("Could not remove export for instance %s"
12618
                        " on node %s: %s", instance_name, node, msg)
12619

    
12620
    if fqdn_warn and not found:
12621
      feedback_fn("Export not found. If trying to remove an export belonging"
12622
                  " to a deleted instance please use its Fully Qualified"
12623
                  " Domain Name.")
12624

    
12625

    
12626
class LUGroupAdd(LogicalUnit):
12627
  """Logical unit for creating node groups.
12628

12629
  """
12630
  HPATH = "group-add"
12631
  HTYPE = constants.HTYPE_GROUP
12632
  REQ_BGL = False
12633

    
12634
  def ExpandNames(self):
12635
    # We need the new group's UUID here so that we can create and acquire the
12636
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
12637
    # that it should not check whether the UUID exists in the configuration.
12638
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
12639
    self.needed_locks = {}
12640
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
12641

    
12642
  def CheckPrereq(self):
12643
    """Check prerequisites.
12644

12645
    This checks that the given group name is not an existing node group
12646
    already.
12647

12648
    """
12649
    try:
12650
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12651
    except errors.OpPrereqError:
12652
      pass
12653
    else:
12654
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
12655
                                 " node group (UUID: %s)" %
12656
                                 (self.op.group_name, existing_uuid),
12657
                                 errors.ECODE_EXISTS)
12658

    
12659
    if self.op.ndparams:
12660
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
12661

    
12662
    if self.op.diskparams:
12663
      for templ in constants.DISK_TEMPLATES:
12664
        if templ not in self.op.diskparams:
12665
          self.op.diskparams[templ] = {}
12666
        utils.ForceDictType(self.op.diskparams[templ], constants.DISK_DT_TYPES)
12667
    else:
12668
      self.op.diskparams = self.cfg.GetClusterInfo().diskparams
12669

    
12670
  def BuildHooksEnv(self):
12671
    """Build hooks env.
12672

12673
    """
12674
    return {
12675
      "GROUP_NAME": self.op.group_name,
12676
      }
12677

    
12678
  def BuildHooksNodes(self):
12679
    """Build hooks nodes.
12680

12681
    """
12682
    mn = self.cfg.GetMasterNode()
12683
    return ([mn], [mn])
12684

    
12685
  def Exec(self, feedback_fn):
12686
    """Add the node group to the cluster.
12687

12688
    """
12689
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
12690
                                  uuid=self.group_uuid,
12691
                                  alloc_policy=self.op.alloc_policy,
12692
                                  ndparams=self.op.ndparams,
12693
                                  diskparams=self.op.diskparams)
12694

    
12695
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
12696
    del self.remove_locks[locking.LEVEL_NODEGROUP]
12697

    
12698

    
12699
class LUGroupAssignNodes(NoHooksLU):
12700
  """Logical unit for assigning nodes to groups.
12701

12702
  """
12703
  REQ_BGL = False
12704

    
12705
  def ExpandNames(self):
12706
    # These raise errors.OpPrereqError on their own:
12707
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12708
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
12709

    
12710
    # We want to lock all the affected nodes and groups. We have readily
12711
    # available the list of nodes, and the *destination* group. To gather the
12712
    # list of "source" groups, we need to fetch node information later on.
12713
    self.needed_locks = {
12714
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
12715
      locking.LEVEL_NODE: self.op.nodes,
12716
      }
12717

    
12718
  def DeclareLocks(self, level):
12719
    if level == locking.LEVEL_NODEGROUP:
12720
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
12721

    
12722
      # Try to get all affected nodes' groups without having the group or node
12723
      # lock yet. Needs verification later in the code flow.
12724
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
12725

    
12726
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
12727

    
12728
  def CheckPrereq(self):
12729
    """Check prerequisites.
12730

12731
    """
12732
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
12733
    assert (frozenset(self.owned_locks(locking.LEVEL_NODE)) ==
12734
            frozenset(self.op.nodes))
12735

    
12736
    expected_locks = (set([self.group_uuid]) |
12737
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
12738
    actual_locks = self.owned_locks(locking.LEVEL_NODEGROUP)
12739
    if actual_locks != expected_locks:
12740
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
12741
                               " current groups are '%s', used to be '%s'" %
12742
                               (utils.CommaJoin(expected_locks),
12743
                                utils.CommaJoin(actual_locks)))
12744

    
12745
    self.node_data = self.cfg.GetAllNodesInfo()
12746
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
12747
    instance_data = self.cfg.GetAllInstancesInfo()
12748

    
12749
    if self.group is None:
12750
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
12751
                               (self.op.group_name, self.group_uuid))
12752

    
12753
    (new_splits, previous_splits) = \
12754
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
12755
                                             for node in self.op.nodes],
12756
                                            self.node_data, instance_data)
12757

    
12758
    if new_splits:
12759
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
12760

    
12761
      if not self.op.force:
12762
        raise errors.OpExecError("The following instances get split by this"
12763
                                 " change and --force was not given: %s" %
12764
                                 fmt_new_splits)
12765
      else:
12766
        self.LogWarning("This operation will split the following instances: %s",
12767
                        fmt_new_splits)
12768

    
12769
        if previous_splits:
12770
          self.LogWarning("In addition, these already-split instances continue"
12771
                          " to be split across groups: %s",
12772
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
12773

    
12774
  def Exec(self, feedback_fn):
12775
    """Assign nodes to a new group.
12776

12777
    """
12778
    mods = [(node_name, self.group_uuid) for node_name in self.op.nodes]
12779

    
12780
    self.cfg.AssignGroupNodes(mods)
12781

    
12782
  @staticmethod
12783
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
12784
    """Check for split instances after a node assignment.
12785

12786
    This method considers a series of node assignments as an atomic operation,
12787
    and returns information about split instances after applying the set of
12788
    changes.
12789

12790
    In particular, it returns information about newly split instances, and
12791
    instances that were already split, and remain so after the change.
12792

12793
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
12794
    considered.
12795

12796
    @type changes: list of (node_name, new_group_uuid) pairs.
12797
    @param changes: list of node assignments to consider.
12798
    @param node_data: a dict with data for all nodes
12799
    @param instance_data: a dict with all instances to consider
12800
    @rtype: a two-tuple
12801
    @return: a list of instances that were previously okay and result split as a
12802
      consequence of this change, and a list of instances that were previously
12803
      split and this change does not fix.
12804

12805
    """
12806
    changed_nodes = dict((node, group) for node, group in changes
12807
                         if node_data[node].group != group)
12808

    
12809
    all_split_instances = set()
12810
    previously_split_instances = set()
12811

    
12812
    def InstanceNodes(instance):
12813
      return [instance.primary_node] + list(instance.secondary_nodes)
12814

    
12815
    for inst in instance_data.values():
12816
      if inst.disk_template not in constants.DTS_INT_MIRROR:
12817
        continue
12818

    
12819
      instance_nodes = InstanceNodes(inst)
12820

    
12821
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
12822
        previously_split_instances.add(inst.name)
12823

    
12824
      if len(set(changed_nodes.get(node, node_data[node].group)
12825
                 for node in instance_nodes)) > 1:
12826
        all_split_instances.add(inst.name)
12827

    
12828
    return (list(all_split_instances - previously_split_instances),
12829
            list(previously_split_instances & all_split_instances))
12830

    
12831

    
12832
class _GroupQuery(_QueryBase):
12833
  FIELDS = query.GROUP_FIELDS
12834

    
12835
  def ExpandNames(self, lu):
12836
    lu.needed_locks = {}
12837

    
12838
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
12839
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
12840

    
12841
    if not self.names:
12842
      self.wanted = [name_to_uuid[name]
12843
                     for name in utils.NiceSort(name_to_uuid.keys())]
12844
    else:
12845
      # Accept names to be either names or UUIDs.
12846
      missing = []
12847
      self.wanted = []
12848
      all_uuid = frozenset(self._all_groups.keys())
12849

    
12850
      for name in self.names:
12851
        if name in all_uuid:
12852
          self.wanted.append(name)
12853
        elif name in name_to_uuid:
12854
          self.wanted.append(name_to_uuid[name])
12855
        else:
12856
          missing.append(name)
12857

    
12858
      if missing:
12859
        raise errors.OpPrereqError("Some groups do not exist: %s" %
12860
                                   utils.CommaJoin(missing),
12861
                                   errors.ECODE_NOENT)
12862

    
12863
  def DeclareLocks(self, lu, level):
12864
    pass
12865

    
12866
  def _GetQueryData(self, lu):
12867
    """Computes the list of node groups and their attributes.
12868

12869
    """
12870
    do_nodes = query.GQ_NODE in self.requested_data
12871
    do_instances = query.GQ_INST in self.requested_data
12872

    
12873
    group_to_nodes = None
12874
    group_to_instances = None
12875

    
12876
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
12877
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
12878
    # latter GetAllInstancesInfo() is not enough, for we have to go through
12879
    # instance->node. Hence, we will need to process nodes even if we only need
12880
    # instance information.
12881
    if do_nodes or do_instances:
12882
      all_nodes = lu.cfg.GetAllNodesInfo()
12883
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
12884
      node_to_group = {}
12885

    
12886
      for node in all_nodes.values():
12887
        if node.group in group_to_nodes:
12888
          group_to_nodes[node.group].append(node.name)
12889
          node_to_group[node.name] = node.group
12890

    
12891
      if do_instances:
12892
        all_instances = lu.cfg.GetAllInstancesInfo()
12893
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
12894

    
12895
        for instance in all_instances.values():
12896
          node = instance.primary_node
12897
          if node in node_to_group:
12898
            group_to_instances[node_to_group[node]].append(instance.name)
12899

    
12900
        if not do_nodes:
12901
          # Do not pass on node information if it was not requested.
12902
          group_to_nodes = None
12903

    
12904
    return query.GroupQueryData([self._all_groups[uuid]
12905
                                 for uuid in self.wanted],
12906
                                group_to_nodes, group_to_instances)
12907

    
12908

    
12909
class LUGroupQuery(NoHooksLU):
12910
  """Logical unit for querying node groups.
12911

12912
  """
12913
  REQ_BGL = False
12914

    
12915
  def CheckArguments(self):
12916
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
12917
                          self.op.output_fields, False)
12918

    
12919
  def ExpandNames(self):
12920
    self.gq.ExpandNames(self)
12921

    
12922
  def DeclareLocks(self, level):
12923
    self.gq.DeclareLocks(self, level)
12924

    
12925
  def Exec(self, feedback_fn):
12926
    return self.gq.OldStyleQuery(self)
12927

    
12928

    
12929
class LUGroupSetParams(LogicalUnit):
12930
  """Modifies the parameters of a node group.
12931

12932
  """
12933
  HPATH = "group-modify"
12934
  HTYPE = constants.HTYPE_GROUP
12935
  REQ_BGL = False
12936

    
12937
  def CheckArguments(self):
12938
    all_changes = [
12939
      self.op.ndparams,
12940
      self.op.diskparams,
12941
      self.op.alloc_policy,
12942
      ]
12943

    
12944
    if all_changes.count(None) == len(all_changes):
12945
      raise errors.OpPrereqError("Please pass at least one modification",
12946
                                 errors.ECODE_INVAL)
12947

    
12948
  def ExpandNames(self):
12949
    # This raises errors.OpPrereqError on its own:
12950
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
12951

    
12952
    self.needed_locks = {
12953
      locking.LEVEL_NODEGROUP: [self.group_uuid],
12954
      }
12955

    
12956
  def CheckPrereq(self):
12957
    """Check prerequisites.
12958

12959
    """
12960
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
12961

    
12962
    if self.group is None:
12963
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
12964
                               (self.op.group_name, self.group_uuid))
12965

    
12966
    if self.op.ndparams:
12967
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
12968
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
12969
      self.new_ndparams = new_ndparams
12970

    
12971
    if self.op.diskparams:
12972
      self.new_diskparams = dict()
12973
      for templ in constants.DISK_TEMPLATES:
12974
        if templ not in self.op.diskparams:
12975
          self.op.diskparams[templ] = {}
12976
        new_templ_params = _GetUpdatedParams(self.group.diskparams[templ],
12977
                                             self.op.diskparams[templ])
12978
        utils.ForceDictType(new_templ_params, constants.DISK_DT_TYPES)
12979
        self.new_diskparams[templ] = new_templ_params
12980

    
12981
  def BuildHooksEnv(self):
12982
    """Build hooks env.
12983

12984
    """
12985
    return {
12986
      "GROUP_NAME": self.op.group_name,
12987
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
12988
      }
12989

    
12990
  def BuildHooksNodes(self):
12991
    """Build hooks nodes.
12992

12993
    """
12994
    mn = self.cfg.GetMasterNode()
12995
    return ([mn], [mn])
12996

    
12997
  def Exec(self, feedback_fn):
12998
    """Modifies the node group.
12999

13000
    """
13001
    result = []
13002

    
13003
    if self.op.ndparams:
13004
      self.group.ndparams = self.new_ndparams
13005
      result.append(("ndparams", str(self.group.ndparams)))
13006

    
13007
    if self.op.diskparams:
13008
      self.group.diskparams = self.new_diskparams
13009
      result.append(("diskparams", str(self.group.diskparams)))
13010

    
13011
    if self.op.alloc_policy:
13012
      self.group.alloc_policy = self.op.alloc_policy
13013

    
13014
    self.cfg.Update(self.group, feedback_fn)
13015
    return result
13016

    
13017

    
13018
class LUGroupRemove(LogicalUnit):
13019
  HPATH = "group-remove"
13020
  HTYPE = constants.HTYPE_GROUP
13021
  REQ_BGL = False
13022

    
13023
  def ExpandNames(self):
13024
    # This will raises errors.OpPrereqError on its own:
13025
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
13026
    self.needed_locks = {
13027
      locking.LEVEL_NODEGROUP: [self.group_uuid],
13028
      }
13029

    
13030
  def CheckPrereq(self):
13031
    """Check prerequisites.
13032

13033
    This checks that the given group name exists as a node group, that is
13034
    empty (i.e., contains no nodes), and that is not the last group of the
13035
    cluster.
13036

13037
    """
13038
    # Verify that the group is empty.
13039
    group_nodes = [node.name
13040
                   for node in self.cfg.GetAllNodesInfo().values()
13041
                   if node.group == self.group_uuid]
13042

    
13043
    if group_nodes:
13044
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
13045
                                 " nodes: %s" %
13046
                                 (self.op.group_name,
13047
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
13048
                                 errors.ECODE_STATE)
13049

    
13050
    # Verify the cluster would not be left group-less.
13051
    if len(self.cfg.GetNodeGroupList()) == 1:
13052
      raise errors.OpPrereqError("Group '%s' is the only group,"
13053
                                 " cannot be removed" %
13054
                                 self.op.group_name,
13055
                                 errors.ECODE_STATE)
13056

    
13057
  def BuildHooksEnv(self):
13058
    """Build hooks env.
13059

13060
    """
13061
    return {
13062
      "GROUP_NAME": self.op.group_name,
13063
      }
13064

    
13065
  def BuildHooksNodes(self):
13066
    """Build hooks nodes.
13067

13068
    """
13069
    mn = self.cfg.GetMasterNode()
13070
    return ([mn], [mn])
13071

    
13072
  def Exec(self, feedback_fn):
13073
    """Remove the node group.
13074

13075
    """
13076
    try:
13077
      self.cfg.RemoveNodeGroup(self.group_uuid)
13078
    except errors.ConfigurationError:
13079
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
13080
                               (self.op.group_name, self.group_uuid))
13081

    
13082
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
13083

    
13084

    
13085
class LUGroupRename(LogicalUnit):
13086
  HPATH = "group-rename"
13087
  HTYPE = constants.HTYPE_GROUP
13088
  REQ_BGL = False
13089

    
13090
  def ExpandNames(self):
13091
    # This raises errors.OpPrereqError on its own:
13092
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
13093

    
13094
    self.needed_locks = {
13095
      locking.LEVEL_NODEGROUP: [self.group_uuid],
13096
      }
13097

    
13098
  def CheckPrereq(self):
13099
    """Check prerequisites.
13100

13101
    Ensures requested new name is not yet used.
13102

13103
    """
13104
    try:
13105
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
13106
    except errors.OpPrereqError:
13107
      pass
13108
    else:
13109
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
13110
                                 " node group (UUID: %s)" %
13111
                                 (self.op.new_name, new_name_uuid),
13112
                                 errors.ECODE_EXISTS)
13113

    
13114
  def BuildHooksEnv(self):
13115
    """Build hooks env.
13116

13117
    """
13118
    return {
13119
      "OLD_NAME": self.op.group_name,
13120
      "NEW_NAME": self.op.new_name,
13121
      }
13122

    
13123
  def BuildHooksNodes(self):
13124
    """Build hooks nodes.
13125

13126
    """
13127
    mn = self.cfg.GetMasterNode()
13128

    
13129
    all_nodes = self.cfg.GetAllNodesInfo()
13130
    all_nodes.pop(mn, None)
13131

    
13132
    run_nodes = [mn]
13133
    run_nodes.extend(node.name for node in all_nodes.values()
13134
                     if node.group == self.group_uuid)
13135

    
13136
    return (run_nodes, run_nodes)
13137

    
13138
  def Exec(self, feedback_fn):
13139
    """Rename the node group.
13140

13141
    """
13142
    group = self.cfg.GetNodeGroup(self.group_uuid)
13143

    
13144
    if group is None:
13145
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
13146
                               (self.op.group_name, self.group_uuid))
13147

    
13148
    group.name = self.op.new_name
13149
    self.cfg.Update(group, feedback_fn)
13150

    
13151
    return self.op.new_name
13152

    
13153

    
13154
class LUGroupEvacuate(LogicalUnit):
13155
  HPATH = "group-evacuate"
13156
  HTYPE = constants.HTYPE_GROUP
13157
  REQ_BGL = False
13158

    
13159
  def ExpandNames(self):
13160
    # This raises errors.OpPrereqError on its own:
13161
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
13162

    
13163
    if self.op.target_groups:
13164
      self.req_target_uuids = map(self.cfg.LookupNodeGroup,
13165
                                  self.op.target_groups)
13166
    else:
13167
      self.req_target_uuids = []
13168

    
13169
    if self.group_uuid in self.req_target_uuids:
13170
      raise errors.OpPrereqError("Group to be evacuated (%s) can not be used"
13171
                                 " as a target group (targets are %s)" %
13172
                                 (self.group_uuid,
13173
                                  utils.CommaJoin(self.req_target_uuids)),
13174
                                 errors.ECODE_INVAL)
13175

    
13176
    self.op.iallocator = _GetDefaultIAllocator(self.cfg, self.op.iallocator)
13177

    
13178
    self.share_locks = _ShareAll()
13179
    self.needed_locks = {
13180
      locking.LEVEL_INSTANCE: [],
13181
      locking.LEVEL_NODEGROUP: [],
13182
      locking.LEVEL_NODE: [],
13183
      }
13184

    
13185
  def DeclareLocks(self, level):
13186
    if level == locking.LEVEL_INSTANCE:
13187
      assert not self.needed_locks[locking.LEVEL_INSTANCE]
13188

    
13189
      # Lock instances optimistically, needs verification once node and group
13190
      # locks have been acquired
13191
      self.needed_locks[locking.LEVEL_INSTANCE] = \
13192
        self.cfg.GetNodeGroupInstances(self.group_uuid)
13193

    
13194
    elif level == locking.LEVEL_NODEGROUP:
13195
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
13196

    
13197
      if self.req_target_uuids:
13198
        lock_groups = set([self.group_uuid] + self.req_target_uuids)
13199

    
13200
        # Lock all groups used by instances optimistically; this requires going
13201
        # via the node before it's locked, requiring verification later on
13202
        lock_groups.update(group_uuid
13203
                           for instance_name in
13204
                             self.owned_locks(locking.LEVEL_INSTANCE)
13205
                           for group_uuid in
13206
                             self.cfg.GetInstanceNodeGroups(instance_name))
13207
      else:
13208
        # No target groups, need to lock all of them
13209
        lock_groups = locking.ALL_SET
13210

    
13211
      self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
13212

    
13213
    elif level == locking.LEVEL_NODE:
13214
      # This will only lock the nodes in the group to be evacuated which
13215
      # contain actual instances
13216
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
13217
      self._LockInstancesNodes()
13218

    
13219
      # Lock all nodes in group to be evacuated and target groups
13220
      owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
13221
      assert self.group_uuid in owned_groups
13222
      member_nodes = [node_name
13223
                      for group in owned_groups
13224
                      for node_name in self.cfg.GetNodeGroup(group).members]
13225
      self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
13226

    
13227
  def CheckPrereq(self):
13228
    owned_instances = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
13229
    owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
13230
    owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
13231

    
13232
    assert owned_groups.issuperset(self.req_target_uuids)
13233
    assert self.group_uuid in owned_groups
13234

    
13235
    # Check if locked instances are still correct
13236
    _CheckNodeGroupInstances(self.cfg, self.group_uuid, owned_instances)
13237

    
13238
    # Get instance information
13239
    self.instances = dict(self.cfg.GetMultiInstanceInfo(owned_instances))
13240

    
13241
    # Check if node groups for locked instances are still correct
13242
    for instance_name in owned_instances:
13243
      inst = self.instances[instance_name]
13244
      assert owned_nodes.issuperset(inst.all_nodes), \
13245
        "Instance %s's nodes changed while we kept the lock" % instance_name
13246

    
13247
      inst_groups = _CheckInstanceNodeGroups(self.cfg, instance_name,
13248
                                             owned_groups)
13249

    
13250
      assert self.group_uuid in inst_groups, \
13251
        "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
13252

    
13253
    if self.req_target_uuids:
13254
      # User requested specific target groups
13255
      self.target_uuids = self.req_target_uuids
13256
    else:
13257
      # All groups except the one to be evacuated are potential targets
13258
      self.target_uuids = [group_uuid for group_uuid in owned_groups
13259
                           if group_uuid != self.group_uuid]
13260

    
13261
      if not self.target_uuids:
13262
        raise errors.OpPrereqError("There are no possible target groups",
13263
                                   errors.ECODE_INVAL)
13264

    
13265
  def BuildHooksEnv(self):
13266
    """Build hooks env.
13267

13268
    """
13269
    return {
13270
      "GROUP_NAME": self.op.group_name,
13271
      "TARGET_GROUPS": " ".join(self.target_uuids),
13272
      }
13273

    
13274
  def BuildHooksNodes(self):
13275
    """Build hooks nodes.
13276

13277
    """
13278
    mn = self.cfg.GetMasterNode()
13279

    
13280
    assert self.group_uuid in self.owned_locks(locking.LEVEL_NODEGROUP)
13281

    
13282
    run_nodes = [mn] + self.cfg.GetNodeGroup(self.group_uuid).members
13283

    
13284
    return (run_nodes, run_nodes)
13285

    
13286
  def Exec(self, feedback_fn):
13287
    instances = list(self.owned_locks(locking.LEVEL_INSTANCE))
13288

    
13289
    assert self.group_uuid not in self.target_uuids
13290

    
13291
    ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
13292
                     instances=instances, target_groups=self.target_uuids)
13293

    
13294
    ial.Run(self.op.iallocator)
13295

    
13296
    if not ial.success:
13297
      raise errors.OpPrereqError("Can't compute group evacuation using"
13298
                                 " iallocator '%s': %s" %
13299
                                 (self.op.iallocator, ial.info),
13300
                                 errors.ECODE_NORES)
13301

    
13302
    jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
13303

    
13304
    self.LogInfo("Iallocator returned %s job(s) for evacuating node group %s",
13305
                 len(jobs), self.op.group_name)
13306

    
13307
    return ResultWithJobs(jobs)
13308

    
13309

    
13310
class TagsLU(NoHooksLU): # pylint: disable=W0223
13311
  """Generic tags LU.
13312

13313
  This is an abstract class which is the parent of all the other tags LUs.
13314

13315
  """
13316
  def ExpandNames(self):
13317
    self.group_uuid = None
13318
    self.needed_locks = {}
13319
    if self.op.kind == constants.TAG_NODE:
13320
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
13321
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
13322
    elif self.op.kind == constants.TAG_INSTANCE:
13323
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
13324
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
13325
    elif self.op.kind == constants.TAG_NODEGROUP:
13326
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
13327

    
13328
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
13329
    # not possible to acquire the BGL based on opcode parameters)
13330

    
13331
  def CheckPrereq(self):
13332
    """Check prerequisites.
13333

13334
    """
13335
    if self.op.kind == constants.TAG_CLUSTER:
13336
      self.target = self.cfg.GetClusterInfo()
13337
    elif self.op.kind == constants.TAG_NODE:
13338
      self.target = self.cfg.GetNodeInfo(self.op.name)
13339
    elif self.op.kind == constants.TAG_INSTANCE:
13340
      self.target = self.cfg.GetInstanceInfo(self.op.name)
13341
    elif self.op.kind == constants.TAG_NODEGROUP:
13342
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
13343
    else:
13344
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
13345
                                 str(self.op.kind), errors.ECODE_INVAL)
13346

    
13347

    
13348
class LUTagsGet(TagsLU):
13349
  """Returns the tags of a given object.
13350

13351
  """
13352
  REQ_BGL = False
13353

    
13354
  def ExpandNames(self):
13355
    TagsLU.ExpandNames(self)
13356

    
13357
    # Share locks as this is only a read operation
13358
    self.share_locks = _ShareAll()
13359

    
13360
  def Exec(self, feedback_fn):
13361
    """Returns the tag list.
13362

13363
    """
13364
    return list(self.target.GetTags())
13365

    
13366

    
13367
class LUTagsSearch(NoHooksLU):
13368
  """Searches the tags for a given pattern.
13369

13370
  """
13371
  REQ_BGL = False
13372

    
13373
  def ExpandNames(self):
13374
    self.needed_locks = {}
13375

    
13376
  def CheckPrereq(self):
13377
    """Check prerequisites.
13378

13379
    This checks the pattern passed for validity by compiling it.
13380

13381
    """
13382
    try:
13383
      self.re = re.compile(self.op.pattern)
13384
    except re.error, err:
13385
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
13386
                                 (self.op.pattern, err), errors.ECODE_INVAL)
13387

    
13388
  def Exec(self, feedback_fn):
13389
    """Returns the tag list.
13390

13391
    """
13392
    cfg = self.cfg
13393
    tgts = [("/cluster", cfg.GetClusterInfo())]
13394
    ilist = cfg.GetAllInstancesInfo().values()
13395
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
13396
    nlist = cfg.GetAllNodesInfo().values()
13397
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
13398
    tgts.extend(("/nodegroup/%s" % n.name, n)
13399
                for n in cfg.GetAllNodeGroupsInfo().values())
13400
    results = []
13401
    for path, target in tgts:
13402
      for tag in target.GetTags():
13403
        if self.re.search(tag):
13404
          results.append((path, tag))
13405
    return results
13406

    
13407

    
13408
class LUTagsSet(TagsLU):
13409
  """Sets a tag on a given object.
13410

13411
  """
13412
  REQ_BGL = False
13413

    
13414
  def CheckPrereq(self):
13415
    """Check prerequisites.
13416

13417
    This checks the type and length of the tag name and value.
13418

13419
    """
13420
    TagsLU.CheckPrereq(self)
13421
    for tag in self.op.tags:
13422
      objects.TaggableObject.ValidateTag(tag)
13423

    
13424
  def Exec(self, feedback_fn):
13425
    """Sets the tag.
13426

13427
    """
13428
    try:
13429
      for tag in self.op.tags:
13430
        self.target.AddTag(tag)
13431
    except errors.TagError, err:
13432
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
13433
    self.cfg.Update(self.target, feedback_fn)
13434

    
13435

    
13436
class LUTagsDel(TagsLU):
13437
  """Delete a list of tags from a given object.
13438

13439
  """
13440
  REQ_BGL = False
13441

    
13442
  def CheckPrereq(self):
13443
    """Check prerequisites.
13444

13445
    This checks that we have the given tag.
13446

13447
    """
13448
    TagsLU.CheckPrereq(self)
13449
    for tag in self.op.tags:
13450
      objects.TaggableObject.ValidateTag(tag)
13451
    del_tags = frozenset(self.op.tags)
13452
    cur_tags = self.target.GetTags()
13453

    
13454
    diff_tags = del_tags - cur_tags
13455
    if diff_tags:
13456
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
13457
      raise errors.OpPrereqError("Tag(s) %s not found" %
13458
                                 (utils.CommaJoin(diff_names), ),
13459
                                 errors.ECODE_NOENT)
13460

    
13461
  def Exec(self, feedback_fn):
13462
    """Remove the tag from the object.
13463

13464
    """
13465
    for tag in self.op.tags:
13466
      self.target.RemoveTag(tag)
13467
    self.cfg.Update(self.target, feedback_fn)
13468

    
13469

    
13470
class LUTestDelay(NoHooksLU):
13471
  """Sleep for a specified amount of time.
13472

13473
  This LU sleeps on the master and/or nodes for a specified amount of
13474
  time.
13475

13476
  """
13477
  REQ_BGL = False
13478

    
13479
  def ExpandNames(self):
13480
    """Expand names and set required locks.
13481

13482
    This expands the node list, if any.
13483

13484
    """
13485
    self.needed_locks = {}
13486
    if self.op.on_nodes:
13487
      # _GetWantedNodes can be used here, but is not always appropriate to use
13488
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
13489
      # more information.
13490
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
13491
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
13492

    
13493
  def _TestDelay(self):
13494
    """Do the actual sleep.
13495

13496
    """
13497
    if self.op.on_master:
13498
      if not utils.TestDelay(self.op.duration):
13499
        raise errors.OpExecError("Error during master delay test")
13500
    if self.op.on_nodes:
13501
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
13502
      for node, node_result in result.items():
13503
        node_result.Raise("Failure during rpc call to node %s" % node)
13504

    
13505
  def Exec(self, feedback_fn):
13506
    """Execute the test delay opcode, with the wanted repetitions.
13507

13508
    """
13509
    if self.op.repeat == 0:
13510
      self._TestDelay()
13511
    else:
13512
      top_value = self.op.repeat - 1
13513
      for i in range(self.op.repeat):
13514
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
13515
        self._TestDelay()
13516

    
13517

    
13518
class LUTestJqueue(NoHooksLU):
13519
  """Utility LU to test some aspects of the job queue.
13520

13521
  """
13522
  REQ_BGL = False
13523

    
13524
  # Must be lower than default timeout for WaitForJobChange to see whether it
13525
  # notices changed jobs
13526
  _CLIENT_CONNECT_TIMEOUT = 20.0
13527
  _CLIENT_CONFIRM_TIMEOUT = 60.0
13528

    
13529
  @classmethod
13530
  def _NotifyUsingSocket(cls, cb, errcls):
13531
    """Opens a Unix socket and waits for another program to connect.
13532

13533
    @type cb: callable
13534
    @param cb: Callback to send socket name to client
13535
    @type errcls: class
13536
    @param errcls: Exception class to use for errors
13537

13538
    """
13539
    # Using a temporary directory as there's no easy way to create temporary
13540
    # sockets without writing a custom loop around tempfile.mktemp and
13541
    # socket.bind
13542
    tmpdir = tempfile.mkdtemp()
13543
    try:
13544
      tmpsock = utils.PathJoin(tmpdir, "sock")
13545

    
13546
      logging.debug("Creating temporary socket at %s", tmpsock)
13547
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
13548
      try:
13549
        sock.bind(tmpsock)
13550
        sock.listen(1)
13551

    
13552
        # Send details to client
13553
        cb(tmpsock)
13554

    
13555
        # Wait for client to connect before continuing
13556
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
13557
        try:
13558
          (conn, _) = sock.accept()
13559
        except socket.error, err:
13560
          raise errcls("Client didn't connect in time (%s)" % err)
13561
      finally:
13562
        sock.close()
13563
    finally:
13564
      # Remove as soon as client is connected
13565
      shutil.rmtree(tmpdir)
13566

    
13567
    # Wait for client to close
13568
    try:
13569
      try:
13570
        # pylint: disable=E1101
13571
        # Instance of '_socketobject' has no ... member
13572
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
13573
        conn.recv(1)
13574
      except socket.error, err:
13575
        raise errcls("Client failed to confirm notification (%s)" % err)
13576
    finally:
13577
      conn.close()
13578

    
13579
  def _SendNotification(self, test, arg, sockname):
13580
    """Sends a notification to the client.
13581

13582
    @type test: string
13583
    @param test: Test name
13584
    @param arg: Test argument (depends on test)
13585
    @type sockname: string
13586
    @param sockname: Socket path
13587

13588
    """
13589
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
13590

    
13591
  def _Notify(self, prereq, test, arg):
13592
    """Notifies the client of a test.
13593

13594
    @type prereq: bool
13595
    @param prereq: Whether this is a prereq-phase test
13596
    @type test: string
13597
    @param test: Test name
13598
    @param arg: Test argument (depends on test)
13599

13600
    """
13601
    if prereq:
13602
      errcls = errors.OpPrereqError
13603
    else:
13604
      errcls = errors.OpExecError
13605

    
13606
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
13607
                                                  test, arg),
13608
                                   errcls)
13609

    
13610
  def CheckArguments(self):
13611
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
13612
    self.expandnames_calls = 0
13613

    
13614
  def ExpandNames(self):
13615
    checkargs_calls = getattr(self, "checkargs_calls", 0)
13616
    if checkargs_calls < 1:
13617
      raise errors.ProgrammerError("CheckArguments was not called")
13618

    
13619
    self.expandnames_calls += 1
13620

    
13621
    if self.op.notify_waitlock:
13622
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
13623

    
13624
    self.LogInfo("Expanding names")
13625

    
13626
    # Get lock on master node (just to get a lock, not for a particular reason)
13627
    self.needed_locks = {
13628
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
13629
      }
13630

    
13631
  def Exec(self, feedback_fn):
13632
    if self.expandnames_calls < 1:
13633
      raise errors.ProgrammerError("ExpandNames was not called")
13634

    
13635
    if self.op.notify_exec:
13636
      self._Notify(False, constants.JQT_EXEC, None)
13637

    
13638
    self.LogInfo("Executing")
13639

    
13640
    if self.op.log_messages:
13641
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
13642
      for idx, msg in enumerate(self.op.log_messages):
13643
        self.LogInfo("Sending log message %s", idx + 1)
13644
        feedback_fn(constants.JQT_MSGPREFIX + msg)
13645
        # Report how many test messages have been sent
13646
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
13647

    
13648
    if self.op.fail:
13649
      raise errors.OpExecError("Opcode failure was requested")
13650

    
13651
    return True
13652

    
13653

    
13654
class IAllocator(object):
13655
  """IAllocator framework.
13656

13657
  An IAllocator instance has three sets of attributes:
13658
    - cfg that is needed to query the cluster
13659
    - input data (all members of the _KEYS class attribute are required)
13660
    - four buffer attributes (in|out_data|text), that represent the
13661
      input (to the external script) in text and data structure format,
13662
      and the output from it, again in two formats
13663
    - the result variables from the script (success, info, nodes) for
13664
      easy usage
13665

13666
  """
13667
  # pylint: disable=R0902
13668
  # lots of instance attributes
13669

    
13670
  def __init__(self, cfg, rpc_runner, mode, **kwargs):
13671
    self.cfg = cfg
13672
    self.rpc = rpc_runner
13673
    # init buffer variables
13674
    self.in_text = self.out_text = self.in_data = self.out_data = None
13675
    # init all input fields so that pylint is happy
13676
    self.mode = mode
13677
    self.memory = self.disks = self.disk_template = None
13678
    self.os = self.tags = self.nics = self.vcpus = None
13679
    self.hypervisor = None
13680
    self.relocate_from = None
13681
    self.name = None
13682
    self.instances = None
13683
    self.evac_mode = None
13684
    self.target_groups = []
13685
    # computed fields
13686
    self.required_nodes = None
13687
    # init result fields
13688
    self.success = self.info = self.result = None
13689

    
13690
    try:
13691
      (fn, keydata, self._result_check) = self._MODE_DATA[self.mode]
13692
    except KeyError:
13693
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
13694
                                   " IAllocator" % self.mode)
13695

    
13696
    keyset = [n for (n, _) in keydata]
13697

    
13698
    for key in kwargs:
13699
      if key not in keyset:
13700
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
13701
                                     " IAllocator" % key)
13702
      setattr(self, key, kwargs[key])
13703

    
13704
    for key in keyset:
13705
      if key not in kwargs:
13706
        raise errors.ProgrammerError("Missing input parameter '%s' to"
13707
                                     " IAllocator" % key)
13708
    self._BuildInputData(compat.partial(fn, self), keydata)
13709

    
13710
  def _ComputeClusterData(self):
13711
    """Compute the generic allocator input data.
13712

13713
    This is the data that is independent of the actual operation.
13714

13715
    """
13716
    cfg = self.cfg
13717
    cluster_info = cfg.GetClusterInfo()
13718
    # cluster data
13719
    data = {
13720
      "version": constants.IALLOCATOR_VERSION,
13721
      "cluster_name": cfg.GetClusterName(),
13722
      "cluster_tags": list(cluster_info.GetTags()),
13723
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
13724
      # we don't have job IDs
13725
      }
13726
    ninfo = cfg.GetAllNodesInfo()
13727
    iinfo = cfg.GetAllInstancesInfo().values()
13728
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
13729

    
13730
    # node data
13731
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
13732

    
13733
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
13734
      hypervisor_name = self.hypervisor
13735
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
13736
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
13737
    else:
13738
      hypervisor_name = cluster_info.primary_hypervisor
13739

    
13740
    node_data = self.rpc.call_node_info(node_list, [cfg.GetVGName()],
13741
                                        [hypervisor_name])
13742
    node_iinfo = \
13743
      self.rpc.call_all_instances_info(node_list,
13744
                                       cluster_info.enabled_hypervisors)
13745

    
13746
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
13747

    
13748
    config_ndata = self._ComputeBasicNodeData(ninfo)
13749
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
13750
                                                 i_list, config_ndata)
13751
    assert len(data["nodes"]) == len(ninfo), \
13752
        "Incomplete node data computed"
13753

    
13754
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
13755

    
13756
    self.in_data = data
13757

    
13758
  @staticmethod
13759
  def _ComputeNodeGroupData(cfg):
13760
    """Compute node groups data.
13761

13762
    """
13763
    ng = dict((guuid, {
13764
      "name": gdata.name,
13765
      "alloc_policy": gdata.alloc_policy,
13766
      })
13767
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
13768

    
13769
    return ng
13770

    
13771
  @staticmethod
13772
  def _ComputeBasicNodeData(node_cfg):
13773
    """Compute global node data.
13774

13775
    @rtype: dict
13776
    @returns: a dict of name: (node dict, node config)
13777

13778
    """
13779
    # fill in static (config-based) values
13780
    node_results = dict((ninfo.name, {
13781
      "tags": list(ninfo.GetTags()),
13782
      "primary_ip": ninfo.primary_ip,
13783
      "secondary_ip": ninfo.secondary_ip,
13784
      "offline": ninfo.offline,
13785
      "drained": ninfo.drained,
13786
      "master_candidate": ninfo.master_candidate,
13787
      "group": ninfo.group,
13788
      "master_capable": ninfo.master_capable,
13789
      "vm_capable": ninfo.vm_capable,
13790
      })
13791
      for ninfo in node_cfg.values())
13792

    
13793
    return node_results
13794

    
13795
  @staticmethod
13796
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
13797
                              node_results):
13798
    """Compute global node data.
13799

13800
    @param node_results: the basic node structures as filled from the config
13801

13802
    """
13803
    #TODO(dynmem): compute the right data on MAX and MIN memory
13804
    # make a copy of the current dict
13805
    node_results = dict(node_results)
13806
    for nname, nresult in node_data.items():
13807
      assert nname in node_results, "Missing basic data for node %s" % nname
13808
      ninfo = node_cfg[nname]
13809

    
13810
      if not (ninfo.offline or ninfo.drained):
13811
        nresult.Raise("Can't get data for node %s" % nname)
13812
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
13813
                                nname)
13814
        remote_info = _MakeLegacyNodeInfo(nresult.payload)
13815

    
13816
        for attr in ["memory_total", "memory_free", "memory_dom0",
13817
                     "vg_size", "vg_free", "cpu_total"]:
13818
          if attr not in remote_info:
13819
            raise errors.OpExecError("Node '%s' didn't return attribute"
13820
                                     " '%s'" % (nname, attr))
13821
          if not isinstance(remote_info[attr], int):
13822
            raise errors.OpExecError("Node '%s' returned invalid value"
13823
                                     " for '%s': %s" %
13824
                                     (nname, attr, remote_info[attr]))
13825
        # compute memory used by primary instances
13826
        i_p_mem = i_p_up_mem = 0
13827
        for iinfo, beinfo in i_list:
13828
          if iinfo.primary_node == nname:
13829
            i_p_mem += beinfo[constants.BE_MAXMEM]
13830
            if iinfo.name not in node_iinfo[nname].payload:
13831
              i_used_mem = 0
13832
            else:
13833
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]["memory"])
13834
            i_mem_diff = beinfo[constants.BE_MAXMEM] - i_used_mem
13835
            remote_info["memory_free"] -= max(0, i_mem_diff)
13836

    
13837
            if iinfo.admin_state == constants.ADMINST_UP:
13838
              i_p_up_mem += beinfo[constants.BE_MAXMEM]
13839

    
13840
        # compute memory used by instances
13841
        pnr_dyn = {
13842
          "total_memory": remote_info["memory_total"],
13843
          "reserved_memory": remote_info["memory_dom0"],
13844
          "free_memory": remote_info["memory_free"],
13845
          "total_disk": remote_info["vg_size"],
13846
          "free_disk": remote_info["vg_free"],
13847
          "total_cpus": remote_info["cpu_total"],
13848
          "i_pri_memory": i_p_mem,
13849
          "i_pri_up_memory": i_p_up_mem,
13850
          }
13851
        pnr_dyn.update(node_results[nname])
13852
        node_results[nname] = pnr_dyn
13853

    
13854
    return node_results
13855

    
13856
  @staticmethod
13857
  def _ComputeInstanceData(cluster_info, i_list):
13858
    """Compute global instance data.
13859

13860
    """
13861
    instance_data = {}
13862
    for iinfo, beinfo in i_list:
13863
      nic_data = []
13864
      for nic in iinfo.nics:
13865
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
13866
        nic_dict = {
13867
          "mac": nic.mac,
13868
          "ip": nic.ip,
13869
          "mode": filled_params[constants.NIC_MODE],
13870
          "link": filled_params[constants.NIC_LINK],
13871
          }
13872
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
13873
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
13874
        nic_data.append(nic_dict)
13875
      pir = {
13876
        "tags": list(iinfo.GetTags()),
13877
        "admin_state": iinfo.admin_state,
13878
        "vcpus": beinfo[constants.BE_VCPUS],
13879
        "memory": beinfo[constants.BE_MAXMEM],
13880
        "os": iinfo.os,
13881
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
13882
        "nics": nic_data,
13883
        "disks": [{constants.IDISK_SIZE: dsk.size,
13884
                   constants.IDISK_MODE: dsk.mode}
13885
                  for dsk in iinfo.disks],
13886
        "disk_template": iinfo.disk_template,
13887
        "hypervisor": iinfo.hypervisor,
13888
        }
13889
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
13890
                                                 pir["disks"])
13891
      instance_data[iinfo.name] = pir
13892

    
13893
    return instance_data
13894

    
13895
  def _AddNewInstance(self):
13896
    """Add new instance data to allocator structure.
13897

13898
    This in combination with _AllocatorGetClusterData will create the
13899
    correct structure needed as input for the allocator.
13900

13901
    The checks for the completeness of the opcode must have already been
13902
    done.
13903

13904
    """
13905
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
13906

    
13907
    if self.disk_template in constants.DTS_INT_MIRROR:
13908
      self.required_nodes = 2
13909
    else:
13910
      self.required_nodes = 1
13911

    
13912
    request = {
13913
      "name": self.name,
13914
      "disk_template": self.disk_template,
13915
      "tags": self.tags,
13916
      "os": self.os,
13917
      "vcpus": self.vcpus,
13918
      "memory": self.memory,
13919
      "disks": self.disks,
13920
      "disk_space_total": disk_space,
13921
      "nics": self.nics,
13922
      "required_nodes": self.required_nodes,
13923
      "hypervisor": self.hypervisor,
13924
      }
13925

    
13926
    return request
13927

    
13928
  def _AddRelocateInstance(self):
13929
    """Add relocate instance data to allocator structure.
13930

13931
    This in combination with _IAllocatorGetClusterData will create the
13932
    correct structure needed as input for the allocator.
13933

13934
    The checks for the completeness of the opcode must have already been
13935
    done.
13936

13937
    """
13938
    instance = self.cfg.GetInstanceInfo(self.name)
13939
    if instance is None:
13940
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
13941
                                   " IAllocator" % self.name)
13942

    
13943
    if instance.disk_template not in constants.DTS_MIRRORED:
13944
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
13945
                                 errors.ECODE_INVAL)
13946

    
13947
    if instance.disk_template in constants.DTS_INT_MIRROR and \
13948
        len(instance.secondary_nodes) != 1:
13949
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
13950
                                 errors.ECODE_STATE)
13951

    
13952
    self.required_nodes = 1
13953
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
13954
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
13955

    
13956
    request = {
13957
      "name": self.name,
13958
      "disk_space_total": disk_space,
13959
      "required_nodes": self.required_nodes,
13960
      "relocate_from": self.relocate_from,
13961
      }
13962
    return request
13963

    
13964
  def _AddNodeEvacuate(self):
13965
    """Get data for node-evacuate requests.
13966

13967
    """
13968
    return {
13969
      "instances": self.instances,
13970
      "evac_mode": self.evac_mode,
13971
      }
13972

    
13973
  def _AddChangeGroup(self):
13974
    """Get data for node-evacuate requests.
13975

13976
    """
13977
    return {
13978
      "instances": self.instances,
13979
      "target_groups": self.target_groups,
13980
      }
13981

    
13982
  def _BuildInputData(self, fn, keydata):
13983
    """Build input data structures.
13984

13985
    """
13986
    self._ComputeClusterData()
13987

    
13988
    request = fn()
13989
    request["type"] = self.mode
13990
    for keyname, keytype in keydata:
13991
      if keyname not in request:
13992
        raise errors.ProgrammerError("Request parameter %s is missing" %
13993
                                     keyname)
13994
      val = request[keyname]
13995
      if not keytype(val):
13996
        raise errors.ProgrammerError("Request parameter %s doesn't pass"
13997
                                     " validation, value %s, expected"
13998
                                     " type %s" % (keyname, val, keytype))
13999
    self.in_data["request"] = request
14000

    
14001
    self.in_text = serializer.Dump(self.in_data)
14002

    
14003
  _STRING_LIST = ht.TListOf(ht.TString)
14004
  _JOB_LIST = ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
14005
     # pylint: disable=E1101
14006
     # Class '...' has no 'OP_ID' member
14007
     "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
14008
                          opcodes.OpInstanceMigrate.OP_ID,
14009
                          opcodes.OpInstanceReplaceDisks.OP_ID])
14010
     })))
14011

    
14012
  _NEVAC_MOVED = \
14013
    ht.TListOf(ht.TAnd(ht.TIsLength(3),
14014
                       ht.TItems([ht.TNonEmptyString,
14015
                                  ht.TNonEmptyString,
14016
                                  ht.TListOf(ht.TNonEmptyString),
14017
                                 ])))
14018
  _NEVAC_FAILED = \
14019
    ht.TListOf(ht.TAnd(ht.TIsLength(2),
14020
                       ht.TItems([ht.TNonEmptyString,
14021
                                  ht.TMaybeString,
14022
                                 ])))
14023
  _NEVAC_RESULT = ht.TAnd(ht.TIsLength(3),
14024
                          ht.TItems([_NEVAC_MOVED, _NEVAC_FAILED, _JOB_LIST]))
14025

    
14026
  _MODE_DATA = {
14027
    constants.IALLOCATOR_MODE_ALLOC:
14028
      (_AddNewInstance,
14029
       [
14030
        ("name", ht.TString),
14031
        ("memory", ht.TInt),
14032
        ("disks", ht.TListOf(ht.TDict)),
14033
        ("disk_template", ht.TString),
14034
        ("os", ht.TString),
14035
        ("tags", _STRING_LIST),
14036
        ("nics", ht.TListOf(ht.TDict)),
14037
        ("vcpus", ht.TInt),
14038
        ("hypervisor", ht.TString),
14039
        ], ht.TList),
14040
    constants.IALLOCATOR_MODE_RELOC:
14041
      (_AddRelocateInstance,
14042
       [("name", ht.TString), ("relocate_from", _STRING_LIST)],
14043
       ht.TList),
14044
     constants.IALLOCATOR_MODE_NODE_EVAC:
14045
      (_AddNodeEvacuate, [
14046
        ("instances", _STRING_LIST),
14047
        ("evac_mode", ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)),
14048
        ], _NEVAC_RESULT),
14049
     constants.IALLOCATOR_MODE_CHG_GROUP:
14050
      (_AddChangeGroup, [
14051
        ("instances", _STRING_LIST),
14052
        ("target_groups", _STRING_LIST),
14053
        ], _NEVAC_RESULT),
14054
    }
14055

    
14056
  def Run(self, name, validate=True, call_fn=None):
14057
    """Run an instance allocator and return the results.
14058

14059
    """
14060
    if call_fn is None:
14061
      call_fn = self.rpc.call_iallocator_runner
14062

    
14063
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
14064
    result.Raise("Failure while running the iallocator script")
14065

    
14066
    self.out_text = result.payload
14067
    if validate:
14068
      self._ValidateResult()
14069

    
14070
  def _ValidateResult(self):
14071
    """Process the allocator results.
14072

14073
    This will process and if successful save the result in
14074
    self.out_data and the other parameters.
14075

14076
    """
14077
    try:
14078
      rdict = serializer.Load(self.out_text)
14079
    except Exception, err:
14080
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
14081

    
14082
    if not isinstance(rdict, dict):
14083
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
14084

    
14085
    # TODO: remove backwards compatiblity in later versions
14086
    if "nodes" in rdict and "result" not in rdict:
14087
      rdict["result"] = rdict["nodes"]
14088
      del rdict["nodes"]
14089

    
14090
    for key in "success", "info", "result":
14091
      if key not in rdict:
14092
        raise errors.OpExecError("Can't parse iallocator results:"
14093
                                 " missing key '%s'" % key)
14094
      setattr(self, key, rdict[key])
14095

    
14096
    if not self._result_check(self.result):
14097
      raise errors.OpExecError("Iallocator returned invalid result,"
14098
                               " expected %s, got %s" %
14099
                               (self._result_check, self.result),
14100
                               errors.ECODE_INVAL)
14101

    
14102
    if self.mode == constants.IALLOCATOR_MODE_RELOC:
14103
      assert self.relocate_from is not None
14104
      assert self.required_nodes == 1
14105

    
14106
      node2group = dict((name, ndata["group"])
14107
                        for (name, ndata) in self.in_data["nodes"].items())
14108

    
14109
      fn = compat.partial(self._NodesToGroups, node2group,
14110
                          self.in_data["nodegroups"])
14111

    
14112
      instance = self.cfg.GetInstanceInfo(self.name)
14113
      request_groups = fn(self.relocate_from + [instance.primary_node])
14114
      result_groups = fn(rdict["result"] + [instance.primary_node])
14115

    
14116
      if self.success and not set(result_groups).issubset(request_groups):
14117
        raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
14118
                                 " differ from original groups (%s)" %
14119
                                 (utils.CommaJoin(result_groups),
14120
                                  utils.CommaJoin(request_groups)))
14121

    
14122
    elif self.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
14123
      assert self.evac_mode in constants.IALLOCATOR_NEVAC_MODES
14124

    
14125
    self.out_data = rdict
14126

    
14127
  @staticmethod
14128
  def _NodesToGroups(node2group, groups, nodes):
14129
    """Returns a list of unique group names for a list of nodes.
14130

14131
    @type node2group: dict
14132
    @param node2group: Map from node name to group UUID
14133
    @type groups: dict
14134
    @param groups: Group information
14135
    @type nodes: list
14136
    @param nodes: Node names
14137

14138
    """
14139
    result = set()
14140

    
14141
    for node in nodes:
14142
      try:
14143
        group_uuid = node2group[node]
14144
      except KeyError:
14145
        # Ignore unknown node
14146
        pass
14147
      else:
14148
        try:
14149
          group = groups[group_uuid]
14150
        except KeyError:
14151
          # Can't find group, let's use UUID
14152
          group_name = group_uuid
14153
        else:
14154
          group_name = group["name"]
14155

    
14156
        result.add(group_name)
14157

    
14158
    return sorted(result)
14159

    
14160

    
14161
class LUTestAllocator(NoHooksLU):
14162
  """Run allocator tests.
14163

14164
  This LU runs the allocator tests
14165

14166
  """
14167
  def CheckPrereq(self):
14168
    """Check prerequisites.
14169

14170
    This checks the opcode parameters depending on the director and mode test.
14171

14172
    """
14173
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
14174
      for attr in ["memory", "disks", "disk_template",
14175
                   "os", "tags", "nics", "vcpus"]:
14176
        if not hasattr(self.op, attr):
14177
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
14178
                                     attr, errors.ECODE_INVAL)
14179
      iname = self.cfg.ExpandInstanceName(self.op.name)
14180
      if iname is not None:
14181
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
14182
                                   iname, errors.ECODE_EXISTS)
14183
      if not isinstance(self.op.nics, list):
14184
        raise errors.OpPrereqError("Invalid parameter 'nics'",
14185
                                   errors.ECODE_INVAL)
14186
      if not isinstance(self.op.disks, list):
14187
        raise errors.OpPrereqError("Invalid parameter 'disks'",
14188
                                   errors.ECODE_INVAL)
14189
      for row in self.op.disks:
14190
        if (not isinstance(row, dict) or
14191
            constants.IDISK_SIZE not in row or
14192
            not isinstance(row[constants.IDISK_SIZE], int) or
14193
            constants.IDISK_MODE not in row or
14194
            row[constants.IDISK_MODE] not in constants.DISK_ACCESS_SET):
14195
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
14196
                                     " parameter", errors.ECODE_INVAL)
14197
      if self.op.hypervisor is None:
14198
        self.op.hypervisor = self.cfg.GetHypervisorType()
14199
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
14200
      fname = _ExpandInstanceName(self.cfg, self.op.name)
14201
      self.op.name = fname
14202
      self.relocate_from = \
14203
          list(self.cfg.GetInstanceInfo(fname).secondary_nodes)
14204
    elif self.op.mode in (constants.IALLOCATOR_MODE_CHG_GROUP,
14205
                          constants.IALLOCATOR_MODE_NODE_EVAC):
14206
      if not self.op.instances:
14207
        raise errors.OpPrereqError("Missing instances", errors.ECODE_INVAL)
14208
      self.op.instances = _GetWantedInstances(self, self.op.instances)
14209
    else:
14210
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
14211
                                 self.op.mode, errors.ECODE_INVAL)
14212

    
14213
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
14214
      if self.op.allocator is None:
14215
        raise errors.OpPrereqError("Missing allocator name",
14216
                                   errors.ECODE_INVAL)
14217
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
14218
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
14219
                                 self.op.direction, errors.ECODE_INVAL)
14220

    
14221
  def Exec(self, feedback_fn):
14222
    """Run the allocator test.
14223

14224
    """
14225
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
14226
      ial = IAllocator(self.cfg, self.rpc,
14227
                       mode=self.op.mode,
14228
                       name=self.op.name,
14229
                       memory=self.op.memory,
14230
                       disks=self.op.disks,
14231
                       disk_template=self.op.disk_template,
14232
                       os=self.op.os,
14233
                       tags=self.op.tags,
14234
                       nics=self.op.nics,
14235
                       vcpus=self.op.vcpus,
14236
                       hypervisor=self.op.hypervisor,
14237
                       )
14238
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
14239
      ial = IAllocator(self.cfg, self.rpc,
14240
                       mode=self.op.mode,
14241
                       name=self.op.name,
14242
                       relocate_from=list(self.relocate_from),
14243
                       )
14244
    elif self.op.mode == constants.IALLOCATOR_MODE_CHG_GROUP:
14245
      ial = IAllocator(self.cfg, self.rpc,
14246
                       mode=self.op.mode,
14247
                       instances=self.op.instances,
14248
                       target_groups=self.op.target_groups)
14249
    elif self.op.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
14250
      ial = IAllocator(self.cfg, self.rpc,
14251
                       mode=self.op.mode,
14252
                       instances=self.op.instances,
14253
                       evac_mode=self.op.evac_mode)
14254
    else:
14255
      raise errors.ProgrammerError("Uncatched mode %s in"
14256
                                   " LUTestAllocator.Exec", self.op.mode)
14257

    
14258
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
14259
      result = ial.in_text
14260
    else:
14261
      ial.Run(self.op.allocator, validate=False)
14262
      result = ial.out_text
14263
    return result
14264

    
14265

    
14266
#: Query type implementations
14267
_QUERY_IMPL = {
14268
  constants.QR_INSTANCE: _InstanceQuery,
14269
  constants.QR_NODE: _NodeQuery,
14270
  constants.QR_GROUP: _GroupQuery,
14271
  constants.QR_OS: _OsQuery,
14272
  }
14273

    
14274
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
14275

    
14276

    
14277
def _GetQueryImplementation(name):
14278
  """Returns the implemtnation for a query type.
14279

14280
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
14281

14282
  """
14283
  try:
14284
    return _QUERY_IMPL[name]
14285
  except KeyError:
14286
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
14287
                               errors.ECODE_INVAL)