Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 31a5d995

History | View | Annotate | Download (384.8 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
63

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

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

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

    
76

    
77
# End types
78
class LogicalUnit(object):
79
  """Logical Unit base class.
80

81
  Subclasses must follow these rules:
82
    - implement ExpandNames
83
    - implement CheckPrereq (except when tasklets are used)
84
    - implement Exec (except when tasklets are used)
85
    - implement BuildHooksEnv
86
    - redefine HPATH and HTYPE
87
    - optionally redefine their run requirements:
88
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
89

90
  Note that all commands require root permissions.
91

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

95
  """
96
  HPATH = None
97
  HTYPE = None
98
  REQ_BGL = True
99

    
100
  def __init__(self, processor, op, context, rpc):
101
    """Constructor for LogicalUnit.
102

103
    This needs to be overridden in derived classes in order to check op
104
    validity.
105

106
    """
107
    self.proc = processor
108
    self.op = op
109
    self.cfg = context.cfg
110
    self.context = context
111
    self.rpc = rpc
112
    # Dicts used to declare locking needs to mcpu
113
    self.needed_locks = None
114
    self.acquired_locks = {}
115
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
116
    self.add_locks = {}
117
    self.remove_locks = {}
118
    # Used to force good behavior when calling helper functions
119
    self.recalculate_locks = {}
120
    self.__ssh = None
121
    # logging
122
    self.Log = processor.Log # pylint: disable-msg=C0103
123
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
124
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
125
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
126
    # support for dry-run
127
    self.dry_run_result = None
128
    # support for generic debug attribute
129
    if (not hasattr(self.op, "debug_level") or
130
        not isinstance(self.op.debug_level, int)):
131
      self.op.debug_level = 0
132

    
133
    # Tasklets
134
    self.tasklets = None
135

    
136
    # Validate opcode parameters and set defaults
137
    self.op.Validate(True)
138

    
139
    self.CheckArguments()
140

    
141
  def __GetSSH(self):
142
    """Returns the SshRunner object
143

144
    """
145
    if not self.__ssh:
146
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
147
    return self.__ssh
148

    
149
  ssh = property(fget=__GetSSH)
150

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

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

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

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

166
    """
167
    pass
168

    
169
  def ExpandNames(self):
170
    """Expand names for this LU.
171

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

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

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

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

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

194
    Examples::
195

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

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

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

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

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

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

233
    """
234

    
235
  def CheckPrereq(self):
236
    """Check prerequisites for this LU.
237

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

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

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

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

    
258
  def Exec(self, feedback_fn):
259
    """Execute the LU.
260

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

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

    
273
  def BuildHooksEnv(self):
274
    """Build hooks environment for this LU.
275

276
    This method should return a three-node tuple consisting of: a dict
277
    containing the environment that will be used for running the
278
    specific hook for this LU, a list of node names on which the hook
279
    should run before the execution, and a list of node names on which
280
    the hook should run after the execution.
281

282
    The keys of the dict must not have 'GANETI_' prefixed as this will
283
    be handled in the hooks runner. Also note additional keys will be
284
    added by the hooks runner. If the LU doesn't define any
285
    environment, an empty dict (and not None) should be returned.
286

287
    No nodes should be returned as an empty list (and not None).
288

289
    Note that if the HPATH for a LU class is None, this function will
290
    not be called.
291

292
    """
293
    raise NotImplementedError
294

    
295
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
296
    """Notify the LU about the results of its hooks.
297

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

304
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
305
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
306
    @param hook_results: the results of the multi-node hooks rpc call
307
    @param feedback_fn: function used send feedback back to the caller
308
    @param lu_result: the previous Exec result this LU had, or None
309
        in the PRE phase
310
    @return: the new Exec result, based on the previous result
311
        and hook results
312

313
    """
314
    # API must be kept, thus we ignore the unused argument and could
315
    # be a function warnings
316
    # pylint: disable-msg=W0613,R0201
317
    return lu_result
318

    
319
  def _ExpandAndLockInstance(self):
320
    """Helper function to expand and lock an instance.
321

322
    Many LUs that work on an instance take its name in self.op.instance_name
323
    and need to expand it and then declare the expanded name for locking. This
324
    function does it, and then updates self.op.instance_name to the expanded
325
    name. It also initializes needed_locks as a dict, if this hasn't been done
326
    before.
327

328
    """
329
    if self.needed_locks is None:
330
      self.needed_locks = {}
331
    else:
332
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
333
        "_ExpandAndLockInstance called with instance-level locks set"
334
    self.op.instance_name = _ExpandInstanceName(self.cfg,
335
                                                self.op.instance_name)
336
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
337

    
338
  def _LockInstancesNodes(self, primary_only=False):
339
    """Helper function to declare instances' nodes for locking.
340

341
    This function should be called after locking one or more instances to lock
342
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
343
    with all primary or secondary nodes for instances already locked and
344
    present in self.needed_locks[locking.LEVEL_INSTANCE].
345

346
    It should be called from DeclareLocks, and for safety only works if
347
    self.recalculate_locks[locking.LEVEL_NODE] is set.
348

349
    In the future it may grow parameters to just lock some instance's nodes, or
350
    to just lock primaries or secondary nodes, if needed.
351

352
    If should be called in DeclareLocks in a way similar to::
353

354
      if level == locking.LEVEL_NODE:
355
        self._LockInstancesNodes()
356

357
    @type primary_only: boolean
358
    @param primary_only: only lock primary nodes of locked instances
359

360
    """
361
    assert locking.LEVEL_NODE in self.recalculate_locks, \
362
      "_LockInstancesNodes helper function called with no nodes to recalculate"
363

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

    
366
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
367
    # future we might want to have different behaviors depending on the value
368
    # of self.recalculate_locks[locking.LEVEL_NODE]
369
    wanted_nodes = []
370
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
371
      instance = self.context.cfg.GetInstanceInfo(instance_name)
372
      wanted_nodes.append(instance.primary_node)
373
      if not primary_only:
374
        wanted_nodes.extend(instance.secondary_nodes)
375

    
376
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
377
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
378
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
379
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
380

    
381
    del self.recalculate_locks[locking.LEVEL_NODE]
382

    
383

    
384
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
385
  """Simple LU which runs no hooks.
386

387
  This LU is intended as a parent for other LogicalUnits which will
388
  run no hooks, in order to reduce duplicate code.
389

390
  """
391
  HPATH = None
392
  HTYPE = None
393

    
394
  def BuildHooksEnv(self):
395
    """Empty BuildHooksEnv for NoHooksLu.
396

397
    This just raises an error.
398

399
    """
400
    assert False, "BuildHooksEnv called for NoHooksLUs"
401

    
402

    
403
class Tasklet:
404
  """Tasklet base class.
405

406
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
407
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
408
  tasklets know nothing about locks.
409

410
  Subclasses must follow these rules:
411
    - Implement CheckPrereq
412
    - Implement Exec
413

414
  """
415
  def __init__(self, lu):
416
    self.lu = lu
417

    
418
    # Shortcuts
419
    self.cfg = lu.cfg
420
    self.rpc = lu.rpc
421

    
422
  def CheckPrereq(self):
423
    """Check prerequisites for this tasklets.
424

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

429
    The method should raise errors.OpPrereqError in case something is not
430
    fulfilled. Its return value is ignored.
431

432
    This method should also update all parameters to their canonical form if it
433
    hasn't been done before.
434

435
    """
436
    pass
437

    
438
  def Exec(self, feedback_fn):
439
    """Execute the tasklet.
440

441
    This method should implement the actual work. It should raise
442
    errors.OpExecError for failures that are somewhat dealt with in code, or
443
    expected.
444

445
    """
446
    raise NotImplementedError
447

    
448

    
449
class _QueryBase:
450
  """Base for query utility classes.
451

452
  """
453
  #: Attribute holding field definitions
454
  FIELDS = None
455

    
456
  def __init__(self, names, fields, use_locking):
457
    """Initializes this class.
458

459
    """
460
    self.names = names
461
    self.use_locking = use_locking
462

    
463
    self.query = query.Query(self.FIELDS, fields)
464
    self.requested_data = self.query.RequestedData()
465

    
466
    self.do_locking = None
467
    self.wanted = None
468

    
469
  def _GetNames(self, lu, all_names, lock_level):
470
    """Helper function to determine names asked for in the query.
471

472
    """
473
    if self.do_locking:
474
      names = lu.acquired_locks[lock_level]
475
    else:
476
      names = all_names
477

    
478
    if self.wanted == locking.ALL_SET:
479
      assert not self.names
480
      # caller didn't specify names, so ordering is not important
481
      return utils.NiceSort(names)
482

    
483
    # caller specified names and we must keep the same order
484
    assert self.names
485
    assert not self.do_locking or lu.acquired_locks[lock_level]
486

    
487
    missing = set(self.wanted).difference(names)
488
    if missing:
489
      raise errors.OpExecError("Some items were removed before retrieving"
490
                               " their data: %s" % missing)
491

    
492
    # Return expanded names
493
    return self.wanted
494

    
495
  @classmethod
496
  def FieldsQuery(cls, fields):
497
    """Returns list of available fields.
498

499
    @return: List of L{objects.QueryFieldDefinition}
500

501
    """
502
    return query.QueryFields(cls.FIELDS, fields)
503

    
504
  def ExpandNames(self, lu):
505
    """Expand names for this query.
506

507
    See L{LogicalUnit.ExpandNames}.
508

509
    """
510
    raise NotImplementedError()
511

    
512
  def DeclareLocks(self, lu, level):
513
    """Declare locks for this query.
514

515
    See L{LogicalUnit.DeclareLocks}.
516

517
    """
518
    raise NotImplementedError()
519

    
520
  def _GetQueryData(self, lu):
521
    """Collects all data for this query.
522

523
    @return: Query data object
524

525
    """
526
    raise NotImplementedError()
527

    
528
  def NewStyleQuery(self, lu):
529
    """Collect data and execute query.
530

531
    """
532
    return query.GetQueryResponse(self.query, self._GetQueryData(lu))
533

    
534
  def OldStyleQuery(self, lu):
535
    """Collect data and execute query.
536

537
    """
538
    return self.query.OldStyleQuery(self._GetQueryData(lu))
539

    
540

    
541
def _GetWantedNodes(lu, nodes):
542
  """Returns list of checked and expanded node names.
543

544
  @type lu: L{LogicalUnit}
545
  @param lu: the logical unit on whose behalf we execute
546
  @type nodes: list
547
  @param nodes: list of node names or None for all nodes
548
  @rtype: list
549
  @return: the list of nodes, sorted
550
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
551

552
  """
553
  if nodes:
554
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
555

    
556
  return utils.NiceSort(lu.cfg.GetNodeList())
557

    
558

    
559
def _GetWantedInstances(lu, instances):
560
  """Returns list of checked and expanded instance names.
561

562
  @type lu: L{LogicalUnit}
563
  @param lu: the logical unit on whose behalf we execute
564
  @type instances: list
565
  @param instances: list of instance names or None for all instances
566
  @rtype: list
567
  @return: the list of instances, sorted
568
  @raise errors.OpPrereqError: if the instances parameter is wrong type
569
  @raise errors.OpPrereqError: if any of the passed instances is not found
570

571
  """
572
  if instances:
573
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
574
  else:
575
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
576
  return wanted
577

    
578

    
579
def _GetUpdatedParams(old_params, update_dict,
580
                      use_default=True, use_none=False):
581
  """Return the new version of a parameter dictionary.
582

583
  @type old_params: dict
584
  @param old_params: old parameters
585
  @type update_dict: dict
586
  @param update_dict: dict containing new parameter values, or
587
      constants.VALUE_DEFAULT to reset the parameter to its default
588
      value
589
  @param use_default: boolean
590
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
591
      values as 'to be deleted' values
592
  @param use_none: boolean
593
  @type use_none: whether to recognise C{None} values as 'to be
594
      deleted' values
595
  @rtype: dict
596
  @return: the new parameter dictionary
597

598
  """
599
  params_copy = copy.deepcopy(old_params)
600
  for key, val in update_dict.iteritems():
601
    if ((use_default and val == constants.VALUE_DEFAULT) or
602
        (use_none and val is None)):
603
      try:
604
        del params_copy[key]
605
      except KeyError:
606
        pass
607
    else:
608
      params_copy[key] = val
609
  return params_copy
610

    
611

    
612
def _CheckOutputFields(static, dynamic, selected):
613
  """Checks whether all selected fields are valid.
614

615
  @type static: L{utils.FieldSet}
616
  @param static: static fields set
617
  @type dynamic: L{utils.FieldSet}
618
  @param dynamic: dynamic fields set
619

620
  """
621
  f = utils.FieldSet()
622
  f.Extend(static)
623
  f.Extend(dynamic)
624

    
625
  delta = f.NonMatching(selected)
626
  if delta:
627
    raise errors.OpPrereqError("Unknown output fields selected: %s"
628
                               % ",".join(delta), errors.ECODE_INVAL)
629

    
630

    
631
def _CheckGlobalHvParams(params):
632
  """Validates that given hypervisor params are not global ones.
633

634
  This will ensure that instances don't get customised versions of
635
  global params.
636

637
  """
638
  used_globals = constants.HVC_GLOBALS.intersection(params)
639
  if used_globals:
640
    msg = ("The following hypervisor parameters are global and cannot"
641
           " be customized at instance level, please modify them at"
642
           " cluster level: %s" % utils.CommaJoin(used_globals))
643
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
644

    
645

    
646
def _CheckNodeOnline(lu, node, msg=None):
647
  """Ensure that a given node is online.
648

649
  @param lu: the LU on behalf of which we make the check
650
  @param node: the node to check
651
  @param msg: if passed, should be a message to replace the default one
652
  @raise errors.OpPrereqError: if the node is offline
653

654
  """
655
  if msg is None:
656
    msg = "Can't use offline node"
657
  if lu.cfg.GetNodeInfo(node).offline:
658
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
659

    
660

    
661
def _CheckNodeNotDrained(lu, node):
662
  """Ensure that a given node is not drained.
663

664
  @param lu: the LU on behalf of which we make the check
665
  @param node: the node to check
666
  @raise errors.OpPrereqError: if the node is drained
667

668
  """
669
  if lu.cfg.GetNodeInfo(node).drained:
670
    raise errors.OpPrereqError("Can't use drained node %s" % node,
671
                               errors.ECODE_STATE)
672

    
673

    
674
def _CheckNodeVmCapable(lu, node):
675
  """Ensure that a given node is vm capable.
676

677
  @param lu: the LU on behalf of which we make the check
678
  @param node: the node to check
679
  @raise errors.OpPrereqError: if the node is not vm capable
680

681
  """
682
  if not lu.cfg.GetNodeInfo(node).vm_capable:
683
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
684
                               errors.ECODE_STATE)
685

    
686

    
687
def _CheckNodeHasOS(lu, node, os_name, force_variant):
688
  """Ensure that a node supports a given OS.
689

690
  @param lu: the LU on behalf of which we make the check
691
  @param node: the node to check
692
  @param os_name: the OS to query about
693
  @param force_variant: whether to ignore variant errors
694
  @raise errors.OpPrereqError: if the node is not supporting the OS
695

696
  """
697
  result = lu.rpc.call_os_get(node, os_name)
698
  result.Raise("OS '%s' not in supported OS list for node %s" %
699
               (os_name, node),
700
               prereq=True, ecode=errors.ECODE_INVAL)
701
  if not force_variant:
702
    _CheckOSVariant(result.payload, os_name)
703

    
704

    
705
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
706
  """Ensure that a node has the given secondary ip.
707

708
  @type lu: L{LogicalUnit}
709
  @param lu: the LU on behalf of which we make the check
710
  @type node: string
711
  @param node: the node to check
712
  @type secondary_ip: string
713
  @param secondary_ip: the ip to check
714
  @type prereq: boolean
715
  @param prereq: whether to throw a prerequisite or an execute error
716
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
717
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
718

719
  """
720
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
721
  result.Raise("Failure checking secondary ip on node %s" % node,
722
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
723
  if not result.payload:
724
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
725
           " please fix and re-run this command" % secondary_ip)
726
    if prereq:
727
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
728
    else:
729
      raise errors.OpExecError(msg)
730

    
731

    
732
def _GetClusterDomainSecret():
733
  """Reads the cluster domain secret.
734

735
  """
736
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
737
                               strict=True)
738

    
739

    
740
def _CheckInstanceDown(lu, instance, reason):
741
  """Ensure that an instance is not running."""
742
  if instance.admin_up:
743
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
744
                               (instance.name, reason), errors.ECODE_STATE)
745

    
746
  pnode = instance.primary_node
747
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
748
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
749
              prereq=True, ecode=errors.ECODE_ENVIRON)
750

    
751
  if instance.name in ins_l.payload:
752
    raise errors.OpPrereqError("Instance %s is running, %s" %
753
                               (instance.name, reason), errors.ECODE_STATE)
754

    
755

    
756
def _ExpandItemName(fn, name, kind):
757
  """Expand an item name.
758

759
  @param fn: the function to use for expansion
760
  @param name: requested item name
761
  @param kind: text description ('Node' or 'Instance')
762
  @return: the resolved (full) name
763
  @raise errors.OpPrereqError: if the item is not found
764

765
  """
766
  full_name = fn(name)
767
  if full_name is None:
768
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
769
                               errors.ECODE_NOENT)
770
  return full_name
771

    
772

    
773
def _ExpandNodeName(cfg, name):
774
  """Wrapper over L{_ExpandItemName} for nodes."""
775
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
776

    
777

    
778
def _ExpandInstanceName(cfg, name):
779
  """Wrapper over L{_ExpandItemName} for instance."""
780
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
781

    
782

    
783
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
784
                          memory, vcpus, nics, disk_template, disks,
785
                          bep, hvp, hypervisor_name):
786
  """Builds instance related env variables for hooks
787

788
  This builds the hook environment from individual variables.
789

790
  @type name: string
791
  @param name: the name of the instance
792
  @type primary_node: string
793
  @param primary_node: the name of the instance's primary node
794
  @type secondary_nodes: list
795
  @param secondary_nodes: list of secondary nodes as strings
796
  @type os_type: string
797
  @param os_type: the name of the instance's OS
798
  @type status: boolean
799
  @param status: the should_run status of the instance
800
  @type memory: string
801
  @param memory: the memory size of the instance
802
  @type vcpus: string
803
  @param vcpus: the count of VCPUs the instance has
804
  @type nics: list
805
  @param nics: list of tuples (ip, mac, mode, link) representing
806
      the NICs the instance has
807
  @type disk_template: string
808
  @param disk_template: the disk template of the instance
809
  @type disks: list
810
  @param disks: the list of (size, mode) pairs
811
  @type bep: dict
812
  @param bep: the backend parameters for the instance
813
  @type hvp: dict
814
  @param hvp: the hypervisor parameters for the instance
815
  @type hypervisor_name: string
816
  @param hypervisor_name: the hypervisor for the instance
817
  @rtype: dict
818
  @return: the hook environment for this instance
819

820
  """
821
  if status:
822
    str_status = "up"
823
  else:
824
    str_status = "down"
825
  env = {
826
    "OP_TARGET": name,
827
    "INSTANCE_NAME": name,
828
    "INSTANCE_PRIMARY": primary_node,
829
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
830
    "INSTANCE_OS_TYPE": os_type,
831
    "INSTANCE_STATUS": str_status,
832
    "INSTANCE_MEMORY": memory,
833
    "INSTANCE_VCPUS": vcpus,
834
    "INSTANCE_DISK_TEMPLATE": disk_template,
835
    "INSTANCE_HYPERVISOR": hypervisor_name,
836
  }
837

    
838
  if nics:
839
    nic_count = len(nics)
840
    for idx, (ip, mac, mode, link) in enumerate(nics):
841
      if ip is None:
842
        ip = ""
843
      env["INSTANCE_NIC%d_IP" % idx] = ip
844
      env["INSTANCE_NIC%d_MAC" % idx] = mac
845
      env["INSTANCE_NIC%d_MODE" % idx] = mode
846
      env["INSTANCE_NIC%d_LINK" % idx] = link
847
      if mode == constants.NIC_MODE_BRIDGED:
848
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
849
  else:
850
    nic_count = 0
851

    
852
  env["INSTANCE_NIC_COUNT"] = nic_count
853

    
854
  if disks:
855
    disk_count = len(disks)
856
    for idx, (size, mode) in enumerate(disks):
857
      env["INSTANCE_DISK%d_SIZE" % idx] = size
858
      env["INSTANCE_DISK%d_MODE" % idx] = mode
859
  else:
860
    disk_count = 0
861

    
862
  env["INSTANCE_DISK_COUNT"] = disk_count
863

    
864
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
865
    for key, value in source.items():
866
      env["INSTANCE_%s_%s" % (kind, key)] = value
867

    
868
  return env
869

    
870

    
871
def _NICListToTuple(lu, nics):
872
  """Build a list of nic information tuples.
873

874
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
875
  value in LUQueryInstanceData.
876

877
  @type lu:  L{LogicalUnit}
878
  @param lu: the logical unit on whose behalf we execute
879
  @type nics: list of L{objects.NIC}
880
  @param nics: list of nics to convert to hooks tuples
881

882
  """
883
  hooks_nics = []
884
  cluster = lu.cfg.GetClusterInfo()
885
  for nic in nics:
886
    ip = nic.ip
887
    mac = nic.mac
888
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
889
    mode = filled_params[constants.NIC_MODE]
890
    link = filled_params[constants.NIC_LINK]
891
    hooks_nics.append((ip, mac, mode, link))
892
  return hooks_nics
893

    
894

    
895
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
896
  """Builds instance related env variables for hooks from an object.
897

898
  @type lu: L{LogicalUnit}
899
  @param lu: the logical unit on whose behalf we execute
900
  @type instance: L{objects.Instance}
901
  @param instance: the instance for which we should build the
902
      environment
903
  @type override: dict
904
  @param override: dictionary with key/values that will override
905
      our values
906
  @rtype: dict
907
  @return: the hook environment dictionary
908

909
  """
910
  cluster = lu.cfg.GetClusterInfo()
911
  bep = cluster.FillBE(instance)
912
  hvp = cluster.FillHV(instance)
913
  args = {
914
    'name': instance.name,
915
    'primary_node': instance.primary_node,
916
    'secondary_nodes': instance.secondary_nodes,
917
    'os_type': instance.os,
918
    'status': instance.admin_up,
919
    'memory': bep[constants.BE_MEMORY],
920
    'vcpus': bep[constants.BE_VCPUS],
921
    'nics': _NICListToTuple(lu, instance.nics),
922
    'disk_template': instance.disk_template,
923
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
924
    'bep': bep,
925
    'hvp': hvp,
926
    'hypervisor_name': instance.hypervisor,
927
  }
928
  if override:
929
    args.update(override)
930
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
931

    
932

    
933
def _AdjustCandidatePool(lu, exceptions):
934
  """Adjust the candidate pool after node operations.
935

936
  """
937
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
938
  if mod_list:
939
    lu.LogInfo("Promoted nodes to master candidate role: %s",
940
               utils.CommaJoin(node.name for node in mod_list))
941
    for name in mod_list:
942
      lu.context.ReaddNode(name)
943
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
944
  if mc_now > mc_max:
945
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
946
               (mc_now, mc_max))
947

    
948

    
949
def _DecideSelfPromotion(lu, exceptions=None):
950
  """Decide whether I should promote myself as a master candidate.
951

952
  """
953
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
954
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
955
  # the new node will increase mc_max with one, so:
956
  mc_should = min(mc_should + 1, cp_size)
957
  return mc_now < mc_should
958

    
959

    
960
def _CheckNicsBridgesExist(lu, target_nics, target_node):
961
  """Check that the brigdes needed by a list of nics exist.
962

963
  """
964
  cluster = lu.cfg.GetClusterInfo()
965
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
966
  brlist = [params[constants.NIC_LINK] for params in paramslist
967
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
968
  if brlist:
969
    result = lu.rpc.call_bridges_exist(target_node, brlist)
970
    result.Raise("Error checking bridges on destination node '%s'" %
971
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
972

    
973

    
974
def _CheckInstanceBridgesExist(lu, instance, node=None):
975
  """Check that the brigdes needed by an instance exist.
976

977
  """
978
  if node is None:
979
    node = instance.primary_node
980
  _CheckNicsBridgesExist(lu, instance.nics, node)
981

    
982

    
983
def _CheckOSVariant(os_obj, name):
984
  """Check whether an OS name conforms to the os variants specification.
985

986
  @type os_obj: L{objects.OS}
987
  @param os_obj: OS object to check
988
  @type name: string
989
  @param name: OS name passed by the user, to check for validity
990

991
  """
992
  if not os_obj.supported_variants:
993
    return
994
  variant = objects.OS.GetVariant(name)
995
  if not variant:
996
    raise errors.OpPrereqError("OS name must include a variant",
997
                               errors.ECODE_INVAL)
998

    
999
  if variant not in os_obj.supported_variants:
1000
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1001

    
1002

    
1003
def _GetNodeInstancesInner(cfg, fn):
1004
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1005

    
1006

    
1007
def _GetNodeInstances(cfg, node_name):
1008
  """Returns a list of all primary and secondary instances on a node.
1009

1010
  """
1011

    
1012
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1013

    
1014

    
1015
def _GetNodePrimaryInstances(cfg, node_name):
1016
  """Returns primary instances on a node.
1017

1018
  """
1019
  return _GetNodeInstancesInner(cfg,
1020
                                lambda inst: node_name == inst.primary_node)
1021

    
1022

    
1023
def _GetNodeSecondaryInstances(cfg, node_name):
1024
  """Returns secondary instances on a node.
1025

1026
  """
1027
  return _GetNodeInstancesInner(cfg,
1028
                                lambda inst: node_name in inst.secondary_nodes)
1029

    
1030

    
1031
def _GetStorageTypeArgs(cfg, storage_type):
1032
  """Returns the arguments for a storage type.
1033

1034
  """
1035
  # Special case for file storage
1036
  if storage_type == constants.ST_FILE:
1037
    # storage.FileStorage wants a list of storage directories
1038
    return [[cfg.GetFileStorageDir()]]
1039

    
1040
  return []
1041

    
1042

    
1043
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1044
  faulty = []
1045

    
1046
  for dev in instance.disks:
1047
    cfg.SetDiskID(dev, node_name)
1048

    
1049
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1050
  result.Raise("Failed to get disk status from node %s" % node_name,
1051
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1052

    
1053
  for idx, bdev_status in enumerate(result.payload):
1054
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1055
      faulty.append(idx)
1056

    
1057
  return faulty
1058

    
1059

    
1060
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1061
  """Check the sanity of iallocator and node arguments and use the
1062
  cluster-wide iallocator if appropriate.
1063

1064
  Check that at most one of (iallocator, node) is specified. If none is
1065
  specified, then the LU's opcode's iallocator slot is filled with the
1066
  cluster-wide default iallocator.
1067

1068
  @type iallocator_slot: string
1069
  @param iallocator_slot: the name of the opcode iallocator slot
1070
  @type node_slot: string
1071
  @param node_slot: the name of the opcode target node slot
1072

1073
  """
1074
  node = getattr(lu.op, node_slot, None)
1075
  iallocator = getattr(lu.op, iallocator_slot, None)
1076

    
1077
  if node is not None and iallocator is not None:
1078
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1079
                               errors.ECODE_INVAL)
1080
  elif node is None and iallocator is None:
1081
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1082
    if default_iallocator:
1083
      setattr(lu.op, iallocator_slot, default_iallocator)
1084
    else:
1085
      raise errors.OpPrereqError("No iallocator or node given and no"
1086
                                 " cluster-wide default iallocator found."
1087
                                 " Please specify either an iallocator or a"
1088
                                 " node, or set a cluster-wide default"
1089
                                 " iallocator.")
1090

    
1091

    
1092
class LUPostInitCluster(LogicalUnit):
1093
  """Logical unit for running hooks after cluster initialization.
1094

1095
  """
1096
  HPATH = "cluster-init"
1097
  HTYPE = constants.HTYPE_CLUSTER
1098

    
1099
  def BuildHooksEnv(self):
1100
    """Build hooks env.
1101

1102
    """
1103
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1104
    mn = self.cfg.GetMasterNode()
1105
    return env, [], [mn]
1106

    
1107
  def Exec(self, feedback_fn):
1108
    """Nothing to do.
1109

1110
    """
1111
    return True
1112

    
1113

    
1114
class LUDestroyCluster(LogicalUnit):
1115
  """Logical unit for destroying the cluster.
1116

1117
  """
1118
  HPATH = "cluster-destroy"
1119
  HTYPE = constants.HTYPE_CLUSTER
1120

    
1121
  def BuildHooksEnv(self):
1122
    """Build hooks env.
1123

1124
    """
1125
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1126
    return env, [], []
1127

    
1128
  def CheckPrereq(self):
1129
    """Check prerequisites.
1130

1131
    This checks whether the cluster is empty.
1132

1133
    Any errors are signaled by raising errors.OpPrereqError.
1134

1135
    """
1136
    master = self.cfg.GetMasterNode()
1137

    
1138
    nodelist = self.cfg.GetNodeList()
1139
    if len(nodelist) != 1 or nodelist[0] != master:
1140
      raise errors.OpPrereqError("There are still %d node(s) in"
1141
                                 " this cluster." % (len(nodelist) - 1),
1142
                                 errors.ECODE_INVAL)
1143
    instancelist = self.cfg.GetInstanceList()
1144
    if instancelist:
1145
      raise errors.OpPrereqError("There are still %d instance(s) in"
1146
                                 " this cluster." % len(instancelist),
1147
                                 errors.ECODE_INVAL)
1148

    
1149
  def Exec(self, feedback_fn):
1150
    """Destroys the cluster.
1151

1152
    """
1153
    master = self.cfg.GetMasterNode()
1154

    
1155
    # Run post hooks on master node before it's removed
1156
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1157
    try:
1158
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1159
    except:
1160
      # pylint: disable-msg=W0702
1161
      self.LogWarning("Errors occurred running hooks on %s" % master)
1162

    
1163
    result = self.rpc.call_node_stop_master(master, False)
1164
    result.Raise("Could not disable the master role")
1165

    
1166
    return master
1167

    
1168

    
1169
def _VerifyCertificate(filename):
1170
  """Verifies a certificate for LUVerifyCluster.
1171

1172
  @type filename: string
1173
  @param filename: Path to PEM file
1174

1175
  """
1176
  try:
1177
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1178
                                           utils.ReadFile(filename))
1179
  except Exception, err: # pylint: disable-msg=W0703
1180
    return (LUVerifyCluster.ETYPE_ERROR,
1181
            "Failed to load X509 certificate %s: %s" % (filename, err))
1182

    
1183
  (errcode, msg) = \
1184
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1185
                                constants.SSL_CERT_EXPIRATION_ERROR)
1186

    
1187
  if msg:
1188
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1189
  else:
1190
    fnamemsg = None
1191

    
1192
  if errcode is None:
1193
    return (None, fnamemsg)
1194
  elif errcode == utils.CERT_WARNING:
1195
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1196
  elif errcode == utils.CERT_ERROR:
1197
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1198

    
1199
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1200

    
1201

    
1202
class LUVerifyCluster(LogicalUnit):
1203
  """Verifies the cluster status.
1204

1205
  """
1206
  HPATH = "cluster-verify"
1207
  HTYPE = constants.HTYPE_CLUSTER
1208
  REQ_BGL = False
1209

    
1210
  TCLUSTER = "cluster"
1211
  TNODE = "node"
1212
  TINSTANCE = "instance"
1213

    
1214
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1215
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1216
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1217
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1218
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1219
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1220
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1221
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1222
  ENODEDRBD = (TNODE, "ENODEDRBD")
1223
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1224
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1225
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1226
  ENODEHV = (TNODE, "ENODEHV")
1227
  ENODELVM = (TNODE, "ENODELVM")
1228
  ENODEN1 = (TNODE, "ENODEN1")
1229
  ENODENET = (TNODE, "ENODENET")
1230
  ENODEOS = (TNODE, "ENODEOS")
1231
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1232
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1233
  ENODERPC = (TNODE, "ENODERPC")
1234
  ENODESSH = (TNODE, "ENODESSH")
1235
  ENODEVERSION = (TNODE, "ENODEVERSION")
1236
  ENODESETUP = (TNODE, "ENODESETUP")
1237
  ENODETIME = (TNODE, "ENODETIME")
1238
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1239

    
1240
  ETYPE_FIELD = "code"
1241
  ETYPE_ERROR = "ERROR"
1242
  ETYPE_WARNING = "WARNING"
1243

    
1244
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1245

    
1246
  class NodeImage(object):
1247
    """A class representing the logical and physical status of a node.
1248

1249
    @type name: string
1250
    @ivar name: the node name to which this object refers
1251
    @ivar volumes: a structure as returned from
1252
        L{ganeti.backend.GetVolumeList} (runtime)
1253
    @ivar instances: a list of running instances (runtime)
1254
    @ivar pinst: list of configured primary instances (config)
1255
    @ivar sinst: list of configured secondary instances (config)
1256
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1257
        of this node (config)
1258
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1259
    @ivar dfree: free disk, as reported by the node (runtime)
1260
    @ivar offline: the offline status (config)
1261
    @type rpc_fail: boolean
1262
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1263
        not whether the individual keys were correct) (runtime)
1264
    @type lvm_fail: boolean
1265
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1266
    @type hyp_fail: boolean
1267
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1268
    @type ghost: boolean
1269
    @ivar ghost: whether this is a known node or not (config)
1270
    @type os_fail: boolean
1271
    @ivar os_fail: whether the RPC call didn't return valid OS data
1272
    @type oslist: list
1273
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1274
    @type vm_capable: boolean
1275
    @ivar vm_capable: whether the node can host instances
1276

1277
    """
1278
    def __init__(self, offline=False, name=None, vm_capable=True):
1279
      self.name = name
1280
      self.volumes = {}
1281
      self.instances = []
1282
      self.pinst = []
1283
      self.sinst = []
1284
      self.sbp = {}
1285
      self.mfree = 0
1286
      self.dfree = 0
1287
      self.offline = offline
1288
      self.vm_capable = vm_capable
1289
      self.rpc_fail = False
1290
      self.lvm_fail = False
1291
      self.hyp_fail = False
1292
      self.ghost = False
1293
      self.os_fail = False
1294
      self.oslist = {}
1295

    
1296
  def ExpandNames(self):
1297
    self.needed_locks = {
1298
      locking.LEVEL_NODE: locking.ALL_SET,
1299
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1300
    }
1301
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1302

    
1303
  def _Error(self, ecode, item, msg, *args, **kwargs):
1304
    """Format an error message.
1305

1306
    Based on the opcode's error_codes parameter, either format a
1307
    parseable error code, or a simpler error string.
1308

1309
    This must be called only from Exec and functions called from Exec.
1310

1311
    """
1312
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1313
    itype, etxt = ecode
1314
    # first complete the msg
1315
    if args:
1316
      msg = msg % args
1317
    # then format the whole message
1318
    if self.op.error_codes:
1319
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1320
    else:
1321
      if item:
1322
        item = " " + item
1323
      else:
1324
        item = ""
1325
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1326
    # and finally report it via the feedback_fn
1327
    self._feedback_fn("  - %s" % msg)
1328

    
1329
  def _ErrorIf(self, cond, *args, **kwargs):
1330
    """Log an error message if the passed condition is True.
1331

1332
    """
1333
    cond = bool(cond) or self.op.debug_simulate_errors
1334
    if cond:
1335
      self._Error(*args, **kwargs)
1336
    # do not mark the operation as failed for WARN cases only
1337
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1338
      self.bad = self.bad or cond
1339

    
1340
  def _VerifyNode(self, ninfo, nresult):
1341
    """Perform some basic validation on data returned from a node.
1342

1343
      - check the result data structure is well formed and has all the
1344
        mandatory fields
1345
      - check ganeti version
1346

1347
    @type ninfo: L{objects.Node}
1348
    @param ninfo: the node to check
1349
    @param nresult: the results from the node
1350
    @rtype: boolean
1351
    @return: whether overall this call was successful (and we can expect
1352
         reasonable values in the respose)
1353

1354
    """
1355
    node = ninfo.name
1356
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1357

    
1358
    # main result, nresult should be a non-empty dict
1359
    test = not nresult or not isinstance(nresult, dict)
1360
    _ErrorIf(test, self.ENODERPC, node,
1361
                  "unable to verify node: no data returned")
1362
    if test:
1363
      return False
1364

    
1365
    # compares ganeti version
1366
    local_version = constants.PROTOCOL_VERSION
1367
    remote_version = nresult.get("version", None)
1368
    test = not (remote_version and
1369
                isinstance(remote_version, (list, tuple)) and
1370
                len(remote_version) == 2)
1371
    _ErrorIf(test, self.ENODERPC, node,
1372
             "connection to node returned invalid data")
1373
    if test:
1374
      return False
1375

    
1376
    test = local_version != remote_version[0]
1377
    _ErrorIf(test, self.ENODEVERSION, node,
1378
             "incompatible protocol versions: master %s,"
1379
             " node %s", local_version, remote_version[0])
1380
    if test:
1381
      return False
1382

    
1383
    # node seems compatible, we can actually try to look into its results
1384

    
1385
    # full package version
1386
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1387
                  self.ENODEVERSION, node,
1388
                  "software version mismatch: master %s, node %s",
1389
                  constants.RELEASE_VERSION, remote_version[1],
1390
                  code=self.ETYPE_WARNING)
1391

    
1392
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1393
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1394
      for hv_name, hv_result in hyp_result.iteritems():
1395
        test = hv_result is not None
1396
        _ErrorIf(test, self.ENODEHV, node,
1397
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1398

    
1399
    test = nresult.get(constants.NV_NODESETUP,
1400
                           ["Missing NODESETUP results"])
1401
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1402
             "; ".join(test))
1403

    
1404
    return True
1405

    
1406
  def _VerifyNodeTime(self, ninfo, nresult,
1407
                      nvinfo_starttime, nvinfo_endtime):
1408
    """Check the node time.
1409

1410
    @type ninfo: L{objects.Node}
1411
    @param ninfo: the node to check
1412
    @param nresult: the remote results for the node
1413
    @param nvinfo_starttime: the start time of the RPC call
1414
    @param nvinfo_endtime: the end time of the RPC call
1415

1416
    """
1417
    node = ninfo.name
1418
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1419

    
1420
    ntime = nresult.get(constants.NV_TIME, None)
1421
    try:
1422
      ntime_merged = utils.MergeTime(ntime)
1423
    except (ValueError, TypeError):
1424
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1425
      return
1426

    
1427
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1428
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1429
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1430
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1431
    else:
1432
      ntime_diff = None
1433

    
1434
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1435
             "Node time diverges by at least %s from master node time",
1436
             ntime_diff)
1437

    
1438
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1439
    """Check the node time.
1440

1441
    @type ninfo: L{objects.Node}
1442
    @param ninfo: the node to check
1443
    @param nresult: the remote results for the node
1444
    @param vg_name: the configured VG name
1445

1446
    """
1447
    if vg_name is None:
1448
      return
1449

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

    
1453
    # checks vg existence and size > 20G
1454
    vglist = nresult.get(constants.NV_VGLIST, None)
1455
    test = not vglist
1456
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1457
    if not test:
1458
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1459
                                            constants.MIN_VG_SIZE)
1460
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1461

    
1462
    # check pv names
1463
    pvlist = nresult.get(constants.NV_PVLIST, None)
1464
    test = pvlist is None
1465
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1466
    if not test:
1467
      # check that ':' is not present in PV names, since it's a
1468
      # special character for lvcreate (denotes the range of PEs to
1469
      # use on the PV)
1470
      for _, pvname, owner_vg in pvlist:
1471
        test = ":" in pvname
1472
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1473
                 " '%s' of VG '%s'", pvname, owner_vg)
1474

    
1475
  def _VerifyNodeNetwork(self, ninfo, nresult):
1476
    """Check the node time.
1477

1478
    @type ninfo: L{objects.Node}
1479
    @param ninfo: the node to check
1480
    @param nresult: the remote results for the node
1481

1482
    """
1483
    node = ninfo.name
1484
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1485

    
1486
    test = constants.NV_NODELIST not in nresult
1487
    _ErrorIf(test, self.ENODESSH, node,
1488
             "node hasn't returned node ssh connectivity data")
1489
    if not test:
1490
      if nresult[constants.NV_NODELIST]:
1491
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1492
          _ErrorIf(True, self.ENODESSH, node,
1493
                   "ssh communication with node '%s': %s", a_node, a_msg)
1494

    
1495
    test = constants.NV_NODENETTEST not in nresult
1496
    _ErrorIf(test, self.ENODENET, node,
1497
             "node hasn't returned node tcp connectivity data")
1498
    if not test:
1499
      if nresult[constants.NV_NODENETTEST]:
1500
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1501
        for anode in nlist:
1502
          _ErrorIf(True, self.ENODENET, node,
1503
                   "tcp communication with node '%s': %s",
1504
                   anode, nresult[constants.NV_NODENETTEST][anode])
1505

    
1506
    test = constants.NV_MASTERIP not in nresult
1507
    _ErrorIf(test, self.ENODENET, node,
1508
             "node hasn't returned node master IP reachability data")
1509
    if not test:
1510
      if not nresult[constants.NV_MASTERIP]:
1511
        if node == self.master_node:
1512
          msg = "the master node cannot reach the master IP (not configured?)"
1513
        else:
1514
          msg = "cannot reach the master IP"
1515
        _ErrorIf(True, self.ENODENET, node, msg)
1516

    
1517
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1518
                      diskstatus):
1519
    """Verify an instance.
1520

1521
    This function checks to see if the required block devices are
1522
    available on the instance's node.
1523

1524
    """
1525
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1526
    node_current = instanceconfig.primary_node
1527

    
1528
    node_vol_should = {}
1529
    instanceconfig.MapLVsByNode(node_vol_should)
1530

    
1531
    for node in node_vol_should:
1532
      n_img = node_image[node]
1533
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1534
        # ignore missing volumes on offline or broken nodes
1535
        continue
1536
      for volume in node_vol_should[node]:
1537
        test = volume not in n_img.volumes
1538
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1539
                 "volume %s missing on node %s", volume, node)
1540

    
1541
    if instanceconfig.admin_up:
1542
      pri_img = node_image[node_current]
1543
      test = instance not in pri_img.instances and not pri_img.offline
1544
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1545
               "instance not running on its primary node %s",
1546
               node_current)
1547

    
1548
    for node, n_img in node_image.items():
1549
      if (not node == node_current):
1550
        test = instance in n_img.instances
1551
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1552
                 "instance should not run on node %s", node)
1553

    
1554
    diskdata = [(nname, success, status, idx)
1555
                for (nname, disks) in diskstatus.items()
1556
                for idx, (success, status) in enumerate(disks)]
1557

    
1558
    for nname, success, bdev_status, idx in diskdata:
1559
      _ErrorIf(instanceconfig.admin_up and not success,
1560
               self.EINSTANCEFAULTYDISK, instance,
1561
               "couldn't retrieve status for disk/%s on %s: %s",
1562
               idx, nname, bdev_status)
1563
      _ErrorIf((instanceconfig.admin_up and success and
1564
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1565
               self.EINSTANCEFAULTYDISK, instance,
1566
               "disk/%s on %s is faulty", idx, nname)
1567

    
1568
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1569
    """Verify if there are any unknown volumes in the cluster.
1570

1571
    The .os, .swap and backup volumes are ignored. All other volumes are
1572
    reported as unknown.
1573

1574
    @type reserved: L{ganeti.utils.FieldSet}
1575
    @param reserved: a FieldSet of reserved volume names
1576

1577
    """
1578
    for node, n_img in node_image.items():
1579
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1580
        # skip non-healthy nodes
1581
        continue
1582
      for volume in n_img.volumes:
1583
        test = ((node not in node_vol_should or
1584
                volume not in node_vol_should[node]) and
1585
                not reserved.Matches(volume))
1586
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1587
                      "volume %s is unknown", volume)
1588

    
1589
  def _VerifyOrphanInstances(self, instancelist, node_image):
1590
    """Verify the list of running instances.
1591

1592
    This checks what instances are running but unknown to the cluster.
1593

1594
    """
1595
    for node, n_img in node_image.items():
1596
      for o_inst in n_img.instances:
1597
        test = o_inst not in instancelist
1598
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1599
                      "instance %s on node %s should not exist", o_inst, node)
1600

    
1601
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1602
    """Verify N+1 Memory Resilience.
1603

1604
    Check that if one single node dies we can still start all the
1605
    instances it was primary for.
1606

1607
    """
1608
    for node, n_img in node_image.items():
1609
      # This code checks that every node which is now listed as
1610
      # secondary has enough memory to host all instances it is
1611
      # supposed to should a single other node in the cluster fail.
1612
      # FIXME: not ready for failover to an arbitrary node
1613
      # FIXME: does not support file-backed instances
1614
      # WARNING: we currently take into account down instances as well
1615
      # as up ones, considering that even if they're down someone
1616
      # might want to start them even in the event of a node failure.
1617
      for prinode, instances in n_img.sbp.items():
1618
        needed_mem = 0
1619
        for instance in instances:
1620
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1621
          if bep[constants.BE_AUTO_BALANCE]:
1622
            needed_mem += bep[constants.BE_MEMORY]
1623
        test = n_img.mfree < needed_mem
1624
        self._ErrorIf(test, self.ENODEN1, node,
1625
                      "not enough memory to accomodate instance failovers"
1626
                      " should node %s fail", prinode)
1627

    
1628
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1629
                       master_files):
1630
    """Verifies and computes the node required file checksums.
1631

1632
    @type ninfo: L{objects.Node}
1633
    @param ninfo: the node to check
1634
    @param nresult: the remote results for the node
1635
    @param file_list: required list of files
1636
    @param local_cksum: dictionary of local files and their checksums
1637
    @param master_files: list of files that only masters should have
1638

1639
    """
1640
    node = ninfo.name
1641
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1642

    
1643
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1644
    test = not isinstance(remote_cksum, dict)
1645
    _ErrorIf(test, self.ENODEFILECHECK, node,
1646
             "node hasn't returned file checksum data")
1647
    if test:
1648
      return
1649

    
1650
    for file_name in file_list:
1651
      node_is_mc = ninfo.master_candidate
1652
      must_have = (file_name not in master_files) or node_is_mc
1653
      # missing
1654
      test1 = file_name not in remote_cksum
1655
      # invalid checksum
1656
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1657
      # existing and good
1658
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1659
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1660
               "file '%s' missing", file_name)
1661
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1662
               "file '%s' has wrong checksum", file_name)
1663
      # not candidate and this is not a must-have file
1664
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1665
               "file '%s' should not exist on non master"
1666
               " candidates (and the file is outdated)", file_name)
1667
      # all good, except non-master/non-must have combination
1668
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1669
               "file '%s' should not exist"
1670
               " on non master candidates", file_name)
1671

    
1672
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1673
                      drbd_map):
1674
    """Verifies and the node DRBD status.
1675

1676
    @type ninfo: L{objects.Node}
1677
    @param ninfo: the node to check
1678
    @param nresult: the remote results for the node
1679
    @param instanceinfo: the dict of instances
1680
    @param drbd_helper: the configured DRBD usermode helper
1681
    @param drbd_map: the DRBD map as returned by
1682
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1683

1684
    """
1685
    node = ninfo.name
1686
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1687

    
1688
    if drbd_helper:
1689
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1690
      test = (helper_result == None)
1691
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1692
               "no drbd usermode helper returned")
1693
      if helper_result:
1694
        status, payload = helper_result
1695
        test = not status
1696
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1697
                 "drbd usermode helper check unsuccessful: %s", payload)
1698
        test = status and (payload != drbd_helper)
1699
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1700
                 "wrong drbd usermode helper: %s", payload)
1701

    
1702
    # compute the DRBD minors
1703
    node_drbd = {}
1704
    for minor, instance in drbd_map[node].items():
1705
      test = instance not in instanceinfo
1706
      _ErrorIf(test, self.ECLUSTERCFG, None,
1707
               "ghost instance '%s' in temporary DRBD map", instance)
1708
        # ghost instance should not be running, but otherwise we
1709
        # don't give double warnings (both ghost instance and
1710
        # unallocated minor in use)
1711
      if test:
1712
        node_drbd[minor] = (instance, False)
1713
      else:
1714
        instance = instanceinfo[instance]
1715
        node_drbd[minor] = (instance.name, instance.admin_up)
1716

    
1717
    # and now check them
1718
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1719
    test = not isinstance(used_minors, (tuple, list))
1720
    _ErrorIf(test, self.ENODEDRBD, node,
1721
             "cannot parse drbd status file: %s", str(used_minors))
1722
    if test:
1723
      # we cannot check drbd status
1724
      return
1725

    
1726
    for minor, (iname, must_exist) in node_drbd.items():
1727
      test = minor not in used_minors and must_exist
1728
      _ErrorIf(test, self.ENODEDRBD, node,
1729
               "drbd minor %d of instance %s is not active", minor, iname)
1730
    for minor in used_minors:
1731
      test = minor not in node_drbd
1732
      _ErrorIf(test, self.ENODEDRBD, node,
1733
               "unallocated drbd minor %d is in use", minor)
1734

    
1735
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1736
    """Builds the node OS structures.
1737

1738
    @type ninfo: L{objects.Node}
1739
    @param ninfo: the node to check
1740
    @param nresult: the remote results for the node
1741
    @param nimg: the node image object
1742

1743
    """
1744
    node = ninfo.name
1745
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1746

    
1747
    remote_os = nresult.get(constants.NV_OSLIST, None)
1748
    test = (not isinstance(remote_os, list) or
1749
            not compat.all(isinstance(v, list) and len(v) == 7
1750
                           for v in remote_os))
1751

    
1752
    _ErrorIf(test, self.ENODEOS, node,
1753
             "node hasn't returned valid OS data")
1754

    
1755
    nimg.os_fail = test
1756

    
1757
    if test:
1758
      return
1759

    
1760
    os_dict = {}
1761

    
1762
    for (name, os_path, status, diagnose,
1763
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1764

    
1765
      if name not in os_dict:
1766
        os_dict[name] = []
1767

    
1768
      # parameters is a list of lists instead of list of tuples due to
1769
      # JSON lacking a real tuple type, fix it:
1770
      parameters = [tuple(v) for v in parameters]
1771
      os_dict[name].append((os_path, status, diagnose,
1772
                            set(variants), set(parameters), set(api_ver)))
1773

    
1774
    nimg.oslist = os_dict
1775

    
1776
  def _VerifyNodeOS(self, ninfo, nimg, base):
1777
    """Verifies the node OS list.
1778

1779
    @type ninfo: L{objects.Node}
1780
    @param ninfo: the node to check
1781
    @param nimg: the node image object
1782
    @param base: the 'template' node we match against (e.g. from the master)
1783

1784
    """
1785
    node = ninfo.name
1786
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1787

    
1788
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1789

    
1790
    for os_name, os_data in nimg.oslist.items():
1791
      assert os_data, "Empty OS status for OS %s?!" % os_name
1792
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1793
      _ErrorIf(not f_status, self.ENODEOS, node,
1794
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1795
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1796
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1797
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1798
      # this will catched in backend too
1799
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1800
               and not f_var, self.ENODEOS, node,
1801
               "OS %s with API at least %d does not declare any variant",
1802
               os_name, constants.OS_API_V15)
1803
      # comparisons with the 'base' image
1804
      test = os_name not in base.oslist
1805
      _ErrorIf(test, self.ENODEOS, node,
1806
               "Extra OS %s not present on reference node (%s)",
1807
               os_name, base.name)
1808
      if test:
1809
        continue
1810
      assert base.oslist[os_name], "Base node has empty OS status?"
1811
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1812
      if not b_status:
1813
        # base OS is invalid, skipping
1814
        continue
1815
      for kind, a, b in [("API version", f_api, b_api),
1816
                         ("variants list", f_var, b_var),
1817
                         ("parameters", f_param, b_param)]:
1818
        _ErrorIf(a != b, self.ENODEOS, node,
1819
                 "OS %s %s differs from reference node %s: %s vs. %s",
1820
                 kind, os_name, base.name,
1821
                 utils.CommaJoin(a), utils.CommaJoin(b))
1822

    
1823
    # check any missing OSes
1824
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1825
    _ErrorIf(missing, self.ENODEOS, node,
1826
             "OSes present on reference node %s but missing on this node: %s",
1827
             base.name, utils.CommaJoin(missing))
1828

    
1829
  def _VerifyOob(self, ninfo, nresult):
1830
    """Verifies out of band functionality of a node.
1831

1832
    @type ninfo: L{objects.Node}
1833
    @param ninfo: the node to check
1834
    @param nresult: the remote results for the node
1835

1836
    """
1837
    node = ninfo.name
1838
    # We just have to verify the paths on master and/or master candidates
1839
    # as the oob helper is invoked on the master
1840
    if ((ninfo.master_candidate or ninfo.master) and
1841
        constants.NV_OOB_PATHS in nresult):
1842
      for path_result in nresult[constants.NV_OOB_PATHS]:
1843
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
1844

    
1845
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1846
    """Verifies and updates the node volume data.
1847

1848
    This function will update a L{NodeImage}'s internal structures
1849
    with data from the remote call.
1850

1851
    @type ninfo: L{objects.Node}
1852
    @param ninfo: the node to check
1853
    @param nresult: the remote results for the node
1854
    @param nimg: the node image object
1855
    @param vg_name: the configured VG name
1856

1857
    """
1858
    node = ninfo.name
1859
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1860

    
1861
    nimg.lvm_fail = True
1862
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1863
    if vg_name is None:
1864
      pass
1865
    elif isinstance(lvdata, basestring):
1866
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1867
               utils.SafeEncode(lvdata))
1868
    elif not isinstance(lvdata, dict):
1869
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1870
    else:
1871
      nimg.volumes = lvdata
1872
      nimg.lvm_fail = False
1873

    
1874
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1875
    """Verifies and updates the node instance list.
1876

1877
    If the listing was successful, then updates this node's instance
1878
    list. Otherwise, it marks the RPC call as failed for the instance
1879
    list key.
1880

1881
    @type ninfo: L{objects.Node}
1882
    @param ninfo: the node to check
1883
    @param nresult: the remote results for the node
1884
    @param nimg: the node image object
1885

1886
    """
1887
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1888
    test = not isinstance(idata, list)
1889
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1890
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1891
    if test:
1892
      nimg.hyp_fail = True
1893
    else:
1894
      nimg.instances = idata
1895

    
1896
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1897
    """Verifies and computes a node information map
1898

1899
    @type ninfo: L{objects.Node}
1900
    @param ninfo: the node to check
1901
    @param nresult: the remote results for the node
1902
    @param nimg: the node image object
1903
    @param vg_name: the configured VG name
1904

1905
    """
1906
    node = ninfo.name
1907
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1908

    
1909
    # try to read free memory (from the hypervisor)
1910
    hv_info = nresult.get(constants.NV_HVINFO, None)
1911
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1912
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1913
    if not test:
1914
      try:
1915
        nimg.mfree = int(hv_info["memory_free"])
1916
      except (ValueError, TypeError):
1917
        _ErrorIf(True, self.ENODERPC, node,
1918
                 "node returned invalid nodeinfo, check hypervisor")
1919

    
1920
    # FIXME: devise a free space model for file based instances as well
1921
    if vg_name is not None:
1922
      test = (constants.NV_VGLIST not in nresult or
1923
              vg_name not in nresult[constants.NV_VGLIST])
1924
      _ErrorIf(test, self.ENODELVM, node,
1925
               "node didn't return data for the volume group '%s'"
1926
               " - it is either missing or broken", vg_name)
1927
      if not test:
1928
        try:
1929
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1930
        except (ValueError, TypeError):
1931
          _ErrorIf(True, self.ENODERPC, node,
1932
                   "node returned invalid LVM info, check LVM status")
1933

    
1934
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1935
    """Gets per-disk status information for all instances.
1936

1937
    @type nodelist: list of strings
1938
    @param nodelist: Node names
1939
    @type node_image: dict of (name, L{objects.Node})
1940
    @param node_image: Node objects
1941
    @type instanceinfo: dict of (name, L{objects.Instance})
1942
    @param instanceinfo: Instance objects
1943
    @rtype: {instance: {node: [(succes, payload)]}}
1944
    @return: a dictionary of per-instance dictionaries with nodes as
1945
        keys and disk information as values; the disk information is a
1946
        list of tuples (success, payload)
1947

1948
    """
1949
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1950

    
1951
    node_disks = {}
1952
    node_disks_devonly = {}
1953
    diskless_instances = set()
1954
    diskless = constants.DT_DISKLESS
1955

    
1956
    for nname in nodelist:
1957
      node_instances = list(itertools.chain(node_image[nname].pinst,
1958
                                            node_image[nname].sinst))
1959
      diskless_instances.update(inst for inst in node_instances
1960
                                if instanceinfo[inst].disk_template == diskless)
1961
      disks = [(inst, disk)
1962
               for inst in node_instances
1963
               for disk in instanceinfo[inst].disks]
1964

    
1965
      if not disks:
1966
        # No need to collect data
1967
        continue
1968

    
1969
      node_disks[nname] = disks
1970

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

    
1975
      for dev in devonly:
1976
        self.cfg.SetDiskID(dev, nname)
1977

    
1978
      node_disks_devonly[nname] = devonly
1979

    
1980
    assert len(node_disks) == len(node_disks_devonly)
1981

    
1982
    # Collect data from all nodes with disks
1983
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1984
                                                          node_disks_devonly)
1985

    
1986
    assert len(result) == len(node_disks)
1987

    
1988
    instdisk = {}
1989

    
1990
    for (nname, nres) in result.items():
1991
      disks = node_disks[nname]
1992

    
1993
      if nres.offline:
1994
        # No data from this node
1995
        data = len(disks) * [(False, "node offline")]
1996
      else:
1997
        msg = nres.fail_msg
1998
        _ErrorIf(msg, self.ENODERPC, nname,
1999
                 "while getting disk information: %s", msg)
2000
        if msg:
2001
          # No data from this node
2002
          data = len(disks) * [(False, msg)]
2003
        else:
2004
          data = []
2005
          for idx, i in enumerate(nres.payload):
2006
            if isinstance(i, (tuple, list)) and len(i) == 2:
2007
              data.append(i)
2008
            else:
2009
              logging.warning("Invalid result from node %s, entry %d: %s",
2010
                              nname, idx, i)
2011
              data.append((False, "Invalid result from the remote node"))
2012

    
2013
      for ((inst, _), status) in zip(disks, data):
2014
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2015

    
2016
    # Add empty entries for diskless instances.
2017
    for inst in diskless_instances:
2018
      assert inst not in instdisk
2019
      instdisk[inst] = {}
2020

    
2021
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2022
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2023
                      compat.all(isinstance(s, (tuple, list)) and
2024
                                 len(s) == 2 for s in statuses)
2025
                      for inst, nnames in instdisk.items()
2026
                      for nname, statuses in nnames.items())
2027
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2028

    
2029
    return instdisk
2030

    
2031
  def BuildHooksEnv(self):
2032
    """Build hooks env.
2033

2034
    Cluster-Verify hooks just ran in the post phase and their failure makes
2035
    the output be logged in the verify output and the verification to fail.
2036

2037
    """
2038
    all_nodes = self.cfg.GetNodeList()
2039
    env = {
2040
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2041
      }
2042
    for node in self.cfg.GetAllNodesInfo().values():
2043
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2044

    
2045
    return env, [], all_nodes
2046

    
2047
  def Exec(self, feedback_fn):
2048
    """Verify integrity of cluster, performing various test on nodes.
2049

2050
    """
2051
    self.bad = False
2052
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2053
    verbose = self.op.verbose
2054
    self._feedback_fn = feedback_fn
2055
    feedback_fn("* Verifying global settings")
2056
    for msg in self.cfg.VerifyConfig():
2057
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2058

    
2059
    # Check the cluster certificates
2060
    for cert_filename in constants.ALL_CERT_FILES:
2061
      (errcode, msg) = _VerifyCertificate(cert_filename)
2062
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2063

    
2064
    vg_name = self.cfg.GetVGName()
2065
    drbd_helper = self.cfg.GetDRBDHelper()
2066
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2067
    cluster = self.cfg.GetClusterInfo()
2068
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2069
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2070
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2071
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2072
                        for iname in instancelist)
2073
    i_non_redundant = [] # Non redundant instances
2074
    i_non_a_balanced = [] # Non auto-balanced instances
2075
    n_offline = 0 # Count of offline nodes
2076
    n_drained = 0 # Count of nodes being drained
2077
    node_vol_should = {}
2078

    
2079
    # FIXME: verify OS list
2080
    # do local checksums
2081
    master_files = [constants.CLUSTER_CONF_FILE]
2082
    master_node = self.master_node = self.cfg.GetMasterNode()
2083
    master_ip = self.cfg.GetMasterIP()
2084

    
2085
    file_names = ssconf.SimpleStore().GetFileList()
2086
    file_names.extend(constants.ALL_CERT_FILES)
2087
    file_names.extend(master_files)
2088
    if cluster.modify_etc_hosts:
2089
      file_names.append(constants.ETC_HOSTS)
2090

    
2091
    local_checksums = utils.FingerprintFiles(file_names)
2092

    
2093
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2094
    node_verify_param = {
2095
      constants.NV_FILELIST: file_names,
2096
      constants.NV_NODELIST: [node.name for node in nodeinfo
2097
                              if not node.offline],
2098
      constants.NV_HYPERVISOR: hypervisors,
2099
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2100
                                  node.secondary_ip) for node in nodeinfo
2101
                                 if not node.offline],
2102
      constants.NV_INSTANCELIST: hypervisors,
2103
      constants.NV_VERSION: None,
2104
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2105
      constants.NV_NODESETUP: None,
2106
      constants.NV_TIME: None,
2107
      constants.NV_MASTERIP: (master_node, master_ip),
2108
      constants.NV_OSLIST: None,
2109
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2110
      }
2111

    
2112
    if vg_name is not None:
2113
      node_verify_param[constants.NV_VGLIST] = None
2114
      node_verify_param[constants.NV_LVLIST] = vg_name
2115
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2116
      node_verify_param[constants.NV_DRBDLIST] = None
2117

    
2118
    if drbd_helper:
2119
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2120

    
2121
    # Build our expected cluster state
2122
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2123
                                                 name=node.name,
2124
                                                 vm_capable=node.vm_capable))
2125
                      for node in nodeinfo)
2126

    
2127
    # Gather OOB paths
2128
    oob_paths = []
2129
    for node in nodeinfo:
2130
      path = _SupportsOob(self.cfg, node)
2131
      if path and path not in oob_paths:
2132
        oob_paths.append(path)
2133

    
2134
    if oob_paths:
2135
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2136

    
2137
    for instance in instancelist:
2138
      inst_config = instanceinfo[instance]
2139

    
2140
      for nname in inst_config.all_nodes:
2141
        if nname not in node_image:
2142
          # ghost node
2143
          gnode = self.NodeImage(name=nname)
2144
          gnode.ghost = True
2145
          node_image[nname] = gnode
2146

    
2147
      inst_config.MapLVsByNode(node_vol_should)
2148

    
2149
      pnode = inst_config.primary_node
2150
      node_image[pnode].pinst.append(instance)
2151

    
2152
      for snode in inst_config.secondary_nodes:
2153
        nimg = node_image[snode]
2154
        nimg.sinst.append(instance)
2155
        if pnode not in nimg.sbp:
2156
          nimg.sbp[pnode] = []
2157
        nimg.sbp[pnode].append(instance)
2158

    
2159
    # At this point, we have the in-memory data structures complete,
2160
    # except for the runtime information, which we'll gather next
2161

    
2162
    # Due to the way our RPC system works, exact response times cannot be
2163
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2164
    # time before and after executing the request, we can at least have a time
2165
    # window.
2166
    nvinfo_starttime = time.time()
2167
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2168
                                           self.cfg.GetClusterName())
2169
    nvinfo_endtime = time.time()
2170

    
2171
    all_drbd_map = self.cfg.ComputeDRBDMap()
2172

    
2173
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2174
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2175

    
2176
    feedback_fn("* Verifying node status")
2177

    
2178
    refos_img = None
2179

    
2180
    for node_i in nodeinfo:
2181
      node = node_i.name
2182
      nimg = node_image[node]
2183

    
2184
      if node_i.offline:
2185
        if verbose:
2186
          feedback_fn("* Skipping offline node %s" % (node,))
2187
        n_offline += 1
2188
        continue
2189

    
2190
      if node == master_node:
2191
        ntype = "master"
2192
      elif node_i.master_candidate:
2193
        ntype = "master candidate"
2194
      elif node_i.drained:
2195
        ntype = "drained"
2196
        n_drained += 1
2197
      else:
2198
        ntype = "regular"
2199
      if verbose:
2200
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2201

    
2202
      msg = all_nvinfo[node].fail_msg
2203
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2204
      if msg:
2205
        nimg.rpc_fail = True
2206
        continue
2207

    
2208
      nresult = all_nvinfo[node].payload
2209

    
2210
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2211
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2212
      self._VerifyNodeNetwork(node_i, nresult)
2213
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2214
                            master_files)
2215

    
2216
      self._VerifyOob(node_i, nresult)
2217

    
2218
      if nimg.vm_capable:
2219
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2220
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2221
                             all_drbd_map)
2222

    
2223
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2224
        self._UpdateNodeInstances(node_i, nresult, nimg)
2225
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2226
        self._UpdateNodeOS(node_i, nresult, nimg)
2227
        if not nimg.os_fail:
2228
          if refos_img is None:
2229
            refos_img = nimg
2230
          self._VerifyNodeOS(node_i, nimg, refos_img)
2231

    
2232
    feedback_fn("* Verifying instance status")
2233
    for instance in instancelist:
2234
      if verbose:
2235
        feedback_fn("* Verifying instance %s" % instance)
2236
      inst_config = instanceinfo[instance]
2237
      self._VerifyInstance(instance, inst_config, node_image,
2238
                           instdisk[instance])
2239
      inst_nodes_offline = []
2240

    
2241
      pnode = inst_config.primary_node
2242
      pnode_img = node_image[pnode]
2243
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2244
               self.ENODERPC, pnode, "instance %s, connection to"
2245
               " primary node failed", instance)
2246

    
2247
      if pnode_img.offline:
2248
        inst_nodes_offline.append(pnode)
2249

    
2250
      # If the instance is non-redundant we cannot survive losing its primary
2251
      # node, so we are not N+1 compliant. On the other hand we have no disk
2252
      # templates with more than one secondary so that situation is not well
2253
      # supported either.
2254
      # FIXME: does not support file-backed instances
2255
      if not inst_config.secondary_nodes:
2256
        i_non_redundant.append(instance)
2257
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2258
               instance, "instance has multiple secondary nodes: %s",
2259
               utils.CommaJoin(inst_config.secondary_nodes),
2260
               code=self.ETYPE_WARNING)
2261

    
2262
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2263
        i_non_a_balanced.append(instance)
2264

    
2265
      for snode in inst_config.secondary_nodes:
2266
        s_img = node_image[snode]
2267
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2268
                 "instance %s, connection to secondary node failed", instance)
2269

    
2270
        if s_img.offline:
2271
          inst_nodes_offline.append(snode)
2272

    
2273
      # warn that the instance lives on offline nodes
2274
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2275
               "instance lives on offline node(s) %s",
2276
               utils.CommaJoin(inst_nodes_offline))
2277
      # ... or ghost/non-vm_capable nodes
2278
      for node in inst_config.all_nodes:
2279
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2280
                 "instance lives on ghost node %s", node)
2281
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2282
                 instance, "instance lives on non-vm_capable node %s", node)
2283

    
2284
    feedback_fn("* Verifying orphan volumes")
2285
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2286
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2287

    
2288
    feedback_fn("* Verifying orphan instances")
2289
    self._VerifyOrphanInstances(instancelist, node_image)
2290

    
2291
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2292
      feedback_fn("* Verifying N+1 Memory redundancy")
2293
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2294

    
2295
    feedback_fn("* Other Notes")
2296
    if i_non_redundant:
2297
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2298
                  % len(i_non_redundant))
2299

    
2300
    if i_non_a_balanced:
2301
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2302
                  % len(i_non_a_balanced))
2303

    
2304
    if n_offline:
2305
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2306

    
2307
    if n_drained:
2308
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2309

    
2310
    return not self.bad
2311

    
2312
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2313
    """Analyze the post-hooks' result
2314

2315
    This method analyses the hook result, handles it, and sends some
2316
    nicely-formatted feedback back to the user.
2317

2318
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2319
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2320
    @param hooks_results: the results of the multi-node hooks rpc call
2321
    @param feedback_fn: function used send feedback back to the caller
2322
    @param lu_result: previous Exec result
2323
    @return: the new Exec result, based on the previous result
2324
        and hook results
2325

2326
    """
2327
    # We only really run POST phase hooks, and are only interested in
2328
    # their results
2329
    if phase == constants.HOOKS_PHASE_POST:
2330
      # Used to change hooks' output to proper indentation
2331
      feedback_fn("* Hooks Results")
2332
      assert hooks_results, "invalid result from hooks"
2333

    
2334
      for node_name in hooks_results:
2335
        res = hooks_results[node_name]
2336
        msg = res.fail_msg
2337
        test = msg and not res.offline
2338
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2339
                      "Communication failure in hooks execution: %s", msg)
2340
        if res.offline or msg:
2341
          # No need to investigate payload if node is offline or gave an error.
2342
          # override manually lu_result here as _ErrorIf only
2343
          # overrides self.bad
2344
          lu_result = 1
2345
          continue
2346
        for script, hkr, output in res.payload:
2347
          test = hkr == constants.HKR_FAIL
2348
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2349
                        "Script %s failed, output:", script)
2350
          if test:
2351
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2352
            feedback_fn("%s" % output)
2353
            lu_result = 0
2354

    
2355
      return lu_result
2356

    
2357

    
2358
class LUVerifyDisks(NoHooksLU):
2359
  """Verifies the cluster disks status.
2360

2361
  """
2362
  REQ_BGL = False
2363

    
2364
  def ExpandNames(self):
2365
    self.needed_locks = {
2366
      locking.LEVEL_NODE: locking.ALL_SET,
2367
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2368
    }
2369
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2370

    
2371
  def Exec(self, feedback_fn):
2372
    """Verify integrity of cluster disks.
2373

2374
    @rtype: tuple of three items
2375
    @return: a tuple of (dict of node-to-node_error, list of instances
2376
        which need activate-disks, dict of instance: (node, volume) for
2377
        missing volumes
2378

2379
    """
2380
    result = res_nodes, res_instances, res_missing = {}, [], {}
2381

    
2382
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2383
    instances = [self.cfg.GetInstanceInfo(name)
2384
                 for name in self.cfg.GetInstanceList()]
2385

    
2386
    nv_dict = {}
2387
    for inst in instances:
2388
      inst_lvs = {}
2389
      if (not inst.admin_up or
2390
          inst.disk_template not in constants.DTS_NET_MIRROR):
2391
        continue
2392
      inst.MapLVsByNode(inst_lvs)
2393
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2394
      for node, vol_list in inst_lvs.iteritems():
2395
        for vol in vol_list:
2396
          nv_dict[(node, vol)] = inst
2397

    
2398
    if not nv_dict:
2399
      return result
2400

    
2401
    vg_names = self.rpc.call_vg_list(nodes)
2402
    vg_names.Raise("Cannot get list of VGs")
2403

    
2404
    for node in nodes:
2405
      # node_volume
2406
      node_res = self.rpc.call_lv_list([node],
2407
                                       vg_names[node].payload.keys())[node]
2408
      if node_res.offline:
2409
        continue
2410
      msg = node_res.fail_msg
2411
      if msg:
2412
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2413
        res_nodes[node] = msg
2414
        continue
2415

    
2416
      lvs = node_res.payload
2417
      for lv_name, (_, _, lv_online) in lvs.items():
2418
        inst = nv_dict.pop((node, lv_name), None)
2419
        if (not lv_online and inst is not None
2420
            and inst.name not in res_instances):
2421
          res_instances.append(inst.name)
2422

    
2423
    # any leftover items in nv_dict are missing LVs, let's arrange the
2424
    # data better
2425
    for key, inst in nv_dict.iteritems():
2426
      if inst.name not in res_missing:
2427
        res_missing[inst.name] = []
2428
      res_missing[inst.name].append(key)
2429

    
2430
    return result
2431

    
2432

    
2433
class LURepairDiskSizes(NoHooksLU):
2434
  """Verifies the cluster disks sizes.
2435

2436
  """
2437
  REQ_BGL = False
2438

    
2439
  def ExpandNames(self):
2440
    if self.op.instances:
2441
      self.wanted_names = []
2442
      for name in self.op.instances:
2443
        full_name = _ExpandInstanceName(self.cfg, name)
2444
        self.wanted_names.append(full_name)
2445
      self.needed_locks = {
2446
        locking.LEVEL_NODE: [],
2447
        locking.LEVEL_INSTANCE: self.wanted_names,
2448
        }
2449
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2450
    else:
2451
      self.wanted_names = None
2452
      self.needed_locks = {
2453
        locking.LEVEL_NODE: locking.ALL_SET,
2454
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2455
        }
2456
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2457

    
2458
  def DeclareLocks(self, level):
2459
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2460
      self._LockInstancesNodes(primary_only=True)
2461

    
2462
  def CheckPrereq(self):
2463
    """Check prerequisites.
2464

2465
    This only checks the optional instance list against the existing names.
2466

2467
    """
2468
    if self.wanted_names is None:
2469
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2470

    
2471
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2472
                             in self.wanted_names]
2473

    
2474
  def _EnsureChildSizes(self, disk):
2475
    """Ensure children of the disk have the needed disk size.
2476

2477
    This is valid mainly for DRBD8 and fixes an issue where the
2478
    children have smaller disk size.
2479

2480
    @param disk: an L{ganeti.objects.Disk} object
2481

2482
    """
2483
    if disk.dev_type == constants.LD_DRBD8:
2484
      assert disk.children, "Empty children for DRBD8?"
2485
      fchild = disk.children[0]
2486
      mismatch = fchild.size < disk.size
2487
      if mismatch:
2488
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2489
                     fchild.size, disk.size)
2490
        fchild.size = disk.size
2491

    
2492
      # and we recurse on this child only, not on the metadev
2493
      return self._EnsureChildSizes(fchild) or mismatch
2494
    else:
2495
      return False
2496

    
2497
  def Exec(self, feedback_fn):
2498
    """Verify the size of cluster disks.
2499

2500
    """
2501
    # TODO: check child disks too
2502
    # TODO: check differences in size between primary/secondary nodes
2503
    per_node_disks = {}
2504
    for instance in self.wanted_instances:
2505
      pnode = instance.primary_node
2506
      if pnode not in per_node_disks:
2507
        per_node_disks[pnode] = []
2508
      for idx, disk in enumerate(instance.disks):
2509
        per_node_disks[pnode].append((instance, idx, disk))
2510

    
2511
    changed = []
2512
    for node, dskl in per_node_disks.items():
2513
      newl = [v[2].Copy() for v in dskl]
2514
      for dsk in newl:
2515
        self.cfg.SetDiskID(dsk, node)
2516
      result = self.rpc.call_blockdev_getsizes(node, newl)
2517
      if result.fail_msg:
2518
        self.LogWarning("Failure in blockdev_getsizes call to node"
2519
                        " %s, ignoring", node)
2520
        continue
2521
      if len(result.data) != len(dskl):
2522
        self.LogWarning("Invalid result from node %s, ignoring node results",
2523
                        node)
2524
        continue
2525
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2526
        if size is None:
2527
          self.LogWarning("Disk %d of instance %s did not return size"
2528
                          " information, ignoring", idx, instance.name)
2529
          continue
2530
        if not isinstance(size, (int, long)):
2531
          self.LogWarning("Disk %d of instance %s did not return valid"
2532
                          " size information, ignoring", idx, instance.name)
2533
          continue
2534
        size = size >> 20
2535
        if size != disk.size:
2536
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2537
                       " correcting: recorded %d, actual %d", idx,
2538
                       instance.name, disk.size, size)
2539
          disk.size = size
2540
          self.cfg.Update(instance, feedback_fn)
2541
          changed.append((instance.name, idx, size))
2542
        if self._EnsureChildSizes(disk):
2543
          self.cfg.Update(instance, feedback_fn)
2544
          changed.append((instance.name, idx, disk.size))
2545
    return changed
2546

    
2547

    
2548
class LURenameCluster(LogicalUnit):
2549
  """Rename the cluster.
2550

2551
  """
2552
  HPATH = "cluster-rename"
2553
  HTYPE = constants.HTYPE_CLUSTER
2554

    
2555
  def BuildHooksEnv(self):
2556
    """Build hooks env.
2557

2558
    """
2559
    env = {
2560
      "OP_TARGET": self.cfg.GetClusterName(),
2561
      "NEW_NAME": self.op.name,
2562
      }
2563
    mn = self.cfg.GetMasterNode()
2564
    all_nodes = self.cfg.GetNodeList()
2565
    return env, [mn], all_nodes
2566

    
2567
  def CheckPrereq(self):
2568
    """Verify that the passed name is a valid one.
2569

2570
    """
2571
    hostname = netutils.GetHostname(name=self.op.name,
2572
                                    family=self.cfg.GetPrimaryIPFamily())
2573

    
2574
    new_name = hostname.name
2575
    self.ip = new_ip = hostname.ip
2576
    old_name = self.cfg.GetClusterName()
2577
    old_ip = self.cfg.GetMasterIP()
2578
    if new_name == old_name and new_ip == old_ip:
2579
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2580
                                 " cluster has changed",
2581
                                 errors.ECODE_INVAL)
2582
    if new_ip != old_ip:
2583
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2584
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2585
                                   " reachable on the network" %
2586
                                   new_ip, errors.ECODE_NOTUNIQUE)
2587

    
2588
    self.op.name = new_name
2589

    
2590
  def Exec(self, feedback_fn):
2591
    """Rename the cluster.
2592

2593
    """
2594
    clustername = self.op.name
2595
    ip = self.ip
2596

    
2597
    # shutdown the master IP
2598
    master = self.cfg.GetMasterNode()
2599
    result = self.rpc.call_node_stop_master(master, False)
2600
    result.Raise("Could not disable the master role")
2601

    
2602
    try:
2603
      cluster = self.cfg.GetClusterInfo()
2604
      cluster.cluster_name = clustername
2605
      cluster.master_ip = ip
2606
      self.cfg.Update(cluster, feedback_fn)
2607

    
2608
      # update the known hosts file
2609
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2610
      node_list = self.cfg.GetOnlineNodeList()
2611
      try:
2612
        node_list.remove(master)
2613
      except ValueError:
2614
        pass
2615
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2616
    finally:
2617
      result = self.rpc.call_node_start_master(master, False, False)
2618
      msg = result.fail_msg
2619
      if msg:
2620
        self.LogWarning("Could not re-enable the master role on"
2621
                        " the master, please restart manually: %s", msg)
2622

    
2623
    return clustername
2624

    
2625

    
2626
class LUSetClusterParams(LogicalUnit):
2627
  """Change the parameters of the cluster.
2628

2629
  """
2630
  HPATH = "cluster-modify"
2631
  HTYPE = constants.HTYPE_CLUSTER
2632
  REQ_BGL = False
2633

    
2634
  def CheckArguments(self):
2635
    """Check parameters
2636

2637
    """
2638
    if self.op.uid_pool:
2639
      uidpool.CheckUidPool(self.op.uid_pool)
2640

    
2641
    if self.op.add_uids:
2642
      uidpool.CheckUidPool(self.op.add_uids)
2643

    
2644
    if self.op.remove_uids:
2645
      uidpool.CheckUidPool(self.op.remove_uids)
2646

    
2647
  def ExpandNames(self):
2648
    # FIXME: in the future maybe other cluster params won't require checking on
2649
    # all nodes to be modified.
2650
    self.needed_locks = {
2651
      locking.LEVEL_NODE: locking.ALL_SET,
2652
    }
2653
    self.share_locks[locking.LEVEL_NODE] = 1
2654

    
2655
  def BuildHooksEnv(self):
2656
    """Build hooks env.
2657

2658
    """
2659
    env = {
2660
      "OP_TARGET": self.cfg.GetClusterName(),
2661
      "NEW_VG_NAME": self.op.vg_name,
2662
      }
2663
    mn = self.cfg.GetMasterNode()
2664
    return env, [mn], [mn]
2665

    
2666
  def CheckPrereq(self):
2667
    """Check prerequisites.
2668

2669
    This checks whether the given params don't conflict and
2670
    if the given volume group is valid.
2671

2672
    """
2673
    if self.op.vg_name is not None and not self.op.vg_name:
2674
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2675
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2676
                                   " instances exist", errors.ECODE_INVAL)
2677

    
2678
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2679
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2680
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2681
                                   " drbd-based instances exist",
2682
                                   errors.ECODE_INVAL)
2683

    
2684
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2685

    
2686
    # if vg_name not None, checks given volume group on all nodes
2687
    if self.op.vg_name:
2688
      vglist = self.rpc.call_vg_list(node_list)
2689
      for node in node_list:
2690
        msg = vglist[node].fail_msg
2691
        if msg:
2692
          # ignoring down node
2693
          self.LogWarning("Error while gathering data on node %s"
2694
                          " (ignoring node): %s", node, msg)
2695
          continue
2696
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2697
                                              self.op.vg_name,
2698
                                              constants.MIN_VG_SIZE)
2699
        if vgstatus:
2700
          raise errors.OpPrereqError("Error on node '%s': %s" %
2701
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2702

    
2703
    if self.op.drbd_helper:
2704
      # checks given drbd helper on all nodes
2705
      helpers = self.rpc.call_drbd_helper(node_list)
2706
      for node in node_list:
2707
        ninfo = self.cfg.GetNodeInfo(node)
2708
        if ninfo.offline:
2709
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2710
          continue
2711
        msg = helpers[node].fail_msg
2712
        if msg:
2713
          raise errors.OpPrereqError("Error checking drbd helper on node"
2714
                                     " '%s': %s" % (node, msg),
2715
                                     errors.ECODE_ENVIRON)
2716
        node_helper = helpers[node].payload
2717
        if node_helper != self.op.drbd_helper:
2718
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2719
                                     (node, node_helper), errors.ECODE_ENVIRON)
2720

    
2721
    self.cluster = cluster = self.cfg.GetClusterInfo()
2722
    # validate params changes
2723
    if self.op.beparams:
2724
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2725
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2726

    
2727
    if self.op.ndparams:
2728
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2729
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2730

    
2731
    if self.op.nicparams:
2732
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2733
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2734
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2735
      nic_errors = []
2736

    
2737
      # check all instances for consistency
2738
      for instance in self.cfg.GetAllInstancesInfo().values():
2739
        for nic_idx, nic in enumerate(instance.nics):
2740
          params_copy = copy.deepcopy(nic.nicparams)
2741
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2742

    
2743
          # check parameter syntax
2744
          try:
2745
            objects.NIC.CheckParameterSyntax(params_filled)
2746
          except errors.ConfigurationError, err:
2747
            nic_errors.append("Instance %s, nic/%d: %s" %
2748
                              (instance.name, nic_idx, err))
2749

    
2750
          # if we're moving instances to routed, check that they have an ip
2751
          target_mode = params_filled[constants.NIC_MODE]
2752
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2753
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2754
                              (instance.name, nic_idx))
2755
      if nic_errors:
2756
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2757
                                   "\n".join(nic_errors))
2758

    
2759
    # hypervisor list/parameters
2760
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2761
    if self.op.hvparams:
2762
      for hv_name, hv_dict in self.op.hvparams.items():
2763
        if hv_name not in self.new_hvparams:
2764
          self.new_hvparams[hv_name] = hv_dict
2765
        else:
2766
          self.new_hvparams[hv_name].update(hv_dict)
2767

    
2768
    # os hypervisor parameters
2769
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2770
    if self.op.os_hvp:
2771
      for os_name, hvs in self.op.os_hvp.items():
2772
        if os_name not in self.new_os_hvp:
2773
          self.new_os_hvp[os_name] = hvs
2774
        else:
2775
          for hv_name, hv_dict in hvs.items():
2776
            if hv_name not in self.new_os_hvp[os_name]:
2777
              self.new_os_hvp[os_name][hv_name] = hv_dict
2778
            else:
2779
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2780

    
2781
    # os parameters
2782
    self.new_osp = objects.FillDict(cluster.osparams, {})
2783
    if self.op.osparams:
2784
      for os_name, osp in self.op.osparams.items():
2785
        if os_name not in self.new_osp:
2786
          self.new_osp[os_name] = {}
2787

    
2788
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2789
                                                  use_none=True)
2790

    
2791
        if not self.new_osp[os_name]:
2792
          # we removed all parameters
2793
          del self.new_osp[os_name]
2794
        else:
2795
          # check the parameter validity (remote check)
2796
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2797
                         os_name, self.new_osp[os_name])
2798

    
2799
    # changes to the hypervisor list
2800
    if self.op.enabled_hypervisors is not None:
2801
      self.hv_list = self.op.enabled_hypervisors
2802
      for hv in self.hv_list:
2803
        # if the hypervisor doesn't already exist in the cluster
2804
        # hvparams, we initialize it to empty, and then (in both
2805
        # cases) we make sure to fill the defaults, as we might not
2806
        # have a complete defaults list if the hypervisor wasn't
2807
        # enabled before
2808
        if hv not in new_hvp:
2809
          new_hvp[hv] = {}
2810
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2811
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2812
    else:
2813
      self.hv_list = cluster.enabled_hypervisors
2814

    
2815
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2816
      # either the enabled list has changed, or the parameters have, validate
2817
      for hv_name, hv_params in self.new_hvparams.items():
2818
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2819
            (self.op.enabled_hypervisors and
2820
             hv_name in self.op.enabled_hypervisors)):
2821
          # either this is a new hypervisor, or its parameters have changed
2822
          hv_class = hypervisor.GetHypervisor(hv_name)
2823
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2824
          hv_class.CheckParameterSyntax(hv_params)
2825
          _CheckHVParams(self, node_list, hv_name, hv_params)
2826

    
2827
    if self.op.os_hvp:
2828
      # no need to check any newly-enabled hypervisors, since the
2829
      # defaults have already been checked in the above code-block
2830
      for os_name, os_hvp in self.new_os_hvp.items():
2831
        for hv_name, hv_params in os_hvp.items():
2832
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2833
          # we need to fill in the new os_hvp on top of the actual hv_p
2834
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2835
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2836
          hv_class = hypervisor.GetHypervisor(hv_name)
2837
          hv_class.CheckParameterSyntax(new_osp)
2838
          _CheckHVParams(self, node_list, hv_name, new_osp)
2839

    
2840
    if self.op.default_iallocator:
2841
      alloc_script = utils.FindFile(self.op.default_iallocator,
2842
                                    constants.IALLOCATOR_SEARCH_PATH,
2843
                                    os.path.isfile)
2844
      if alloc_script is None:
2845
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2846
                                   " specified" % self.op.default_iallocator,
2847
                                   errors.ECODE_INVAL)
2848

    
2849
  def Exec(self, feedback_fn):
2850
    """Change the parameters of the cluster.
2851

2852
    """
2853
    if self.op.vg_name is not None:
2854
      new_volume = self.op.vg_name
2855
      if not new_volume:
2856
        new_volume = None
2857
      if new_volume != self.cfg.GetVGName():
2858
        self.cfg.SetVGName(new_volume)
2859
      else:
2860
        feedback_fn("Cluster LVM configuration already in desired"
2861
                    " state, not changing")
2862
    if self.op.drbd_helper is not None:
2863
      new_helper = self.op.drbd_helper
2864
      if not new_helper:
2865
        new_helper = None
2866
      if new_helper != self.cfg.GetDRBDHelper():
2867
        self.cfg.SetDRBDHelper(new_helper)
2868
      else:
2869
        feedback_fn("Cluster DRBD helper already in desired state,"
2870
                    " not changing")
2871
    if self.op.hvparams:
2872
      self.cluster.hvparams = self.new_hvparams
2873
    if self.op.os_hvp:
2874
      self.cluster.os_hvp = self.new_os_hvp
2875
    if self.op.enabled_hypervisors is not None:
2876
      self.cluster.hvparams = self.new_hvparams
2877
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2878
    if self.op.beparams:
2879
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2880
    if self.op.nicparams:
2881
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2882
    if self.op.osparams:
2883
      self.cluster.osparams = self.new_osp
2884
    if self.op.ndparams:
2885
      self.cluster.ndparams = self.new_ndparams
2886

    
2887
    if self.op.candidate_pool_size is not None:
2888
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2889
      # we need to update the pool size here, otherwise the save will fail
2890
      _AdjustCandidatePool(self, [])
2891

    
2892
    if self.op.maintain_node_health is not None:
2893
      self.cluster.maintain_node_health = self.op.maintain_node_health
2894

    
2895
    if self.op.prealloc_wipe_disks is not None:
2896
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2897

    
2898
    if self.op.add_uids is not None:
2899
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2900

    
2901
    if self.op.remove_uids is not None:
2902
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2903

    
2904
    if self.op.uid_pool is not None:
2905
      self.cluster.uid_pool = self.op.uid_pool
2906

    
2907
    if self.op.default_iallocator is not None:
2908
      self.cluster.default_iallocator = self.op.default_iallocator
2909

    
2910
    if self.op.reserved_lvs is not None:
2911
      self.cluster.reserved_lvs = self.op.reserved_lvs
2912

    
2913
    def helper_os(aname, mods, desc):
2914
      desc += " OS list"
2915
      lst = getattr(self.cluster, aname)
2916
      for key, val in mods:
2917
        if key == constants.DDM_ADD:
2918
          if val in lst:
2919
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2920
          else:
2921
            lst.append(val)
2922
        elif key == constants.DDM_REMOVE:
2923
          if val in lst:
2924
            lst.remove(val)
2925
          else:
2926
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
2927
        else:
2928
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2929

    
2930
    if self.op.hidden_os:
2931
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2932

    
2933
    if self.op.blacklisted_os:
2934
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2935

    
2936
    if self.op.master_netdev:
2937
      master = self.cfg.GetMasterNode()
2938
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
2939
                  self.cluster.master_netdev)
2940
      result = self.rpc.call_node_stop_master(master, False)
2941
      result.Raise("Could not disable the master ip")
2942
      feedback_fn("Changing master_netdev from %s to %s" %
2943
                  (self.cluster.master_netdev, self.op.master_netdev))
2944
      self.cluster.master_netdev = self.op.master_netdev
2945

    
2946
    self.cfg.Update(self.cluster, feedback_fn)
2947

    
2948
    if self.op.master_netdev:
2949
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
2950
                  self.op.master_netdev)
2951
      result = self.rpc.call_node_start_master(master, False, False)
2952
      if result.fail_msg:
2953
        self.LogWarning("Could not re-enable the master ip on"
2954
                        " the master, please restart manually: %s",
2955
                        result.fail_msg)
2956

    
2957

    
2958
def _UploadHelper(lu, nodes, fname):
2959
  """Helper for uploading a file and showing warnings.
2960

2961
  """
2962
  if os.path.exists(fname):
2963
    result = lu.rpc.call_upload_file(nodes, fname)
2964
    for to_node, to_result in result.items():
2965
      msg = to_result.fail_msg
2966
      if msg:
2967
        msg = ("Copy of file %s to node %s failed: %s" %
2968
               (fname, to_node, msg))
2969
        lu.proc.LogWarning(msg)
2970

    
2971

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

2975
  ConfigWriter takes care of distributing the config and ssconf files, but
2976
  there are more files which should be distributed to all nodes. This function
2977
  makes sure those are copied.
2978

2979
  @param lu: calling logical unit
2980
  @param additional_nodes: list of nodes not in the config to distribute to
2981
  @type additional_vm: boolean
2982
  @param additional_vm: whether the additional nodes are vm-capable or not
2983

2984
  """
2985
  # 1. Gather target nodes
2986
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2987
  dist_nodes = lu.cfg.GetOnlineNodeList()
2988
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
2989
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
2990
  if additional_nodes is not None:
2991
    dist_nodes.extend(additional_nodes)
2992
    if additional_vm:
2993
      vm_nodes.extend(additional_nodes)
2994
  if myself.name in dist_nodes:
2995
    dist_nodes.remove(myself.name)
2996
  if myself.name in vm_nodes:
2997
    vm_nodes.remove(myself.name)
2998

    
2999
  # 2. Gather files to distribute
3000
  dist_files = set([constants.ETC_HOSTS,
3001
                    constants.SSH_KNOWN_HOSTS_FILE,
3002
                    constants.RAPI_CERT_FILE,
3003
                    constants.RAPI_USERS_FILE,
3004
                    constants.CONFD_HMAC_KEY,
3005
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3006
                   ])
3007

    
3008
  vm_files = set()
3009
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3010
  for hv_name in enabled_hypervisors:
3011
    hv_class = hypervisor.GetHypervisor(hv_name)
3012
    vm_files.update(hv_class.GetAncillaryFiles())
3013

    
3014
  # 3. Perform the files upload
3015
  for fname in dist_files:
3016
    _UploadHelper(lu, dist_nodes, fname)
3017
  for fname in vm_files:
3018
    _UploadHelper(lu, vm_nodes, fname)
3019

    
3020

    
3021
class LURedistributeConfig(NoHooksLU):
3022
  """Force the redistribution of cluster configuration.
3023

3024
  This is a very simple LU.
3025

3026
  """
3027
  REQ_BGL = False
3028

    
3029
  def ExpandNames(self):
3030
    self.needed_locks = {
3031
      locking.LEVEL_NODE: locking.ALL_SET,
3032
    }
3033
    self.share_locks[locking.LEVEL_NODE] = 1
3034

    
3035
  def Exec(self, feedback_fn):
3036
    """Redistribute the configuration.
3037

3038
    """
3039
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3040
    _RedistributeAncillaryFiles(self)
3041

    
3042

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

3046
  """
3047
  if not instance.disks or disks is not None and not disks:
3048
    return True
3049

    
3050
  disks = _ExpandCheckDisks(instance, disks)
3051

    
3052
  if not oneshot:
3053
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3054

    
3055
  node = instance.primary_node
3056

    
3057
  for dev in disks:
3058
    lu.cfg.SetDiskID(dev, node)
3059

    
3060
  # TODO: Convert to utils.Retry
3061

    
3062
  retries = 0
3063
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3064
  while True:
3065
    max_time = 0
3066
    done = True
3067
    cumul_degraded = False
3068
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3069
    msg = rstats.fail_msg
3070
    if msg:
3071
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3072
      retries += 1
3073
      if retries >= 10:
3074
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3075
                                 " aborting." % node)
3076
      time.sleep(6)
3077
      continue
3078
    rstats = rstats.payload
3079
    retries = 0
3080
    for i, mstat in enumerate(rstats):
3081
      if mstat is None:
3082
        lu.LogWarning("Can't compute data for node %s/%s",
3083
                           node, disks[i].iv_name)
3084
        continue
3085

    
3086
      cumul_degraded = (cumul_degraded or
3087
                        (mstat.is_degraded and mstat.sync_percent is None))
3088
      if mstat.sync_percent is not None:
3089
        done = False
3090
        if mstat.estimated_time is not None:
3091
          rem_time = ("%s remaining (estimated)" %
3092
                      utils.FormatSeconds(mstat.estimated_time))
3093
          max_time = mstat.estimated_time
3094
        else:
3095
          rem_time = "no time estimate"
3096
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3097
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3098

    
3099
    # if we're done but degraded, let's do a few small retries, to
3100
    # make sure we see a stable and not transient situation; therefore
3101
    # we force restart of the loop
3102
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3103
      logging.info("Degraded disks found, %d retries left", degr_retries)
3104
      degr_retries -= 1
3105
      time.sleep(1)
3106
      continue
3107

    
3108
    if done or oneshot:
3109
      break
3110

    
3111
    time.sleep(min(60, max_time))
3112

    
3113
  if done:
3114
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3115
  return not cumul_degraded
3116

    
3117

    
3118
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3119
  """Check that mirrors are not degraded.
3120

3121
  The ldisk parameter, if True, will change the test from the
3122
  is_degraded attribute (which represents overall non-ok status for
3123
  the device(s)) to the ldisk (representing the local storage status).
3124

3125
  """
3126
  lu.cfg.SetDiskID(dev, node)
3127

    
3128
  result = True
3129

    
3130
  if on_primary or dev.AssembleOnSecondary():
3131
    rstats = lu.rpc.call_blockdev_find(node, dev)
3132
    msg = rstats.fail_msg
3133
    if msg:
3134
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3135
      result = False
3136
    elif not rstats.payload:
3137
      lu.LogWarning("Can't find disk on node %s", node)
3138
      result = False
3139
    else:
3140
      if ldisk:
3141
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3142
      else:
3143
        result = result and not rstats.payload.is_degraded
3144

    
3145
  if dev.children:
3146
    for child in dev.children:
3147
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3148

    
3149
  return result
3150

    
3151

    
3152
class LUOobCommand(NoHooksLU):
3153
  """Logical unit for OOB handling.
3154

3155
  """
3156
  REG_BGL = False
3157

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

3161
    This checks:
3162
     - the node exists in the configuration
3163
     - OOB is supported
3164

3165
    Any errors are signaled by raising errors.OpPrereqError.
3166

3167
    """
3168
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3169
    node = self.cfg.GetNodeInfo(self.op.node_name)
3170

    
3171
    if node is None:
3172
      raise errors.OpPrereqError("Node %s not found" % self.op.node_name)
3173

    
3174
    self.oob_program = _SupportsOob(self.cfg, node)
3175

    
3176
    if not self.oob_program:
3177
      raise errors.OpPrereqError("OOB is not supported for node %s" %
3178
                                 self.op.node_name)
3179

    
3180
    if self.op.command == constants.OOB_POWER_OFF and not node.offline:
3181
      raise errors.OpPrereqError(("Cannot power off node %s because it is"
3182
                                  " not marked offline") % self.op.node_name)
3183

    
3184
    self.node = node
3185

    
3186
  def ExpandNames(self):
3187
    """Gather locks we need.
3188

3189
    """
3190
    node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3191
    self.needed_locks = {
3192
      locking.LEVEL_NODE: [node_name],
3193
      }
3194

    
3195
  def Exec(self, feedback_fn):
3196
    """Execute OOB and return result if we expect any.
3197

3198
    """
3199
    master_node = self.cfg.GetMasterNode()
3200
    node = self.node
3201

    
3202
    logging.info("Executing out-of-band command '%s' using '%s' on %s",
3203
                 self.op.command, self.oob_program, self.op.node_name)
3204
    result = self.rpc.call_run_oob(master_node, self.oob_program,
3205
                                   self.op.command, self.op.node_name,
3206
                                   self.op.timeout)
3207

    
3208
    result.Raise("An error occurred on execution of OOB helper")
3209

    
3210
    self._CheckPayload(result)
3211

    
3212
    if self.op.command == constants.OOB_HEALTH:
3213
      # For health we should log important events
3214
      for item, status in result.payload:
3215
        if status in [constants.OOB_STATUS_WARNING,
3216
                      constants.OOB_STATUS_CRITICAL]:
3217
          logging.warning("On node '%s' item '%s' has status '%s'",
3218
                          self.op.node_name, item, status)
3219

    
3220
    if self.op.command == constants.OOB_POWER_ON:
3221
      node.powered = True
3222
    elif self.op.command == constants.OOB_POWER_OFF:
3223
      node.powered = False
3224
    elif self.op.command == constants.OOB_POWER_STATUS:
3225
      powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3226
      if powered != self.node.powered:
3227
        logging.warning(("Recorded power state (%s) of node '%s' does not match"
3228
                         " actual power state (%s)"), node.powered,
3229
                        self.op.node_name, powered)
3230

    
3231
    self.cfg.Update(node, feedback_fn)
3232

    
3233
    return result.payload
3234

    
3235
  def _CheckPayload(self, result):
3236
    """Checks if the payload is valid.
3237

3238
    @param result: RPC result
3239
    @raises errors.OpExecError: If payload is not valid
3240

3241
    """
3242
    errs = []
3243
    if self.op.command == constants.OOB_HEALTH:
3244
      if not isinstance(result.payload, list):
3245
        errs.append("command 'health' is expected to return a list but got %s" %
3246
                    type(result.payload))
3247
      for item, status in result.payload:
3248
        if status not in constants.OOB_STATUSES:
3249
          errs.append("health item '%s' has invalid status '%s'" %
3250
                      (item, status))
3251

    
3252
    if self.op.command == constants.OOB_POWER_STATUS:
3253
      if not isinstance(result.payload, dict):
3254
        errs.append("power-status is expected to return a dict but got %s" %
3255
                    type(result.payload))
3256

    
3257
    if self.op.command in [
3258
        constants.OOB_POWER_ON,
3259
        constants.OOB_POWER_OFF,
3260
        constants.OOB_POWER_CYCLE,
3261
        ]:
3262
      if result.payload is not None:
3263
        errs.append("%s is expected to not return payload but got '%s'" %
3264
                    (self.op.command, result.payload))
3265

    
3266
    if errs:
3267
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3268
                               utils.CommaJoin(errs))
3269

    
3270

    
3271

    
3272
class LUDiagnoseOS(NoHooksLU):
3273
  """Logical unit for OS diagnose/query.
3274

3275
  """
3276
  REQ_BGL = False
3277
  _HID = "hidden"
3278
  _BLK = "blacklisted"
3279
  _VLD = "valid"
3280
  _FIELDS_STATIC = utils.FieldSet()
3281
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3282
                                   "parameters", "api_versions", _HID, _BLK)
3283

    
3284
  def CheckArguments(self):
3285
    if self.op.names:
3286
      raise errors.OpPrereqError("Selective OS query not supported",
3287
                                 errors.ECODE_INVAL)
3288

    
3289
    _CheckOutputFields(static=self._FIELDS_STATIC,
3290
                       dynamic=self._FIELDS_DYNAMIC,
3291
                       selected=self.op.output_fields)
3292

    
3293
  def ExpandNames(self):
3294
    # Lock all nodes, in shared mode
3295
    # Temporary removal of locks, should be reverted later
3296
    # TODO: reintroduce locks when they are lighter-weight
3297
    self.needed_locks = {}
3298
    #self.share_locks[locking.LEVEL_NODE] = 1
3299
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3300

    
3301
  @staticmethod
3302
  def _DiagnoseByOS(rlist):
3303
    """Remaps a per-node return list into an a per-os per-node dictionary
3304

3305
    @param rlist: a map with node names as keys and OS objects as values
3306

3307
    @rtype: dict
3308
    @return: a dictionary with osnames as keys and as value another
3309
        map, with nodes as keys and tuples of (path, status, diagnose,
3310
        variants, parameters, api_versions) as values, eg::
3311

3312
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3313
                                     (/srv/..., False, "invalid api")],
3314
                           "node2": [(/srv/..., True, "", [], [])]}
3315
          }
3316

3317
    """
3318
    all_os = {}
3319
    # we build here the list of nodes that didn't fail the RPC (at RPC
3320
    # level), so that nodes with a non-responding node daemon don't
3321
    # make all OSes invalid
3322
    good_nodes = [node_name for node_name in rlist
3323
                  if not rlist[node_name].fail_msg]
3324
    for node_name, nr in rlist.items():
3325
      if nr.fail_msg or not nr.payload:
3326
        continue
3327
      for (name, path, status, diagnose, variants,
3328
           params, api_versions) in nr.payload:
3329
        if name not in all_os:
3330
          # build a list of nodes for this os containing empty lists
3331
          # for each node in node_list
3332
          all_os[name] = {}
3333
          for nname in good_nodes:
3334
            all_os[name][nname] = []
3335
        # convert params from [name, help] to (name, help)
3336
        params = [tuple(v) for v in params]
3337
        all_os[name][node_name].append((path, status, diagnose,
3338
                                        variants, params, api_versions))
3339
    return all_os
3340

    
3341
  def Exec(self, feedback_fn):
3342
    """Compute the list of OSes.
3343

3344
    """
3345
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3346
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3347
    pol = self._DiagnoseByOS(node_data)
3348
    output = []
3349
    cluster = self.cfg.GetClusterInfo()
3350

    
3351
    for os_name in utils.NiceSort(pol.keys()):
3352
      os_data = pol[os_name]
3353
      row = []
3354
      valid = True
3355
      (variants, params, api_versions) = null_state = (set(), set(), set())
3356
      for idx, osl in enumerate(os_data.values()):
3357
        valid = bool(valid and osl and osl[0][1])
3358
        if not valid:
3359
          (variants, params, api_versions) = null_state
3360
          break
3361
        node_variants, node_params, node_api = osl[0][3:6]
3362
        if idx == 0: # first entry
3363
          variants = set(node_variants)
3364
          params = set(node_params)
3365
          api_versions = set(node_api)
3366
        else: # keep consistency
3367
          variants.intersection_update(node_variants)
3368
          params.intersection_update(node_params)
3369
          api_versions.intersection_update(node_api)
3370

    
3371
      is_hid = os_name in cluster.hidden_os
3372
      is_blk = os_name in cluster.blacklisted_os
3373
      if ((self._HID not in self.op.output_fields and is_hid) or
3374
          (self._BLK not in self.op.output_fields and is_blk) or
3375
          (self._VLD not in self.op.output_fields and not valid)):
3376
        continue
3377

    
3378
      for field in self.op.output_fields:
3379
        if field == "name":
3380
          val = os_name
3381
        elif field == self._VLD:
3382
          val = valid
3383
        elif field == "node_status":
3384
          # this is just a copy of the dict
3385
          val = {}
3386
          for node_name, nos_list in os_data.items():
3387
            val[node_name] = nos_list
3388
        elif field == "variants":
3389
          val = utils.NiceSort(list(variants))
3390
        elif field == "parameters":
3391
          val = list(params)
3392
        elif field == "api_versions":
3393
          val = list(api_versions)
3394
        elif field == self._HID:
3395
          val = is_hid
3396
        elif field == self._BLK:
3397
          val = is_blk
3398
        else:
3399
          raise errors.ParameterError(field)
3400
        row.append(val)
3401
      output.append(row)
3402

    
3403
    return output
3404

    
3405

    
3406
class LURemoveNode(LogicalUnit):
3407
  """Logical unit for removing a node.
3408

3409
  """
3410
  HPATH = "node-remove"
3411
  HTYPE = constants.HTYPE_NODE
3412

    
3413
  def BuildHooksEnv(self):
3414
    """Build hooks env.
3415

3416
    This doesn't run on the target node in the pre phase as a failed
3417
    node would then be impossible to remove.
3418

3419
    """
3420
    env = {
3421
      "OP_TARGET": self.op.node_name,
3422
      "NODE_NAME": self.op.node_name,
3423
      }
3424
    all_nodes = self.cfg.GetNodeList()
3425
    try:
3426
      all_nodes.remove(self.op.node_name)
3427
    except ValueError:
3428
      logging.warning("Node %s which is about to be removed not found"
3429
                      " in the all nodes list", self.op.node_name)
3430
    return env, all_nodes, all_nodes
3431

    
3432
  def CheckPrereq(self):
3433
    """Check prerequisites.
3434

3435
    This checks:
3436
     - the node exists in the configuration
3437
     - it does not have primary or secondary instances
3438
     - it's not the master
3439

3440
    Any errors are signaled by raising errors.OpPrereqError.
3441

3442
    """
3443
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3444
    node = self.cfg.GetNodeInfo(self.op.node_name)
3445
    assert node is not None
3446

    
3447
    instance_list = self.cfg.GetInstanceList()
3448

    
3449
    masternode = self.cfg.GetMasterNode()
3450
    if node.name == masternode:
3451
      raise errors.OpPrereqError("Node is the master node,"
3452
                                 " you need to failover first.",
3453
                                 errors.ECODE_INVAL)
3454

    
3455
    for instance_name in instance_list:
3456
      instance = self.cfg.GetInstanceInfo(instance_name)
3457
      if node.name in instance.all_nodes:
3458
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3459
                                   " please remove first." % instance_name,
3460
                                   errors.ECODE_INVAL)
3461
    self.op.node_name = node.name
3462
    self.node = node
3463

    
3464
  def Exec(self, feedback_fn):
3465
    """Removes the node from the cluster.
3466

3467
    """
3468
    node = self.node
3469
    logging.info("Stopping the node daemon and removing configs from node %s",
3470
                 node.name)
3471

    
3472
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3473

    
3474
    # Promote nodes to master candidate as needed
3475
    _AdjustCandidatePool(self, exceptions=[node.name])
3476
    self.context.RemoveNode(node.name)
3477

    
3478
    # Run post hooks on the node before it's removed
3479
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3480
    try:
3481
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3482
    except:
3483
      # pylint: disable-msg=W0702
3484
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3485

    
3486
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3487
    msg = result.fail_msg
3488
    if msg:
3489
      self.LogWarning("Errors encountered on the remote node while leaving"
3490
                      " the cluster: %s", msg)
3491

    
3492
    # Remove node from our /etc/hosts
3493
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3494
      master_node = self.cfg.GetMasterNode()
3495
      result = self.rpc.call_etc_hosts_modify(master_node,
3496
                                              constants.ETC_HOSTS_REMOVE,
3497
                                              node.name, None)
3498
      result.Raise("Can't update hosts file with new host data")
3499
      _RedistributeAncillaryFiles(self)
3500

    
3501

    
3502
class _NodeQuery(_QueryBase):
3503
  FIELDS = query.NODE_FIELDS
3504

    
3505
  def ExpandNames(self, lu):
3506
    lu.needed_locks = {}
3507
    lu.share_locks[locking.LEVEL_NODE] = 1
3508

    
3509
    if self.names:
3510
      self.wanted = _GetWantedNodes(lu, self.names)
3511
    else:
3512
      self.wanted = locking.ALL_SET
3513

    
3514
    self.do_locking = (self.use_locking and
3515
                       query.NQ_LIVE in self.requested_data)
3516

    
3517
    if self.do_locking:
3518
      # if we don't request only static fields, we need to lock the nodes
3519
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3520

    
3521
  def DeclareLocks(self, lu, level):
3522
    pass
3523

    
3524
  def _GetQueryData(self, lu):
3525
    """Computes the list of nodes and their attributes.
3526

3527
    """
3528
    all_info = lu.cfg.GetAllNodesInfo()
3529

    
3530
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3531

    
3532
    # Gather data as requested
3533
    if query.NQ_LIVE in self.requested_data:
3534
      node_data = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
3535
                                        lu.cfg.GetHypervisorType())
3536
      live_data = dict((name, nresult.payload)
3537
                       for (name, nresult) in node_data.items()
3538
                       if not nresult.fail_msg and nresult.payload)
3539
    else:
3540
      live_data = None
3541

    
3542
    if query.NQ_INST in self.requested_data:
3543
      node_to_primary = dict([(name, set()) for name in nodenames])
3544
      node_to_secondary = dict([(name, set()) for name in nodenames])
3545

    
3546
      inst_data = lu.cfg.GetAllInstancesInfo()
3547

    
3548
      for inst in inst_data.values():
3549
        if inst.primary_node in node_to_primary:
3550
          node_to_primary[inst.primary_node].add(inst.name)
3551
        for secnode in inst.secondary_nodes:
3552
          if secnode in node_to_secondary:
3553
            node_to_secondary[secnode].add(inst.name)
3554
    else:
3555
      node_to_primary = None
3556
      node_to_secondary = None
3557

    
3558
    if query.NQ_GROUP in self.requested_data:
3559
      groups = lu.cfg.GetAllNodeGroupsInfo()
3560
    else:
3561
      groups = {}
3562

    
3563
    return query.NodeQueryData([all_info[name] for name in nodenames],
3564
                               live_data, lu.cfg.GetMasterNode(),
3565
                               node_to_primary, node_to_secondary, groups)
3566

    
3567

    
3568
class LUQueryNodes(NoHooksLU):
3569
  """Logical unit for querying nodes.
3570

3571
  """
3572
  # pylint: disable-msg=W0142
3573
  REQ_BGL = False
3574

    
3575
  def CheckArguments(self):
3576
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3577
                         self.op.use_locking)
3578

    
3579
  def ExpandNames(self):
3580
    self.nq.ExpandNames(self)
3581

    
3582
  def Exec(self, feedback_fn):
3583
    return self.nq.OldStyleQuery(self)
3584

    
3585

    
3586
class LUQueryNodeVolumes(NoHooksLU):
3587
  """Logical unit for getting volumes on node(s).
3588

3589
  """
3590
  REQ_BGL = False
3591
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3592
  _FIELDS_STATIC = utils.FieldSet("node")
3593

    
3594
  def CheckArguments(self):
3595
    _CheckOutputFields(static=self._FIELDS_STATIC,
3596
                       dynamic=self._FIELDS_DYNAMIC,
3597
                       selected=self.op.output_fields)
3598

    
3599
  def ExpandNames(self):
3600
    self.needed_locks = {}
3601
    self.share_locks[locking.LEVEL_NODE] = 1
3602
    if not self.op.nodes:
3603
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3604
    else:
3605
      self.needed_locks[locking.LEVEL_NODE] = \
3606
        _GetWantedNodes(self, self.op.nodes)
3607

    
3608
  def Exec(self, feedback_fn):
3609
    """Computes the list of nodes and their attributes.
3610

3611
    """
3612
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3613
    volumes = self.rpc.call_node_volumes(nodenames)
3614

    
3615
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3616
             in self.cfg.GetInstanceList()]
3617

    
3618
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3619

    
3620
    output = []
3621
    for node in nodenames:
3622
      nresult = volumes[node]
3623
      if nresult.offline:
3624
        continue
3625
      msg = nresult.fail_msg
3626
      if msg:
3627
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3628
        continue
3629

    
3630
      node_vols = nresult.payload[:]
3631
      node_vols.sort(key=lambda vol: vol['dev'])
3632

    
3633
      for vol in node_vols:
3634
        node_output = []
3635
        for field in self.op.output_fields:
3636
          if field == "node":
3637
            val = node
3638
          elif field == "phys":
3639
            val = vol['dev']
3640
          elif field == "vg":
3641
            val = vol['vg']
3642
          elif field == "name":
3643
            val = vol['name']
3644
          elif field == "size":
3645
            val = int(float(vol['size']))
3646
          elif field == "instance":
3647
            for inst in ilist:
3648
              if node not in lv_by_node[inst]:
3649
                continue
3650
              if vol['name'] in lv_by_node[inst][node]:
3651
                val = inst.name
3652
                break
3653
            else:
3654
              val = '-'
3655
          else:
3656
            raise errors.ParameterError(field)
3657
          node_output.append(str(val))
3658

    
3659
        output.append(node_output)
3660

    
3661
    return output
3662

    
3663

    
3664
class LUQueryNodeStorage(NoHooksLU):
3665
  """Logical unit for getting information on storage units on node(s).
3666

3667
  """
3668
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3669
  REQ_BGL = False
3670

    
3671
  def CheckArguments(self):
3672
    _CheckOutputFields(static=self._FIELDS_STATIC,
3673
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3674
                       selected=self.op.output_fields)
3675

    
3676
  def ExpandNames(self):
3677
    self.needed_locks = {}
3678
    self.share_locks[locking.LEVEL_NODE] = 1
3679

    
3680
    if self.op.nodes:
3681
      self.needed_locks[locking.LEVEL_NODE] = \
3682
        _GetWantedNodes(self, self.op.nodes)
3683
    else:
3684
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3685

    
3686
  def Exec(self, feedback_fn):
3687
    """Computes the list of nodes and their attributes.
3688

3689
    """
3690
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3691

    
3692
    # Always get name to sort by
3693
    if constants.SF_NAME in self.op.output_fields:
3694
      fields = self.op.output_fields[:]
3695
    else:
3696
      fields = [constants.SF_NAME] + self.op.output_fields
3697

    
3698
    # Never ask for node or type as it's only known to the LU
3699
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3700
      while extra in fields:
3701
        fields.remove(extra)
3702

    
3703
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3704
    name_idx = field_idx[constants.SF_NAME]
3705

    
3706
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3707
    data = self.rpc.call_storage_list(self.nodes,
3708
                                      self.op.storage_type, st_args,
3709
                                      self.op.name, fields)
3710

    
3711
    result = []
3712

    
3713
    for node in utils.NiceSort(self.nodes):
3714
      nresult = data[node]
3715
      if nresult.offline:
3716
        continue
3717

    
3718
      msg = nresult.fail_msg
3719
      if msg:
3720
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3721
        continue
3722

    
3723
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3724

    
3725
      for name in utils.NiceSort(rows.keys()):
3726
        row = rows[name]
3727

    
3728
        out = []
3729

    
3730
        for field in self.op.output_fields:
3731
          if field == constants.SF_NODE:
3732
            val = node
3733
          elif field == constants.SF_TYPE:
3734
            val = self.op.storage_type
3735
          elif field in field_idx:
3736
            val = row[field_idx[field]]
3737
          else:
3738
            raise errors.ParameterError(field)
3739

    
3740
          out.append(val)
3741

    
3742
        result.append(out)
3743

    
3744
    return result
3745

    
3746

    
3747
class _InstanceQuery(_QueryBase):
3748
  FIELDS = query.INSTANCE_FIELDS
3749

    
3750
  def ExpandNames(self, lu):
3751
    lu.needed_locks = {}
3752
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
3753
    lu.share_locks[locking.LEVEL_NODE] = 1
3754

    
3755
    if self.names:
3756
      self.wanted = _GetWantedInstances(lu, self.names)
3757
    else:
3758
      self.wanted = locking.ALL_SET
3759

    
3760
    self.do_locking = (self.use_locking and
3761
                       query.IQ_LIVE in self.requested_data)
3762
    if self.do_locking:
3763
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3764
      lu.needed_locks[locking.LEVEL_NODE] = []
3765
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3766

    
3767
  def DeclareLocks(self, lu, level):
3768
    if level == locking.LEVEL_NODE and self.do_locking:
3769
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3770

    
3771
  def _GetQueryData(self, lu):
3772
    """Computes the list of instances and their attributes.
3773

3774
    """
3775
    all_info = lu.cfg.GetAllInstancesInfo()
3776

    
3777
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3778

    
3779
    instance_list = [all_info[name] for name in instance_names]
3780
    nodes = frozenset([inst.primary_node for inst in instance_list])
3781
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3782
    bad_nodes = []
3783
    offline_nodes = []
3784

    
3785
    # Gather data as requested
3786
    if query.IQ_LIVE in self.requested_data:
3787
      live_data = {}
3788
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
3789
      for name in nodes:
3790
        result = node_data[name]
3791
        if result.offline:
3792
          # offline nodes will be in both lists
3793
          assert result.fail_msg
3794
          offline_nodes.append(name)
3795
        if result.fail_msg:
3796
          bad_nodes.append(name)
3797
        elif result.payload:
3798
          live_data.update(result.payload)
3799
        # else no instance is alive
3800
    else:
3801
      live_data = {}
3802

    
3803
    if query.IQ_DISKUSAGE in self.requested_data:
3804
      disk_usage = dict((inst.name,
3805
                         _ComputeDiskSize(inst.disk_template,
3806
                                          [{"size": disk.size}
3807
                                           for disk in inst.disks]))
3808
                        for inst in instance_list)
3809
    else:
3810
      disk_usage = None
3811

    
3812
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
3813
                                   disk_usage, offline_nodes, bad_nodes,
3814
                                   live_data)
3815

    
3816

    
3817
class LUQuery(NoHooksLU):
3818
  """Query for resources/items of a certain kind.
3819

3820
  """
3821
  # pylint: disable-msg=W0142
3822
  REQ_BGL = False
3823

    
3824
  def CheckArguments(self):
3825
    qcls = _GetQueryImplementation(self.op.what)
3826
    names = qlang.ReadSimpleFilter("name", self.op.filter)
3827

    
3828
    self.impl = qcls(names, self.op.fields, False)
3829

    
3830
  def ExpandNames(self):
3831
    self.impl.ExpandNames(self)
3832

    
3833
  def DeclareLocks(self, level):
3834
    self.impl.DeclareLocks(self, level)
3835

    
3836
  def Exec(self, feedback_fn):
3837
    return self.impl.NewStyleQuery(self)
3838

    
3839

    
3840
class LUQueryFields(NoHooksLU):
3841
  """Query for resources/items of a certain kind.
3842

3843
  """
3844
  # pylint: disable-msg=W0142
3845
  REQ_BGL = False
3846

    
3847
  def CheckArguments(self):
3848
    self.qcls = _GetQueryImplementation(self.op.what)
3849

    
3850
  def ExpandNames(self):
3851
    self.needed_locks = {}
3852

    
3853
  def Exec(self, feedback_fn):
3854
    return self.qcls.FieldsQuery(self.op.fields)
3855

    
3856

    
3857
class LUModifyNodeStorage(NoHooksLU):
3858
  """Logical unit for modifying a storage volume on a node.
3859

3860
  """
3861
  REQ_BGL = False
3862

    
3863
  def CheckArguments(self):
3864
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3865

    
3866
    storage_type = self.op.storage_type
3867

    
3868
    try:
3869
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3870
    except KeyError:
3871
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3872
                                 " modified" % storage_type,
3873
                                 errors.ECODE_INVAL)
3874

    
3875
    diff = set(self.op.changes.keys()) - modifiable
3876
    if diff:
3877
      raise errors.OpPrereqError("The following fields can not be modified for"
3878
                                 " storage units of type '%s': %r" %
3879
                                 (storage_type, list(diff)),
3880
                                 errors.ECODE_INVAL)
3881

    
3882
  def ExpandNames(self):
3883
    self.needed_locks = {
3884
      locking.LEVEL_NODE: self.op.node_name,
3885
      }
3886

    
3887
  def Exec(self, feedback_fn):
3888
    """Computes the list of nodes and their attributes.
3889

3890
    """
3891
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3892
    result = self.rpc.call_storage_modify(self.op.node_name,
3893
                                          self.op.storage_type, st_args,
3894
                                          self.op.name, self.op.changes)
3895
    result.Raise("Failed to modify storage unit '%s' on %s" %
3896
                 (self.op.name, self.op.node_name))
3897

    
3898

    
3899
class LUAddNode(LogicalUnit):
3900
  """Logical unit for adding node to the cluster.
3901

3902
  """
3903
  HPATH = "node-add"
3904
  HTYPE = constants.HTYPE_NODE
3905
  _NFLAGS = ["master_capable", "vm_capable"]
3906

    
3907
  def CheckArguments(self):
3908
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3909
    # validate/normalize the node name
3910
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3911
                                         family=self.primary_ip_family)
3912
    self.op.node_name = self.hostname.name
3913
    if self.op.readd and self.op.group:
3914
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3915
                                 " being readded", errors.ECODE_INVAL)
3916

    
3917
  def BuildHooksEnv(self):
3918
    """Build hooks env.
3919

3920
    This will run on all nodes before, and on all nodes + the new node after.
3921

3922
    """
3923
    env = {
3924
      "OP_TARGET": self.op.node_name,
3925
      "NODE_NAME": self.op.node_name,
3926
      "NODE_PIP": self.op.primary_ip,
3927
      "NODE_SIP": self.op.secondary_ip,
3928
      "MASTER_CAPABLE": str(self.op.master_capable),
3929
      "VM_CAPABLE": str(self.op.vm_capable),
3930
      }
3931
    nodes_0 = self.cfg.GetNodeList()
3932
    nodes_1 = nodes_0 + [self.op.node_name, ]
3933
    return env, nodes_0, nodes_1
3934

    
3935
  def CheckPrereq(self):
3936
    """Check prerequisites.
3937

3938
    This checks:
3939
     - the new node is not already in the config
3940
     - it is resolvable
3941
     - its parameters (single/dual homed) matches the cluster
3942

3943
    Any errors are signaled by raising errors.OpPrereqError.
3944

3945
    """
3946
    cfg = self.cfg
3947
    hostname = self.hostname
3948
    node = hostname.name
3949
    primary_ip = self.op.primary_ip = hostname.ip
3950
    if self.op.secondary_ip is None:
3951
      if self.primary_ip_family == netutils.IP6Address.family:
3952
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3953
                                   " IPv4 address must be given as secondary",
3954
                                   errors.ECODE_INVAL)
3955
      self.op.secondary_ip = primary_ip
3956

    
3957
    secondary_ip = self.op.secondary_ip
3958
    if not netutils.IP4Address.IsValid(secondary_ip):
3959
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3960
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3961

    
3962
    node_list = cfg.GetNodeList()
3963
    if not self.op.readd and node in node_list:
3964
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3965
                                 node, errors.ECODE_EXISTS)
3966
    elif self.op.readd and node not in node_list:
3967
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3968
                                 errors.ECODE_NOENT)
3969

    
3970
    self.changed_primary_ip = False
3971

    
3972
    for existing_node_name in node_list:
3973
      existing_node = cfg.GetNodeInfo(existing_node_name)
3974

    
3975
      if self.op.readd and node == existing_node_name:
3976
        if existing_node.secondary_ip != secondary_ip:
3977
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3978
                                     " address configuration as before",
3979
                                     errors.ECODE_INVAL)
3980
        if existing_node.primary_ip != primary_ip:
3981
          self.changed_primary_ip = True
3982

    
3983
        continue
3984

    
3985
      if (existing_node.primary_ip == primary_ip or
3986
          existing_node.secondary_ip == primary_ip or
3987
          existing_node.primary_ip == secondary_ip or
3988
          existing_node.secondary_ip == secondary_ip):
3989
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3990
                                   " existing node %s" % existing_node.name,
3991
                                   errors.ECODE_NOTUNIQUE)
3992

    
3993
    # After this 'if' block, None is no longer a valid value for the
3994
    # _capable op attributes
3995
    if self.op.readd:
3996
      old_node = self.cfg.GetNodeInfo(node)
3997
      assert old_node is not None, "Can't retrieve locked node %s" % node
3998
      for attr in self._NFLAGS:
3999
        if getattr(self.op, attr) is None:
4000
          setattr(self.op, attr, getattr(old_node, attr))
4001
    else:
4002
      for attr in self._NFLAGS:
4003
        if getattr(self.op, attr) is None:
4004
          setattr(self.op, attr, True)
4005

    
4006
    if self.op.readd and not self.op.vm_capable:
4007
      pri, sec = cfg.GetNodeInstances(node)
4008
      if pri or sec:
4009
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4010
                                   " flag set to false, but it already holds"
4011
                                   " instances" % node,
4012
                                   errors.ECODE_STATE)
4013

    
4014
    # check that the type of the node (single versus dual homed) is the
4015
    # same as for the master
4016
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4017
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4018
    newbie_singlehomed = secondary_ip == primary_ip
4019
    if master_singlehomed != newbie_singlehomed:
4020
      if master_singlehomed:
4021
        raise errors.OpPrereqError("The master has no secondary ip but the"
4022
                                   " new node has one",
4023
                                   errors.ECODE_INVAL)
4024
      else:
4025
        raise errors.OpPrereqError("The master has a secondary ip but the"
4026
                                   " new node doesn't have one",
4027
                                   errors.ECODE_INVAL)
4028

    
4029
    # checks reachability
4030
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4031
      raise errors.OpPrereqError("Node not reachable by ping",
4032
                                 errors.ECODE_ENVIRON)
4033

    
4034
    if not newbie_singlehomed:
4035
      # check reachability from my secondary ip to newbie's secondary ip
4036
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4037
                           source=myself.secondary_ip):
4038
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4039
                                   " based ping to node daemon port",
4040
                                   errors.ECODE_ENVIRON)
4041

    
4042
    if self.op.readd:
4043
      exceptions = [node]
4044
    else:
4045
      exceptions = []
4046

    
4047
    if self.op.master_capable:
4048
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4049
    else:
4050
      self.master_candidate = False
4051

    
4052
    if self.op.readd:
4053
      self.new_node = old_node
4054
    else:
4055
      node_group = cfg.LookupNodeGroup(self.op.group)
4056
      self.new_node = objects.Node(name=node,
4057
                                   primary_ip=primary_ip,
4058
                                   secondary_ip=secondary_ip,
4059
                                   master_candidate=self.master_candidate,
4060
                                   offline=False, drained=False,
4061
                                   group=node_group)
4062

    
4063
    if self.op.ndparams:
4064
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4065

    
4066
  def Exec(self, feedback_fn):
4067
    """Adds the new node to the cluster.
4068

4069
    """
4070
    new_node = self.new_node
4071
    node = new_node.name
4072

    
4073
    # We adding a new node so we assume it's powered
4074
    new_node.powered = True
4075

    
4076
    # for re-adds, reset the offline/drained/master-candidate flags;
4077
    # we need to reset here, otherwise offline would prevent RPC calls
4078
    # later in the procedure; this also means that if the re-add
4079
    # fails, we are left with a non-offlined, broken node
4080
    if self.op.readd:
4081
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4082
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4083
      # if we demote the node, we do cleanup later in the procedure
4084
      new_node.master_candidate = self.master_candidate
4085
      if self.changed_primary_ip:
4086
        new_node.primary_ip = self.op.primary_ip
4087

    
4088
    # copy the master/vm_capable flags
4089
    for attr in self._NFLAGS:
4090
      setattr(new_node, attr, getattr(self.op, attr))
4091

    
4092
    # notify the user about any possible mc promotion
4093
    if new_node.master_candidate:
4094
      self.LogInfo("Node will be a master candidate")
4095

    
4096
    if self.op.ndparams:
4097
      new_node.ndparams = self.op.ndparams
4098
    else:
4099
      new_node.ndparams = {}
4100

    
4101
    # check connectivity
4102
    result = self.rpc.call_version([node])[node]
4103
    result.Raise("Can't get version information from node %s" % node)
4104
    if constants.PROTOCOL_VERSION == result.payload:
4105
      logging.info("Communication to node %s fine, sw version %s match",
4106
                   node, result.payload)
4107
    else:
4108
      raise errors.OpExecError("Version mismatch master version %s,"
4109
                               " node version %s" %
4110
                               (constants.PROTOCOL_VERSION, result.payload))
4111

    
4112
    # Add node to our /etc/hosts, and add key to known_hosts
4113
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4114
      master_node = self.cfg.GetMasterNode()
4115
      result = self.rpc.call_etc_hosts_modify(master_node,
4116
                                              constants.ETC_HOSTS_ADD,
4117
                                              self.hostname.name,
4118
                                              self.hostname.ip)
4119
      result.Raise("Can't update hosts file with new host data")
4120

    
4121
    if new_node.secondary_ip != new_node.primary_ip:
4122
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4123
                               False)
4124

    
4125
    node_verify_list = [self.cfg.GetMasterNode()]
4126
    node_verify_param = {
4127
      constants.NV_NODELIST: [node],
4128
      # TODO: do a node-net-test as well?
4129
    }
4130

    
4131
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4132
                                       self.cfg.GetClusterName())
4133
    for verifier in node_verify_list:
4134
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4135
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4136
      if nl_payload:
4137
        for failed in nl_payload:
4138
          feedback_fn("ssh/hostname verification failed"
4139
                      " (checking from %s): %s" %
4140
                      (verifier, nl_payload[failed]))
4141
        raise errors.OpExecError("ssh/hostname verification failed.")
4142

    
4143
    if self.op.readd:
4144
      _RedistributeAncillaryFiles(self)
4145
      self.context.ReaddNode(new_node)
4146
      # make sure we redistribute the config
4147
      self.cfg.Update(new_node, feedback_fn)
4148
      # and make sure the new node will not have old files around
4149
      if not new_node.master_candidate:
4150
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4151
        msg = result.fail_msg
4152
        if msg:
4153
          self.LogWarning("Node failed to demote itself from master"
4154
                          " candidate status: %s" % msg)
4155
    else:
4156
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4157
                                  additional_vm=self.op.vm_capable)
4158
      self.context.AddNode(new_node, self.proc.GetECId())
4159

    
4160

    
4161
class LUSetNodeParams(LogicalUnit):
4162
  """Modifies the parameters of a node.
4163

4164
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4165
      to the node role (as _ROLE_*)
4166
  @cvar _R2F: a dictionary from node role to tuples of flags
4167
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4168

4169
  """
4170
  HPATH = "node-modify"
4171
  HTYPE = constants.HTYPE_NODE
4172
  REQ_BGL = False
4173
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4174
  _F2R = {
4175
    (True, False, False): _ROLE_CANDIDATE,
4176
    (False, True, False): _ROLE_DRAINED,
4177
    (False, False, True): _ROLE_OFFLINE,
4178
    (False, False, False): _ROLE_REGULAR,
4179
    }
4180
  _R2F = dict((v, k) for k, v in _F2R.items())
4181
  _FLAGS = ["master_candidate", "drained", "offline"]
4182

    
4183
  def CheckArguments(self):
4184
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4185
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4186
                self.op.master_capable, self.op.vm_capable,
4187
                self.op.secondary_ip, self.op.ndparams]
4188
    if all_mods.count(None) == len(all_mods):
4189
      raise errors.OpPrereqError("Please pass at least one modification",
4190
                                 errors.ECODE_INVAL)
4191
    if all_mods.count(True) > 1:
4192
      raise errors.OpPrereqError("Can't set the node into more than one"
4193
                                 " state at the same time",
4194
                                 errors.ECODE_INVAL)
4195

    
4196
    # Boolean value that tells us whether we might be demoting from MC
4197
    self.might_demote = (self.op.master_candidate == False or
4198
                         self.op.offline == True or
4199
                         self.op.drained == True or
4200
                         self.op.master_capable == False)
4201

    
4202
    if self.op.secondary_ip:
4203
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4204
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4205
                                   " address" % self.op.secondary_ip,
4206
                                   errors.ECODE_INVAL)
4207

    
4208
    self.lock_all = self.op.auto_promote and self.might_demote
4209
    self.lock_instances = self.op.secondary_ip is not None
4210

    
4211
  def ExpandNames(self):
4212
    if self.lock_all:
4213
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4214
    else:
4215
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4216

    
4217
    if self.lock_instances:
4218
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4219

    
4220
  def DeclareLocks(self, level):
4221
    # If we have locked all instances, before waiting to lock nodes, release
4222
    # all the ones living on nodes unrelated to the current operation.
4223
    if level == locking.LEVEL_NODE and self.lock_instances:
4224
      instances_release = []
4225
      instances_keep = []
4226
      self.affected_instances = []
4227
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4228
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4229
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4230
          i_mirrored = instance.disk_template in constants.DTS_NET_MIRROR
4231
          if i_mirrored and self.op.node_name in instance.all_nodes:
4232
            instances_keep.append(instance_name)
4233
            self.affected_instances.append(instance)
4234
          else:
4235
            instances_release.append(instance_name)
4236
        if instances_release:
4237
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4238
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4239

    
4240
  def BuildHooksEnv(self):
4241
    """Build hooks env.
4242

4243
    This runs on the master node.
4244

4245
    """
4246
    env = {
4247
      "OP_TARGET": self.op.node_name,
4248
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4249
      "OFFLINE": str(self.op.offline),
4250
      "DRAINED": str(self.op.drained),
4251
      "MASTER_CAPABLE": str(self.op.master_capable),
4252
      "VM_CAPABLE": str(self.op.vm_capable),
4253
      }
4254
    nl = [self.cfg.GetMasterNode(),
4255
          self.op.node_name]
4256
    return env, nl, nl
4257

    
4258
  def CheckPrereq(self):
4259
    """Check prerequisites.
4260

4261
    This only checks the instance list against the existing names.
4262

4263
    """
4264
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4265

    
4266
    if (self.op.master_candidate is not None or
4267
        self.op.drained is not None or
4268
        self.op.offline is not None):
4269
      # we can't change the master's node flags
4270
      if self.op.node_name == self.cfg.GetMasterNode():
4271
        raise errors.OpPrereqError("The master role can be changed"
4272
                                   " only via master-failover",
4273
                                   errors.ECODE_INVAL)
4274

    
4275
    if self.op.master_candidate and not node.master_capable:
4276
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4277
                                 " it a master candidate" % node.name,
4278
                                 errors.ECODE_STATE)
4279

    
4280
    if self.op.vm_capable == False:
4281
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4282
      if ipri or isec:
4283
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4284
                                   " the vm_capable flag" % node.name,
4285
                                   errors.ECODE_STATE)
4286

    
4287
    if node.master_candidate and self.might_demote and not self.lock_all:
4288
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4289
      # check if after removing the current node, we're missing master
4290
      # candidates
4291
      (mc_remaining, mc_should, _) = \
4292
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4293
      if mc_remaining < mc_should:
4294
        raise errors.OpPrereqError("Not enough master candidates, please"
4295
                                   " pass auto_promote to allow promotion",
4296
                                   errors.ECODE_STATE)
4297

    
4298
    self.old_flags = old_flags = (node.master_candidate,
4299
                                  node.drained, node.offline)
4300
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4301
    self.old_role = old_role = self._F2R[old_flags]
4302

    
4303
    # Check for ineffective changes
4304
    for attr in self._FLAGS:
4305
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4306
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4307
        setattr(self.op, attr, None)
4308

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

    
4312
    # TODO: We might query the real power state if it supports OOB
4313
    if _SupportsOob(self.cfg, node):
4314
      if self.op.offline is False and not (node.powered or
4315
                                           self.op.powered == True):
4316
        raise errors.OpPrereqError(("Please power on node %s first before you"
4317
                                    " can reset offline state") %
4318
                                   self.op.node_name)
4319
    elif self.op.powered is not None:
4320
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4321
                                  " which does not support out-of-band"
4322
                                  " handling") % self.op.node_name)
4323

    
4324
    # If we're being deofflined/drained, we'll MC ourself if needed
4325
    if (self.op.drained == False or self.op.offline == False or
4326
        (self.op.master_capable and not node.master_capable)):
4327
      if _DecideSelfPromotion(self):
4328
        self.op.master_candidate = True
4329
        self.LogInfo("Auto-promoting node to master candidate")
4330

    
4331
    # If we're no longer master capable, we'll demote ourselves from MC
4332
    if self.op.master_capable == False and node.master_candidate:
4333
      self.LogInfo("Demoting from master candidate")
4334
      self.op.master_candidate = False
4335

    
4336
    # Compute new role
4337
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4338
    if self.op.master_candidate:
4339
      new_role = self._ROLE_CANDIDATE
4340
    elif self.op.drained:
4341
      new_role = self._ROLE_DRAINED
4342
    elif self.op.offline:
4343
      new_role = self._ROLE_OFFLINE
4344
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4345
      # False is still in new flags, which means we're un-setting (the
4346
      # only) True flag
4347
      new_role = self._ROLE_REGULAR
4348
    else: # no new flags, nothing, keep old role
4349
      new_role = old_role
4350

    
4351
    self.new_role = new_role
4352

    
4353
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4354
      # Trying to transition out of offline status
4355
      result = self.rpc.call_version([node.name])[node.name]
4356
      if result.fail_msg:
4357
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4358
                                   " to report its version: %s" %
4359
                                   (node.name, result.fail_msg),
4360
                                   errors.ECODE_STATE)
4361
      else:
4362
        self.LogWarning("Transitioning node from offline to online state"
4363
                        " without using re-add. Please make sure the node"
4364
                        " is healthy!")
4365

    
4366
    if self.op.secondary_ip:
4367
      # Ok even without locking, because this can't be changed by any LU
4368
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4369
      master_singlehomed = master.secondary_ip == master.primary_ip
4370
      if master_singlehomed and self.op.secondary_ip:
4371
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4372
                                   " homed cluster", errors.ECODE_INVAL)
4373

    
4374
      if node.offline:
4375
        if self.affected_instances:
4376
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4377
                                     " node has instances (%s) configured"
4378
                                     " to use it" % self.affected_instances)
4379
      else:
4380
        # On online nodes, check that no instances are running, and that
4381
        # the node has the new ip and we can reach it.
4382
        for instance in self.affected_instances:
4383
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4384

    
4385
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4386
        if master.name != node.name:
4387
          # check reachability from master secondary ip to new secondary ip
4388
          if not netutils.TcpPing(self.op.secondary_ip,
4389
                                  constants.DEFAULT_NODED_PORT,
4390
                                  source=master.secondary_ip):
4391
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4392
                                       " based ping to node daemon port",
4393
                                       errors.ECODE_ENVIRON)
4394

    
4395
    if self.op.ndparams:
4396
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4397
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4398
      self.new_ndparams = new_ndparams
4399

    
4400
  def Exec(self, feedback_fn):
4401
    """Modifies a node.
4402

4403
    """
4404
    node = self.node
4405
    old_role = self.old_role
4406
    new_role = self.new_role
4407

    
4408
    result = []
4409

    
4410
    if self.op.ndparams:
4411
      node.ndparams = self.new_ndparams
4412

    
4413
    if self.op.powered is not None:
4414
      node.powered = self.op.powered
4415

    
4416
    for attr in ["master_capable", "vm_capable"]:
4417
      val = getattr(self.op, attr)
4418
      if val is not None:
4419
        setattr(node, attr, val)
4420
        result.append((attr, str(val)))
4421

    
4422
    if new_role != old_role:
4423
      # Tell the node to demote itself, if no longer MC and not offline
4424
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4425
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4426
        if msg:
4427
          self.LogWarning("Node failed to demote itself: %s", msg)
4428

    
4429
      new_flags = self._R2F[new_role]
4430
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4431
        if of != nf:
4432
          result.append((desc, str(nf)))
4433
      (node.master_candidate, node.drained, node.offline) = new_flags
4434

    
4435
      # we locked all nodes, we adjust the CP before updating this node
4436
      if self.lock_all:
4437
        _AdjustCandidatePool(self, [node.name])
4438

    
4439
    if self.op.secondary_ip:
4440
      node.secondary_ip = self.op.secondary_ip
4441
      result.append(("secondary_ip", self.op.secondary_ip))
4442

    
4443
    # this will trigger configuration file update, if needed
4444
    self.cfg.Update(node, feedback_fn)
4445

    
4446
    # this will trigger job queue propagation or cleanup if the mc
4447
    # flag changed
4448
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4449
      self.context.ReaddNode(node)
4450

    
4451
    return result
4452

    
4453

    
4454
class LUPowercycleNode(NoHooksLU):
4455
  """Powercycles a node.
4456

4457
  """
4458
  REQ_BGL = False
4459

    
4460
  def CheckArguments(self):
4461
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4462
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4463
      raise errors.OpPrereqError("The node is the master and the force"
4464
                                 " parameter was not set",
4465
                                 errors.ECODE_INVAL)
4466

    
4467
  def ExpandNames(self):
4468
    """Locking for PowercycleNode.
4469

4470
    This is a last-resort option and shouldn't block on other
4471
    jobs. Therefore, we grab no locks.
4472

4473
    """
4474
    self.needed_locks = {}
4475

    
4476
  def Exec(self, feedback_fn):
4477
    """Reboots a node.
4478

4479
    """
4480
    result = self.rpc.call_node_powercycle(self.op.node_name,
4481
                                           self.cfg.GetHypervisorType())
4482
    result.Raise("Failed to schedule the reboot")
4483
    return result.payload
4484

    
4485

    
4486
class LUQueryClusterInfo(NoHooksLU):
4487
  """Query cluster configuration.
4488

4489
  """
4490
  REQ_BGL = False
4491

    
4492
  def ExpandNames(self):
4493
    self.needed_locks = {}
4494

    
4495
  def Exec(self, feedback_fn):
4496
    """Return cluster config.
4497

4498
    """
4499
    cluster = self.cfg.GetClusterInfo()
4500
    os_hvp = {}
4501

    
4502
    # Filter just for enabled hypervisors
4503
    for os_name, hv_dict in cluster.os_hvp.items():
4504
      os_hvp[os_name] = {}
4505
      for hv_name, hv_params in hv_dict.items():
4506
        if hv_name in cluster.enabled_hypervisors:
4507
          os_hvp[os_name][hv_name] = hv_params
4508

    
4509
    # Convert ip_family to ip_version
4510
    primary_ip_version = constants.IP4_VERSION
4511
    if cluster.primary_ip_family == netutils.IP6Address.family:
4512
      primary_ip_version = constants.IP6_VERSION
4513

    
4514
    result = {
4515
      "software_version": constants.RELEASE_VERSION,
4516
      "protocol_version": constants.PROTOCOL_VERSION,
4517
      "config_version": constants.CONFIG_VERSION,
4518
      "os_api_version": max(constants.OS_API_VERSIONS),
4519
      "export_version": constants.EXPORT_VERSION,
4520
      "architecture": (platform.architecture()[0], platform.machine()),
4521
      "name": cluster.cluster_name,
4522
      "master": cluster.master_node,
4523
      "default_hypervisor": cluster.enabled_hypervisors[0],
4524
      "enabled_hypervisors": cluster.enabled_hypervisors,
4525
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4526
                        for hypervisor_name in cluster.enabled_hypervisors]),
4527
      "os_hvp": os_hvp,
4528
      "beparams": cluster.beparams,
4529
      "osparams": cluster.osparams,
4530
      "nicparams": cluster.nicparams,
4531
      "candidate_pool_size": cluster.candidate_pool_size,
4532
      "master_netdev": cluster.master_netdev,
4533
      "volume_group_name": cluster.volume_group_name,
4534
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4535
      "file_storage_dir": cluster.file_storage_dir,
4536
      "maintain_node_health": cluster.maintain_node_health,
4537
      "ctime": cluster.ctime,
4538
      "mtime": cluster.mtime,
4539
      "uuid": cluster.uuid,
4540
      "tags": list(cluster.GetTags()),
4541
      "uid_pool": cluster.uid_pool,
4542
      "default_iallocator": cluster.default_iallocator,
4543
      "reserved_lvs": cluster.reserved_lvs,
4544
      "primary_ip_version": primary_ip_version,
4545
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4546
      }
4547

    
4548
    return result
4549

    
4550

    
4551
class LUQueryConfigValues(NoHooksLU):
4552
  """Return configuration values.
4553

4554
  """
4555
  REQ_BGL = False
4556
  _FIELDS_DYNAMIC = utils.FieldSet()
4557
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4558
                                  "watcher_pause", "volume_group_name")
4559

    
4560
  def CheckArguments(self):
4561
    _CheckOutputFields(static=self._FIELDS_STATIC,
4562
                       dynamic=self._FIELDS_DYNAMIC,
4563
                       selected=self.op.output_fields)
4564

    
4565
  def ExpandNames(self):
4566
    self.needed_locks = {}
4567

    
4568
  def Exec(self, feedback_fn):
4569
    """Dump a representation of the cluster config to the standard output.
4570

4571
    """
4572
    values = []
4573
    for field in self.op.output_fields:
4574
      if field == "cluster_name":
4575
        entry = self.cfg.GetClusterName()
4576
      elif field == "master_node":
4577
        entry = self.cfg.GetMasterNode()
4578
      elif field == "drain_flag":
4579
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4580
      elif field == "watcher_pause":
4581
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4582
      elif field == "volume_group_name":
4583
        entry = self.cfg.GetVGName()
4584
      else:
4585
        raise errors.ParameterError(field)
4586
      values.append(entry)
4587
    return values
4588

    
4589

    
4590
class LUActivateInstanceDisks(NoHooksLU):
4591
  """Bring up an instance's disks.
4592

4593
  """
4594
  REQ_BGL = False
4595

    
4596
  def ExpandNames(self):
4597
    self._ExpandAndLockInstance()
4598
    self.needed_locks[locking.LEVEL_NODE] = []
4599
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4600

    
4601
  def DeclareLocks(self, level):
4602
    if level == locking.LEVEL_NODE:
4603
      self._LockInstancesNodes()
4604

    
4605
  def CheckPrereq(self):
4606
    """Check prerequisites.
4607

4608
    This checks that the instance is in the cluster.
4609

4610
    """
4611
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4612
    assert self.instance is not None, \
4613
      "Cannot retrieve locked instance %s" % self.op.instance_name
4614
    _CheckNodeOnline(self, self.instance.primary_node)
4615

    
4616
  def Exec(self, feedback_fn):
4617
    """Activate the disks.
4618

4619
    """
4620
    disks_ok, disks_info = \
4621
              _AssembleInstanceDisks(self, self.instance,
4622
                                     ignore_size=self.op.ignore_size)
4623
    if not disks_ok:
4624
      raise errors.OpExecError("Cannot activate block devices")
4625

    
4626
    return disks_info
4627

    
4628

    
4629
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4630
                           ignore_size=False):
4631
  """Prepare the block devices for an instance.
4632

4633
  This sets up the block devices on all nodes.
4634

4635
  @type lu: L{LogicalUnit}
4636
  @param lu: the logical unit on whose behalf we execute
4637
  @type instance: L{objects.Instance}
4638
  @param instance: the instance for whose disks we assemble
4639
  @type disks: list of L{objects.Disk} or None
4640
  @param disks: which disks to assemble (or all, if None)
4641
  @type ignore_secondaries: boolean
4642
  @param ignore_secondaries: if true, errors on secondary nodes
4643
      won't result in an error return from the function
4644
  @type ignore_size: boolean
4645
  @param ignore_size: if true, the current known size of the disk
4646
      will not be used during the disk activation, useful for cases
4647
      when the size is wrong
4648
  @return: False if the operation failed, otherwise a list of
4649
      (host, instance_visible_name, node_visible_name)
4650
      with the mapping from node devices to instance devices
4651

4652
  """
4653
  device_info = []
4654
  disks_ok = True
4655
  iname = instance.name
4656
  disks = _ExpandCheckDisks(instance, disks)
4657

    
4658
  # With the two passes mechanism we try to reduce the window of
4659
  # opportunity for the race condition of switching DRBD to primary
4660
  # before handshaking occured, but we do not eliminate it
4661

    
4662
  # The proper fix would be to wait (with some limits) until the
4663
  # connection has been made and drbd transitions from WFConnection
4664
  # into any other network-connected state (Connected, SyncTarget,
4665
  # SyncSource, etc.)
4666

    
4667
  # 1st pass, assemble on all nodes in secondary mode
4668
  for inst_disk in disks:
4669
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4670
      if ignore_size:
4671
        node_disk = node_disk.Copy()
4672
        node_disk.UnsetSize()
4673
      lu.cfg.SetDiskID(node_disk, node)
4674
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4675
      msg = result.fail_msg
4676
      if msg:
4677
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4678
                           " (is_primary=False, pass=1): %s",
4679
                           inst_disk.iv_name, node, msg)
4680
        if not ignore_secondaries:
4681
          disks_ok = False
4682

    
4683
  # FIXME: race condition on drbd migration to primary
4684

    
4685
  # 2nd pass, do only the primary node
4686
  for inst_disk in disks:
4687
    dev_path = None
4688

    
4689
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4690
      if node != instance.primary_node:
4691
        continue
4692
      if ignore_size:
4693
        node_disk = node_disk.Copy()
4694
        node_disk.UnsetSize()
4695
      lu.cfg.SetDiskID(node_disk, node)
4696
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4697
      msg = result.fail_msg
4698
      if msg:
4699
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4700
                           " (is_primary=True, pass=2): %s",
4701
                           inst_disk.iv_name, node, msg)
4702
        disks_ok = False
4703
      else:
4704
        dev_path = result.payload
4705

    
4706
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4707

    
4708
  # leave the disks configured for the primary node
4709
  # this is a workaround that would be fixed better by
4710
  # improving the logical/physical id handling
4711
  for disk in disks:
4712
    lu.cfg.SetDiskID(disk, instance.primary_node)
4713

    
4714
  return disks_ok, device_info
4715

    
4716

    
4717
def _StartInstanceDisks(lu, instance, force):
4718
  """Start the disks of an instance.
4719

4720
  """
4721
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4722
                                           ignore_secondaries=force)
4723
  if not disks_ok:
4724
    _ShutdownInstanceDisks(lu, instance)
4725
    if force is not None and not force:
4726
      lu.proc.LogWarning("", hint="If the message above refers to a"
4727
                         " secondary node,"
4728
                         " you can retry the operation using '--force'.")
4729
    raise errors.OpExecError("Disk consistency error")
4730

    
4731

    
4732
class LUDeactivateInstanceDisks(NoHooksLU):
4733
  """Shutdown an instance's disks.
4734

4735
  """
4736
  REQ_BGL = False
4737

    
4738
  def ExpandNames(self):
4739
    self._ExpandAndLockInstance()
4740
    self.needed_locks[locking.LEVEL_NODE] = []
4741
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4742

    
4743
  def DeclareLocks(self, level):
4744
    if level == locking.LEVEL_NODE:
4745
      self._LockInstancesNodes()
4746

    
4747
  def CheckPrereq(self):
4748
    """Check prerequisites.
4749

4750
    This checks that the instance is in the cluster.
4751

4752
    """
4753
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4754
    assert self.instance is not None, \
4755
      "Cannot retrieve locked instance %s" % self.op.instance_name
4756

    
4757
  def Exec(self, feedback_fn):
4758
    """Deactivate the disks
4759

4760
    """
4761
    instance = self.instance
4762
    _SafeShutdownInstanceDisks(self, instance)
4763

    
4764

    
4765
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4766
  """Shutdown block devices of an instance.
4767

4768
  This function checks if an instance is running, before calling
4769
  _ShutdownInstanceDisks.
4770

4771
  """
4772
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4773
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4774

    
4775

    
4776
def _ExpandCheckDisks(instance, disks):
4777
  """Return the instance disks selected by the disks list
4778

4779
  @type disks: list of L{objects.Disk} or None
4780
  @param disks: selected disks
4781
  @rtype: list of L{objects.Disk}
4782
  @return: selected instance disks to act on
4783

4784
  """
4785
  if disks is None:
4786
    return instance.disks
4787
  else:
4788
    if not set(disks).issubset(instance.disks):
4789
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4790
                                   " target instance")
4791
    return disks
4792

    
4793

    
4794
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4795
  """Shutdown block devices of an instance.
4796

4797
  This does the shutdown on all nodes of the instance.
4798

4799
  If the ignore_primary is false, errors on the primary node are
4800
  ignored.
4801

4802
  """
4803
  all_result = True
4804
  disks = _ExpandCheckDisks(instance, disks)
4805

    
4806
  for disk in disks:
4807
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4808
      lu.cfg.SetDiskID(top_disk, node)
4809
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4810
      msg = result.fail_msg
4811
      if msg:
4812
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4813
                      disk.iv_name, node, msg)
4814
        if ((node == instance.primary_node and not ignore_primary) or
4815
            (node != instance.primary_node and not result.offline)):
4816
          all_result = False
4817
  return all_result
4818

    
4819

    
4820
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4821
  """Checks if a node has enough free memory.
4822

4823
  This function check if a given node has the needed amount of free
4824
  memory. In case the node has less memory or we cannot get the
4825
  information from the node, this function raise an OpPrereqError
4826
  exception.
4827

4828
  @type lu: C{LogicalUnit}
4829
  @param lu: a logical unit from which we get configuration data
4830
  @type node: C{str}
4831
  @param node: the node to check
4832
  @type reason: C{str}
4833
  @param reason: string to use in the error message
4834
  @type requested: C{int}
4835
  @param requested: the amount of memory in MiB to check for
4836
  @type hypervisor_name: C{str}
4837
  @param hypervisor_name: the hypervisor to ask for memory stats
4838
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4839
      we cannot check the node
4840

4841
  """
4842
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
4843
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4844
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4845
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4846
  if not isinstance(free_mem, int):
4847
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4848
                               " was '%s'" % (node, free_mem),
4849
                               errors.ECODE_ENVIRON)
4850
  if requested > free_mem:
4851
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4852
                               " needed %s MiB, available %s MiB" %
4853
                               (node, reason, requested, free_mem),
4854
                               errors.ECODE_NORES)
4855

    
4856

    
4857
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
4858
  """Checks if nodes have enough free disk space in the all VGs.
4859

4860
  This function check if all given nodes have the needed amount of
4861
  free disk. In case any node has less disk or we cannot get the
4862
  information from the node, this function raise an OpPrereqError
4863
  exception.
4864

4865
  @type lu: C{LogicalUnit}
4866
  @param lu: a logical unit from which we get configuration data
4867
  @type nodenames: C{list}
4868
  @param nodenames: the list of node names to check
4869
  @type req_sizes: C{dict}
4870
  @param req_sizes: the hash of vg and corresponding amount of disk in
4871
      MiB to check for
4872
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
4873
      or we cannot check the node
4874

4875
  """
4876
  if req_sizes is not None:
4877
    for vg, req_size in req_sizes.iteritems():
4878
      _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
4879

    
4880

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

4884
  This function check if all given nodes have the needed amount of
4885
  free disk. In case any node has less disk or we cannot get the
4886
  information from the node, this function raise an OpPrereqError
4887
  exception.
4888

4889
  @type lu: C{LogicalUnit}
4890
  @param lu: a logical unit from which we get configuration data
4891
  @type nodenames: C{list}
4892
  @param nodenames: the list of node names to check
4893
  @type vg: C{str}
4894
  @param vg: the volume group to check
4895
  @type requested: C{int}
4896
  @param requested: the amount of disk in MiB to check for
4897
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
4898
      or we cannot check the node
4899

4900
  """
4901
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
4902
  for node in nodenames:
4903
    info = nodeinfo[node]
4904
    info.Raise("Cannot get current information from node %s" % node,
4905
               prereq=True, ecode=errors.ECODE_ENVIRON)
4906
    vg_free = info.payload.get("vg_free", None)
4907
    if not isinstance(vg_free, int):
4908
      raise errors.OpPrereqError("Can't compute free disk space on node"
4909
                                 " %s for vg %s, result was '%s'" %
4910
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
4911
    if requested > vg_free:
4912
      raise errors.OpPrereqError("Not enough disk space on target node %s"
4913
                                 " vg %s: required %d MiB, available %d MiB" %
4914
                                 (node, vg, requested, vg_free),
4915
                                 errors.ECODE_NORES)
4916

    
4917

    
4918
class LUStartupInstance(LogicalUnit):
4919
  """Starts an instance.
4920

4921
  """
4922
  HPATH = "instance-start"
4923
  HTYPE = constants.HTYPE_INSTANCE
4924
  REQ_BGL = False
4925

    
4926
  def CheckArguments(self):
4927
    # extra beparams
4928
    if self.op.beparams:
4929
      # fill the beparams dict
4930
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4931

    
4932
  def ExpandNames(self):
4933
    self._ExpandAndLockInstance()
4934

    
4935
  def BuildHooksEnv(self):
4936
    """Build hooks env.
4937

4938
    This runs on master, primary and secondary nodes of the instance.
4939

4940
    """
4941
    env = {
4942
      "FORCE": self.op.force,
4943
      }
4944
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4945
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4946
    return env, nl, nl
4947

    
4948
  def CheckPrereq(self):
4949
    """Check prerequisites.
4950

4951
    This checks that the instance is in the cluster.
4952

4953
    """
4954
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4955
    assert self.instance is not None, \
4956
      "Cannot retrieve locked instance %s" % self.op.instance_name
4957

    
4958
    # extra hvparams
4959
    if self.op.hvparams:
4960
      # check hypervisor parameter syntax (locally)
4961
      cluster = self.cfg.GetClusterInfo()
4962
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4963
      filled_hvp = cluster.FillHV(instance)
4964
      filled_hvp.update(self.op.hvparams)
4965
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4966
      hv_type.CheckParameterSyntax(filled_hvp)
4967
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4968

    
4969
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4970

    
4971
    if self.primary_offline and self.op.ignore_offline_nodes:
4972
      self.proc.LogWarning("Ignoring offline primary node")
4973

    
4974
      if self.op.hvparams or self.op.beparams:
4975
        self.proc.LogWarning("Overridden parameters are ignored")
4976
    else:
4977
      _CheckNodeOnline(self, instance.primary_node)
4978

    
4979
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4980

    
4981
      # check bridges existence
4982
      _CheckInstanceBridgesExist(self, instance)
4983

    
4984
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4985
                                                instance.name,
4986
                                                instance.hypervisor)
4987
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4988
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4989
      if not remote_info.payload: # not running already
4990
        _CheckNodeFreeMemory(self, instance.primary_node,
4991
                             "starting instance %s" % instance.name,
4992
                             bep[constants.BE_MEMORY], instance.hypervisor)
4993

    
4994
  def Exec(self, feedback_fn):
4995
    """Start the instance.
4996

4997
    """
4998
    instance = self.instance
4999
    force = self.op.force
5000

    
5001
    self.cfg.MarkInstanceUp(instance.name)
5002

    
5003
    if self.primary_offline:
5004
      assert self.op.ignore_offline_nodes
5005
      self.proc.LogInfo("Primary node offline, marked instance as started")
5006
    else:
5007
      node_current = instance.primary_node
5008

    
5009
      _StartInstanceDisks(self, instance, force)
5010

    
5011
      result = self.rpc.call_instance_start(node_current, instance,
5012
                                            self.op.hvparams, self.op.beparams)
5013
      msg = result.fail_msg
5014
      if msg:
5015
        _ShutdownInstanceDisks(self, instance)
5016
        raise errors.OpExecError("Could not start instance: %s" % msg)
5017

    
5018

    
5019
class LURebootInstance(LogicalUnit):
5020
  """Reboot an instance.
5021

5022
  """
5023
  HPATH = "instance-reboot"
5024
  HTYPE = constants.HTYPE_INSTANCE
5025
  REQ_BGL = False
5026

    
5027
  def ExpandNames(self):
5028
    self._ExpandAndLockInstance()
5029

    
5030
  def BuildHooksEnv(self):
5031
    """Build hooks env.
5032

5033
    This runs on master, primary and secondary nodes of the instance.
5034

5035
    """
5036
    env = {
5037
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5038
      "REBOOT_TYPE": self.op.reboot_type,
5039
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5040
      }
5041
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5042
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5043
    return env, nl, nl
5044

    
5045
  def CheckPrereq(self):
5046
    """Check prerequisites.
5047

5048
    This checks that the instance is in the cluster.
5049

5050
    """
5051
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5052
    assert self.instance is not None, \
5053
      "Cannot retrieve locked instance %s" % self.op.instance_name
5054

    
5055
    _CheckNodeOnline(self, instance.primary_node)
5056

    
5057
    # check bridges existence
5058
    _CheckInstanceBridgesExist(self, instance)
5059

    
5060
  def Exec(self, feedback_fn):
5061
    """Reboot the instance.
5062

5063
    """
5064
    instance = self.instance
5065
    ignore_secondaries = self.op.ignore_secondaries
5066
    reboot_type = self.op.reboot_type
5067

    
5068
    node_current = instance.primary_node
5069

    
5070
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5071
                       constants.INSTANCE_REBOOT_HARD]:
5072
      for disk in instance.disks:
5073
        self.cfg.SetDiskID(disk, node_current)
5074
      result = self.rpc.call_instance_reboot(node_current, instance,
5075
                                             reboot_type,
5076
                                             self.op.shutdown_timeout)
5077
      result.Raise("Could not reboot instance")
5078
    else:
5079
      result = self.rpc.call_instance_shutdown(node_current, instance,
5080
                                               self.op.shutdown_timeout)
5081
      result.Raise("Could not shutdown instance for full reboot")
5082
      _ShutdownInstanceDisks(self, instance)
5083
      _StartInstanceDisks(self, instance, ignore_secondaries)
5084
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5085
      msg = result.fail_msg
5086
      if msg:
5087
        _ShutdownInstanceDisks(self, instance)
5088
        raise errors.OpExecError("Could not start instance for"
5089
                                 " full reboot: %s" % msg)
5090

    
5091
    self.cfg.MarkInstanceUp(instance.name)
5092

    
5093

    
5094
class LUShutdownInstance(LogicalUnit):
5095
  """Shutdown an instance.
5096

5097
  """
5098
  HPATH = "instance-stop"
5099
  HTYPE = constants.HTYPE_INSTANCE
5100
  REQ_BGL = False
5101

    
5102
  def ExpandNames(self):
5103
    self._ExpandAndLockInstance()
5104

    
5105
  def BuildHooksEnv(self):
5106
    """Build hooks env.
5107

5108
    This runs on master, primary and secondary nodes of the instance.
5109

5110
    """
5111
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5112
    env["TIMEOUT"] = self.op.timeout
5113
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5114
    return env, nl, nl
5115

    
5116
  def CheckPrereq(self):
5117
    """Check prerequisites.
5118

5119
    This checks that the instance is in the cluster.
5120

5121
    """
5122
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5123
    assert self.instance is not None, \
5124
      "Cannot retrieve locked instance %s" % self.op.instance_name
5125

    
5126
    self.primary_offline = \
5127
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5128

    
5129
    if self.primary_offline and self.op.ignore_offline_nodes:
5130
      self.proc.LogWarning("Ignoring offline primary node")
5131
    else:
5132
      _CheckNodeOnline(self, self.instance.primary_node)
5133

    
5134
  def Exec(self, feedback_fn):
5135
    """Shutdown the instance.
5136

5137
    """
5138
    instance = self.instance
5139
    node_current = instance.primary_node
5140
    timeout = self.op.timeout
5141

    
5142
    self.cfg.MarkInstanceDown(instance.name)
5143

    
5144
    if self.primary_offline:
5145
      assert self.op.ignore_offline_nodes
5146
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5147
    else:
5148
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5149
      msg = result.fail_msg
5150
      if msg:
5151
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5152

    
5153
      _ShutdownInstanceDisks(self, instance)
5154

    
5155

    
5156
class LUReinstallInstance(LogicalUnit):
5157
  """Reinstall an instance.
5158

5159
  """
5160
  HPATH = "instance-reinstall"
5161
  HTYPE = constants.HTYPE_INSTANCE
5162
  REQ_BGL = False
5163

    
5164
  def ExpandNames(self):
5165
    self._ExpandAndLockInstance()
5166

    
5167
  def BuildHooksEnv(self):
5168
    """Build hooks env.
5169

5170
    This runs on master, primary and secondary nodes of the instance.
5171

5172
    """
5173
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5174
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5175
    return env, nl, nl
5176

    
5177
  def CheckPrereq(self):
5178
    """Check prerequisites.
5179

5180
    This checks that the instance is in the cluster and is not running.
5181

5182
    """
5183
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5184
    assert instance is not None, \
5185
      "Cannot retrieve locked instance %s" % self.op.instance_name
5186
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5187
                     " offline, cannot reinstall")
5188
    for node in instance.secondary_nodes:
5189
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5190
                       " cannot reinstall")
5191

    
5192
    if instance.disk_template == constants.DT_DISKLESS:
5193
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5194
                                 self.op.instance_name,
5195
                                 errors.ECODE_INVAL)
5196
    _CheckInstanceDown(self, instance, "cannot reinstall")
5197

    
5198
    if self.op.os_type is not None:
5199
      # OS verification
5200
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5201
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5202
      instance_os = self.op.os_type
5203
    else:
5204
      instance_os = instance.os
5205

    
5206
    nodelist = list(instance.all_nodes)
5207

    
5208
    if self.op.osparams:
5209
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5210
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5211
      self.os_inst = i_osdict # the new dict (without defaults)
5212
    else:
5213
      self.os_inst = None
5214

    
5215
    self.instance = instance
5216

    
5217
  def Exec(self, feedback_fn):
5218
    """Reinstall the instance.
5219

5220
    """
5221
    inst = self.instance
5222

    
5223
    if self.op.os_type is not None:
5224
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5225
      inst.os = self.op.os_type
5226
      # Write to configuration
5227
      self.cfg.Update(inst, feedback_fn)
5228

    
5229
    _StartInstanceDisks(self, inst, None)
5230
    try:
5231
      feedback_fn("Running the instance OS create scripts...")
5232
      # FIXME: pass debug option from opcode to backend
5233
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5234
                                             self.op.debug_level,
5235
                                             osparams=self.os_inst)
5236
      result.Raise("Could not install OS for instance %s on node %s" %
5237
                   (inst.name, inst.primary_node))
5238
    finally:
5239
      _ShutdownInstanceDisks(self, inst)
5240

    
5241

    
5242
class LURecreateInstanceDisks(LogicalUnit):
5243
  """Recreate an instance's missing disks.
5244

5245
  """
5246
  HPATH = "instance-recreate-disks"
5247
  HTYPE = constants.HTYPE_INSTANCE
5248
  REQ_BGL = False
5249

    
5250
  def ExpandNames(self):
5251
    self._ExpandAndLockInstance()
5252

    
5253
  def BuildHooksEnv(self):
5254
    """Build hooks env.
5255

5256
    This runs on master, primary and secondary nodes of the instance.
5257

5258
    """
5259
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5260
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5261
    return env, nl, nl
5262

    
5263
  def CheckPrereq(self):
5264
    """Check prerequisites.
5265

5266
    This checks that the instance is in the cluster and is not running.
5267

5268
    """
5269
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5270
    assert instance is not None, \
5271
      "Cannot retrieve locked instance %s" % self.op.instance_name
5272
    _CheckNodeOnline(self, instance.primary_node)
5273

    
5274
    if instance.disk_template == constants.DT_DISKLESS:
5275
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5276
                                 self.op.instance_name, errors.ECODE_INVAL)
5277
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5278

    
5279
    if not self.op.disks:
5280
      self.op.disks = range(len(instance.disks))
5281
    else:
5282
      for idx in self.op.disks:
5283
        if idx >= len(instance.disks):
5284
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5285
                                     errors.ECODE_INVAL)
5286

    
5287
    self.instance = instance
5288

    
5289
  def Exec(self, feedback_fn):
5290
    """Recreate the disks.
5291

5292
    """
5293
    to_skip = []
5294
    for idx, _ in enumerate(self.instance.disks):
5295
      if idx not in self.op.disks: # disk idx has not been passed in
5296
        to_skip.append(idx)
5297
        continue
5298

    
5299
    _CreateDisks(self, self.instance, to_skip=to_skip)
5300

    
5301

    
5302
class LURenameInstance(LogicalUnit):
5303
  """Rename an instance.
5304

5305
  """
5306
  HPATH = "instance-rename"
5307
  HTYPE = constants.HTYPE_INSTANCE
5308

    
5309
  def CheckArguments(self):
5310
    """Check arguments.
5311

5312
    """
5313
    if self.op.ip_check and not self.op.name_check:
5314
      # TODO: make the ip check more flexible and not depend on the name check
5315
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5316
                                 errors.ECODE_INVAL)
5317

    
5318
  def BuildHooksEnv(self):
5319
    """Build hooks env.
5320

5321
    This runs on master, primary and secondary nodes of the instance.
5322

5323
    """
5324
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5325
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5326
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5327
    return env, nl, nl
5328

    
5329
  def CheckPrereq(self):
5330
    """Check prerequisites.
5331

5332
    This checks that the instance is in the cluster and is not running.
5333

5334
    """
5335
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5336
                                                self.op.instance_name)
5337
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5338
    assert instance is not None
5339
    _CheckNodeOnline(self, instance.primary_node)
5340
    _CheckInstanceDown(self, instance, "cannot rename")
5341
    self.instance = instance
5342

    
5343
    new_name = self.op.new_name
5344
    if self.op.name_check:
5345
      hostname = netutils.GetHostname(name=new_name)
5346
      self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5347
                   hostname.name)
5348
      new_name = self.op.new_name = hostname.name
5349
      if (self.op.ip_check and
5350
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5351
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5352
                                   (hostname.ip, new_name),
5353
                                   errors.ECODE_NOTUNIQUE)
5354

    
5355
    instance_list = self.cfg.GetInstanceList()
5356
    if new_name in instance_list and new_name != instance.name:
5357
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5358
                                 new_name, errors.ECODE_EXISTS)
5359

    
5360
  def Exec(self, feedback_fn):
5361
    """Rename the instance.
5362

5363
    """
5364
    inst = self.instance
5365
    old_name = inst.name
5366

    
5367
    rename_file_storage = False
5368
    if (inst.disk_template == constants.DT_FILE and
5369
        self.op.new_name != inst.name):
5370
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5371
      rename_file_storage = True
5372

    
5373
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5374
    # Change the instance lock. This is definitely safe while we hold the BGL
5375
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5376
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5377

    
5378
    # re-read the instance from the configuration after rename
5379
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5380

    
5381
    if rename_file_storage:
5382
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5383
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5384
                                                     old_file_storage_dir,
5385
                                                     new_file_storage_dir)
5386
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5387
                   " (but the instance has been renamed in Ganeti)" %
5388
                   (inst.primary_node, old_file_storage_dir,
5389
                    new_file_storage_dir))
5390

    
5391
    _StartInstanceDisks(self, inst, None)
5392
    try:
5393
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5394
                                                 old_name, self.op.debug_level)
5395
      msg = result.fail_msg
5396
      if msg:
5397
        msg = ("Could not run OS rename script for instance %s on node %s"
5398
               " (but the instance has been renamed in Ganeti): %s" %
5399
               (inst.name, inst.primary_node, msg))
5400
        self.proc.LogWarning(msg)
5401
    finally:
5402
      _ShutdownInstanceDisks(self, inst)
5403

    
5404
    return inst.name
5405

    
5406

    
5407
class LURemoveInstance(LogicalUnit):
5408
  """Remove an instance.
5409

5410
  """
5411
  HPATH = "instance-remove"
5412
  HTYPE = constants.HTYPE_INSTANCE
5413
  REQ_BGL = False
5414

    
5415
  def ExpandNames(self):
5416
    self._ExpandAndLockInstance()
5417
    self.needed_locks[locking.LEVEL_NODE] = []
5418
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5419

    
5420
  def DeclareLocks(self, level):
5421
    if level == locking.LEVEL_NODE:
5422
      self._LockInstancesNodes()
5423

    
5424
  def BuildHooksEnv(self):
5425
    """Build hooks env.
5426

5427
    This runs on master, primary and secondary nodes of the instance.
5428

5429
    """
5430
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5431
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5432
    nl = [self.cfg.GetMasterNode()]
5433
    nl_post = list(self.instance.all_nodes) + nl
5434
    return env, nl, nl_post
5435

    
5436
  def CheckPrereq(self):
5437
    """Check prerequisites.
5438

5439
    This checks that the instance is in the cluster.
5440

5441
    """
5442
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5443
    assert self.instance is not None, \
5444
      "Cannot retrieve locked instance %s" % self.op.instance_name
5445

    
5446
  def Exec(self, feedback_fn):
5447
    """Remove the instance.
5448

5449
    """
5450
    instance = self.instance
5451
    logging.info("Shutting down instance %s on node %s",
5452
                 instance.name, instance.primary_node)
5453

    
5454
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5455
                                             self.op.shutdown_timeout)
5456
    msg = result.fail_msg
5457
    if msg:
5458
      if self.op.ignore_failures:
5459
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5460
      else:
5461
        raise errors.OpExecError("Could not shutdown instance %s on"
5462
                                 " node %s: %s" %
5463
                                 (instance.name, instance.primary_node, msg))
5464

    
5465
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5466

    
5467

    
5468
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5469
  """Utility function to remove an instance.
5470

5471
  """
5472
  logging.info("Removing block devices for instance %s", instance.name)
5473

    
5474
  if not _RemoveDisks(lu, instance):
5475
    if not ignore_failures:
5476
      raise errors.OpExecError("Can't remove instance's disks")
5477
    feedback_fn("Warning: can't remove instance's disks")
5478

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

    
5481
  lu.cfg.RemoveInstance(instance.name)
5482

    
5483
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5484
    "Instance lock removal conflict"
5485

    
5486
  # Remove lock for the instance
5487
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5488

    
5489

    
5490
class LUQueryInstances(NoHooksLU):
5491
  """Logical unit for querying instances.
5492

5493
  """
5494
  # pylint: disable-msg=W0142
5495
  REQ_BGL = False
5496

    
5497
  def CheckArguments(self):
5498
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5499
                             self.op.use_locking)
5500

    
5501
  def ExpandNames(self):
5502
    self.iq.ExpandNames(self)
5503

    
5504
  def DeclareLocks(self, level):
5505
    self.iq.DeclareLocks(self, level)
5506

    
5507
  def Exec(self, feedback_fn):
5508
    return self.iq.OldStyleQuery(self)
5509

    
5510

    
5511
class LUFailoverInstance(LogicalUnit):
5512
  """Failover an instance.
5513

5514
  """
5515
  HPATH = "instance-failover"
5516
  HTYPE = constants.HTYPE_INSTANCE
5517
  REQ_BGL = False
5518

    
5519
  def ExpandNames(self):
5520
    self._ExpandAndLockInstance()
5521
    self.needed_locks[locking.LEVEL_NODE] = []
5522
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5523

    
5524
  def DeclareLocks(self, level):
5525
    if level == locking.LEVEL_NODE:
5526
      self._LockInstancesNodes()
5527

    
5528
  def BuildHooksEnv(self):
5529
    """Build hooks env.
5530

5531
    This runs on master, primary and secondary nodes of the instance.
5532

5533
    """
5534
    instance = self.instance
5535
    source_node = instance.primary_node
5536
    target_node = instance.secondary_nodes[0]
5537
    env = {
5538
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5539
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5540
      "OLD_PRIMARY": source_node,
5541
      "OLD_SECONDARY": target_node,
5542
      "NEW_PRIMARY": target_node,
5543
      "NEW_SECONDARY": source_node,
5544
      }
5545
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5546
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5547
    nl_post = list(nl)
5548
    nl_post.append(source_node)
5549
    return env, nl, nl_post
5550

    
5551
  def CheckPrereq(self):
5552
    """Check prerequisites.
5553

5554
    This checks that the instance is in the cluster.
5555

5556
    """
5557
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5558
    assert self.instance is not None, \
5559
      "Cannot retrieve locked instance %s" % self.op.instance_name
5560

    
5561
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5562
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5563
      raise errors.OpPrereqError("Instance's disk layout is not"
5564
                                 " network mirrored, cannot failover.",
5565
                                 errors.ECODE_STATE)
5566

    
5567
    secondary_nodes = instance.secondary_nodes
5568
    if not secondary_nodes:
5569
      raise errors.ProgrammerError("no secondary node but using "
5570
                                   "a mirrored disk template")
5571

    
5572
    target_node = secondary_nodes[0]
5573
    _CheckNodeOnline(self, target_node)
5574
    _CheckNodeNotDrained(self, target_node)
5575
    if instance.admin_up:
5576
      # check memory requirements on the secondary node
5577
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5578
                           instance.name, bep[constants.BE_MEMORY],
5579
                           instance.hypervisor)
5580
    else:
5581
      self.LogInfo("Not checking memory on the secondary node as"
5582
                   " instance will not be started")
5583

    
5584
    # check bridge existance
5585
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5586

    
5587
  def Exec(self, feedback_fn):
5588
    """Failover an instance.
5589

5590
    The failover is done by shutting it down on its present node and
5591
    starting it on the secondary.
5592

5593
    """
5594
    instance = self.instance
5595
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5596

    
5597
    source_node = instance.primary_node
5598
    target_node = instance.secondary_nodes[0]
5599

    
5600
    if instance.admin_up:
5601
      feedback_fn("* checking disk consistency between source and target")
5602
      for dev in instance.disks:
5603
        # for drbd, these are drbd over lvm
5604
        if not _CheckDiskConsistency(self, dev, target_node, False):
5605
          if not self.op.ignore_consistency:
5606
            raise errors.OpExecError("Disk %s is degraded on target node,"
5607
                                     " aborting failover." % dev.iv_name)
5608
    else:
5609
      feedback_fn("* not checking disk consistency as instance is not running")
5610

    
5611
    feedback_fn("* shutting down instance on source node")
5612
    logging.info("Shutting down instance %s on node %s",
5613
                 instance.name, source_node)
5614

    
5615
    result = self.rpc.call_instance_shutdown(source_node, instance,
5616
                                             self.op.shutdown_timeout)
5617
    msg = result.fail_msg
5618
    if msg:
5619
      if self.op.ignore_consistency or primary_node.offline:
5620
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5621
                             " Proceeding anyway. Please make sure node"
5622
                             " %s is down. Error details: %s",
5623
                             instance.name, source_node, source_node, msg)
5624
      else:
5625
        raise errors.OpExecError("Could not shutdown instance %s on"
5626
                                 " node %s: %s" %
5627
                                 (instance.name, source_node, msg))
5628

    
5629
    feedback_fn("* deactivating the instance's disks on source node")
5630
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5631
      raise errors.OpExecError("Can't shut down the instance's disks.")
5632

    
5633
    instance.primary_node = target_node
5634
    # distribute new instance config to the other nodes
5635
    self.cfg.Update(instance, feedback_fn)
5636

    
5637
    # Only start the instance if it's marked as up
5638
    if instance.admin_up:
5639
      feedback_fn("* activating the instance's disks on target node")
5640
      logging.info("Starting instance %s on node %s",
5641
                   instance.name, target_node)
5642

    
5643
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5644
                                           ignore_secondaries=True)
5645
      if not disks_ok:
5646
        _ShutdownInstanceDisks(self, instance)
5647
        raise errors.OpExecError("Can't activate the instance's disks")
5648

    
5649
      feedback_fn("* starting the instance on the target node")
5650
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5651
      msg = result.fail_msg
5652
      if msg:
5653
        _ShutdownInstanceDisks(self, instance)
5654
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5655
                                 (instance.name, target_node, msg))
5656

    
5657

    
5658
class LUMigrateInstance(LogicalUnit):
5659
  """Migrate an instance.
5660

5661
  This is migration without shutting down, compared to the failover,
5662
  which is done with shutdown.
5663

5664
  """
5665
  HPATH = "instance-migrate"
5666
  HTYPE = constants.HTYPE_INSTANCE
5667
  REQ_BGL = False
5668

    
5669
  def ExpandNames(self):
5670
    self._ExpandAndLockInstance()
5671

    
5672
    self.needed_locks[locking.LEVEL_NODE] = []
5673
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5674

    
5675
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5676
                                       self.op.cleanup)
5677
    self.tasklets = [self._migrater]
5678

    
5679
  def DeclareLocks(self, level):
5680
    if level == locking.LEVEL_NODE:
5681
      self._LockInstancesNodes()
5682

    
5683
  def BuildHooksEnv(self):
5684
    """Build hooks env.
5685

5686
    This runs on master, primary and secondary nodes of the instance.
5687

5688
    """
5689
    instance = self._migrater.instance
5690
    source_node = instance.primary_node
5691
    target_node = instance.secondary_nodes[0]
5692
    env = _BuildInstanceHookEnvByObject(self, instance)
5693
    env["MIGRATE_LIVE"] = self._migrater.live
5694
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5695
    env.update({
5696
        "OLD_PRIMARY": source_node,
5697
        "OLD_SECONDARY": target_node,
5698
        "NEW_PRIMARY": target_node,
5699
        "NEW_SECONDARY": source_node,
5700
        })
5701
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5702
    nl_post = list(nl)
5703
    nl_post.append(source_node)
5704
    return env, nl, nl_post
5705

    
5706

    
5707
class LUMoveInstance(LogicalUnit):
5708
  """Move an instance by data-copying.
5709

5710
  """
5711
  HPATH = "instance-move"
5712
  HTYPE = constants.HTYPE_INSTANCE
5713
  REQ_BGL = False
5714

    
5715
  def ExpandNames(self):
5716
    self._ExpandAndLockInstance()
5717
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5718
    self.op.target_node = target_node
5719
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5720
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5721

    
5722
  def DeclareLocks(self, level):
5723
    if level == locking.LEVEL_NODE:
5724
      self._LockInstancesNodes(primary_only=True)
5725

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

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

5731
    """
5732
    env = {
5733
      "TARGET_NODE": self.op.target_node,
5734
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5735
      }
5736
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5737
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5738
                                       self.op.target_node]
5739
    return env, nl, nl
5740

    
5741
  def CheckPrereq(self):
5742
    """Check prerequisites.
5743

5744
    This checks that the instance is in the cluster.
5745

5746
    """
5747
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5748
    assert self.instance is not None, \
5749
      "Cannot retrieve locked instance %s" % self.op.instance_name
5750

    
5751
    node = self.cfg.GetNodeInfo(self.op.target_node)
5752
    assert node is not None, \
5753
      "Cannot retrieve locked node %s" % self.op.target_node
5754

    
5755
    self.target_node = target_node = node.name
5756

    
5757
    if target_node == instance.primary_node:
5758
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5759
                                 (instance.name, target_node),
5760
                                 errors.ECODE_STATE)
5761

    
5762
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5763

    
5764
    for idx, dsk in enumerate(instance.disks):
5765
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5766
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5767
                                   " cannot copy" % idx, errors.ECODE_STATE)
5768

    
5769
    _CheckNodeOnline(self, target_node)
5770
    _CheckNodeNotDrained(self, target_node)
5771
    _CheckNodeVmCapable(self, target_node)
5772

    
5773
    if instance.admin_up:
5774
      # check memory requirements on the secondary node
5775
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5776
                           instance.name, bep[constants.BE_MEMORY],
5777
                           instance.hypervisor)
5778
    else:
5779
      self.LogInfo("Not checking memory on the secondary node as"
5780
                   " instance will not be started")
5781

    
5782
    # check bridge existance
5783
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5784

    
5785
  def Exec(self, feedback_fn):
5786
    """Move an instance.
5787

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

5791
    """
5792
    instance = self.instance
5793

    
5794
    source_node = instance.primary_node
5795
    target_node = self.target_node
5796

    
5797
    self.LogInfo("Shutting down instance %s on source node %s",
5798
                 instance.name, source_node)
5799

    
5800
    result = self.rpc.call_instance_shutdown(source_node, instance,
5801
                                             self.op.shutdown_timeout)
5802
    msg = result.fail_msg
5803
    if msg:
5804
      if self.op.ignore_consistency:
5805
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5806
                             " Proceeding anyway. Please make sure node"
5807
                             " %s is down. Error details: %s",
5808
                             instance.name, source_node, source_node, msg)
5809
      else:
5810
        raise errors.OpExecError("Could not shutdown instance %s on"
5811
                                 " node %s: %s" %
5812
                                 (instance.name, source_node, msg))
5813

    
5814
    # create the target disks
5815
    try:
5816
      _CreateDisks(self, instance, target_node=target_node)
5817
    except errors.OpExecError:
5818
      self.LogWarning("Device creation failed, reverting...")
5819
      try:
5820
        _RemoveDisks(self, instance, target_node=target_node)
5821
      finally:
5822
        self.cfg.ReleaseDRBDMinors(instance.name)
5823
        raise
5824

    
5825
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5826

    
5827
    errs = []
5828
    # activate, get path, copy the data over
5829
    for idx, disk in enumerate(instance.disks):
5830
      self.LogInfo("Copying data for disk %d", idx)
5831
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5832
                                               instance.name, True)
5833
      if result.fail_msg:
5834
        self.LogWarning("Can't assemble newly created disk %d: %s",
5835
                        idx, result.fail_msg)
5836
        errs.append(result.fail_msg)
5837
        break
5838
      dev_path = result.payload
5839
      result = self.rpc.call_blockdev_export(source_node, disk,
5840
                                             target_node, dev_path,
5841
                                             cluster_name)
5842
      if result.fail_msg:
5843
        self.LogWarning("Can't copy data over for disk %d: %s",
5844
                        idx, result.fail_msg)
5845
        errs.append(result.fail_msg)
5846
        break
5847

    
5848
    if errs:
5849
      self.LogWarning("Some disks failed to copy, aborting")
5850
      try:
5851
        _RemoveDisks(self, instance, target_node=target_node)
5852
      finally:
5853
        self.cfg.ReleaseDRBDMinors(instance.name)
5854
        raise errors.OpExecError("Errors during disk copy: %s" %
5855
                                 (",".join(errs),))
5856

    
5857
    instance.primary_node = target_node
5858
    self.cfg.Update(instance, feedback_fn)
5859

    
5860
    self.LogInfo("Removing the disks on the original node")
5861
    _RemoveDisks(self, instance, target_node=source_node)
5862

    
5863
    # Only start the instance if it's marked as up
5864
    if instance.admin_up:
5865
      self.LogInfo("Starting instance %s on node %s",
5866
                   instance.name, target_node)
5867

    
5868
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5869
                                           ignore_secondaries=True)
5870
      if not disks_ok:
5871
        _ShutdownInstanceDisks(self, instance)
5872
        raise errors.OpExecError("Can't activate the instance's disks")
5873

    
5874
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5875
      msg = result.fail_msg
5876
      if msg:
5877
        _ShutdownInstanceDisks(self, instance)
5878
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5879
                                 (instance.name, target_node, msg))
5880

    
5881

    
5882
class LUMigrateNode(LogicalUnit):
5883
  """Migrate all instances from a node.
5884

5885
  """
5886
  HPATH = "node-migrate"
5887
  HTYPE = constants.HTYPE_NODE
5888
  REQ_BGL = False
5889

    
5890
  def ExpandNames(self):
5891
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5892

    
5893
    self.needed_locks = {
5894
      locking.LEVEL_NODE: [self.op.node_name],
5895
      }
5896

    
5897
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5898

    
5899
    # Create tasklets for migrating instances for all instances on this node
5900
    names = []
5901
    tasklets = []
5902

    
5903
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5904
      logging.debug("Migrating instance %s", inst.name)
5905
      names.append(inst.name)
5906

    
5907
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5908

    
5909
    self.tasklets = tasklets
5910

    
5911
    # Declare instance locks
5912
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5913

    
5914
  def DeclareLocks(self, level):
5915
    if level == locking.LEVEL_NODE:
5916
      self._LockInstancesNodes()
5917

    
5918
  def BuildHooksEnv(self):
5919
    """Build hooks env.
5920

5921
    This runs on the master, the primary and all the secondaries.
5922

5923
    """
5924
    env = {
5925
      "NODE_NAME": self.op.node_name,
5926
      }
5927

    
5928
    nl = [self.cfg.GetMasterNode()]
5929

    
5930
    return (env, nl, nl)
5931

    
5932

    
5933
class TLMigrateInstance(Tasklet):
5934
  """Tasklet class for instance migration.
5935

5936
  @type live: boolean
5937
  @ivar live: whether the migration will be done live or non-live;
5938
      this variable is initalized only after CheckPrereq has run
5939

5940
  """
5941
  def __init__(self, lu, instance_name, cleanup):
5942
    """Initializes this class.
5943

5944
    """
5945
    Tasklet.__init__(self, lu)
5946

    
5947
    # Parameters
5948
    self.instance_name = instance_name
5949
    self.cleanup = cleanup
5950
    self.live = False # will be overridden later
5951

    
5952
  def CheckPrereq(self):
5953
    """Check prerequisites.
5954

5955
    This checks that the instance is in the cluster.
5956

5957
    """
5958
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5959
    instance = self.cfg.GetInstanceInfo(instance_name)
5960
    assert instance is not None
5961

    
5962
    if instance.disk_template != constants.DT_DRBD8:
5963
      raise errors.OpPrereqError("Instance's disk layout is not"
5964
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5965

    
5966
    secondary_nodes = instance.secondary_nodes
5967
    if not secondary_nodes:
5968
      raise errors.ConfigurationError("No secondary node but using"
5969
                                      " drbd8 disk template")
5970

    
5971
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5972

    
5973
    target_node = secondary_nodes[0]
5974
    # check memory requirements on the secondary node
5975
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5976
                         instance.name, i_be[constants.BE_MEMORY],
5977
                         instance.hypervisor)
5978

    
5979
    # check bridge existance
5980
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5981

    
5982
    if not self.cleanup:
5983
      _CheckNodeNotDrained(self.lu, target_node)
5984
      result = self.rpc.call_instance_migratable(instance.primary_node,
5985
                                                 instance)
5986
      result.Raise("Can't migrate, please use failover",
5987
                   prereq=True, ecode=errors.ECODE_STATE)
5988

    
5989
    self.instance = instance
5990

    
5991
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5992
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5993
                                 " parameters are accepted",
5994
                                 errors.ECODE_INVAL)
5995
    if self.lu.op.live is not None:
5996
      if self.lu.op.live:
5997
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5998
      else:
5999
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6000
      # reset the 'live' parameter to None so that repeated
6001
      # invocations of CheckPrereq do not raise an exception
6002
      self.lu.op.live = None
6003
    elif self.lu.op.mode is None:
6004
      # read the default value from the hypervisor
6005
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6006
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6007

    
6008
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6009

    
6010
  def _WaitUntilSync(self):
6011
    """Poll with custom rpc for disk sync.
6012

6013
    This uses our own step-based rpc call.
6014

6015
    """
6016
    self.feedback_fn("* wait until resync is done")
6017
    all_done = False
6018
    while not all_done:
6019
      all_done = True
6020
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6021
                                            self.nodes_ip,
6022
                                            self.instance.disks)
6023
      min_percent = 100
6024
      for node, nres in result.items():
6025
        nres.Raise("Cannot resync disks on node %s" % node)
6026
        node_done, node_percent = nres.payload
6027
        all_done = all_done and node_done
6028
        if node_percent is not None:
6029
          min_percent = min(min_percent, node_percent)
6030
      if not all_done:
6031
        if min_percent < 100:
6032
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6033
        time.sleep(2)
6034

    
6035
  def _EnsureSecondary(self, node):
6036
    """Demote a node to secondary.
6037

6038
    """
6039
    self.feedback_fn("* switching node %s to secondary mode" % node)
6040

    
6041
    for dev in self.instance.disks:
6042
      self.cfg.SetDiskID(dev, node)
6043

    
6044
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6045
                                          self.instance.disks)
6046
    result.Raise("Cannot change disk to secondary on node %s" % node)
6047

    
6048
  def _GoStandalone(self):
6049
    """Disconnect from the network.
6050

6051
    """
6052
    self.feedback_fn("* changing into standalone mode")
6053
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6054
                                               self.instance.disks)
6055
    for node, nres in result.items():
6056
      nres.Raise("Cannot disconnect disks node %s" % node)
6057

    
6058
  def _GoReconnect(self, multimaster):
6059
    """Reconnect to the network.
6060

6061
    """
6062
    if multimaster:
6063
      msg = "dual-master"
6064
    else:
6065
      msg = "single-master"
6066
    self.feedback_fn("* changing disks into %s mode" % msg)
6067
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6068
                                           self.instance.disks,
6069
                                           self.instance.name, multimaster)
6070
    for node, nres in result.items():
6071
      nres.Raise("Cannot change disks config on node %s" % node)
6072

    
6073
  def _ExecCleanup(self):
6074
    """Try to cleanup after a failed migration.
6075

6076
    The cleanup is done by:
6077
      - check that the instance is running only on one node
6078
        (and update the config if needed)
6079
      - change disks on its secondary node to secondary
6080
      - wait until disks are fully synchronized
6081
      - disconnect from the network
6082
      - change disks into single-master mode
6083
      - wait again until disks are fully synchronized
6084

6085
    """
6086
    instance = self.instance
6087
    target_node = self.target_node
6088
    source_node = self.source_node
6089

    
6090
    # check running on only one node
6091
    self.feedback_fn("* checking where the instance actually runs"
6092
                     " (if this hangs, the hypervisor might be in"
6093
                     " a bad state)")
6094
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6095
    for node, result in ins_l.items():
6096
      result.Raise("Can't contact node %s" % node)
6097

    
6098
    runningon_source = instance.name in ins_l[source_node].payload
6099
    runningon_target = instance.name in ins_l[target_node].payload
6100

    
6101
    if runningon_source and runningon_target:
6102
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6103
                               " or the hypervisor is confused. You will have"
6104
                               " to ensure manually that it runs only on one"
6105
                               " and restart this operation.")
6106

    
6107
    if not (runningon_source or runningon_target):
6108
      raise errors.OpExecError("Instance does not seem to be running at all."
6109
                               " In this case, it's safer to repair by"
6110
                               " running 'gnt-instance stop' to ensure disk"
6111
                               " shutdown, and then restarting it.")
6112

    
6113
    if runningon_target:
6114
      # the migration has actually succeeded, we need to update the config
6115
      self.feedback_fn("* instance running on secondary node (%s),"
6116
                       " updating config" % target_node)
6117
      instance.primary_node = target_node
6118
      self.cfg.Update(instance, self.feedback_fn)
6119
      demoted_node = source_node
6120
    else:
6121
      self.feedback_fn("* instance confirmed to be running on its"
6122
                       " primary node (%s)" % source_node)
6123
      demoted_node = target_node
6124

    
6125
    self._EnsureSecondary(demoted_node)
6126
    try:
6127
      self._WaitUntilSync()
6128
    except errors.OpExecError:
6129
      # we ignore here errors, since if the device is standalone, it
6130
      # won't be able to sync
6131
      pass
6132
    self._GoStandalone()
6133
    self._GoReconnect(False)
6134
    self._WaitUntilSync()
6135

    
6136
    self.feedback_fn("* done")
6137

    
6138
  def _RevertDiskStatus(self):
6139
    """Try to revert the disk status after a failed migration.
6140

6141
    """
6142
    target_node = self.target_node
6143
    try:
6144
      self._EnsureSecondary(target_node)
6145
      self._GoStandalone()
6146
      self._GoReconnect(False)
6147
      self._WaitUntilSync()
6148
    except errors.OpExecError, err:
6149
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6150
                         " drives: error '%s'\n"
6151
                         "Please look and recover the instance status" %
6152
                         str(err))
6153

    
6154
  def _AbortMigration(self):
6155
    """Call the hypervisor code to abort a started migration.
6156

6157
    """
6158
    instance = self.instance
6159
    target_node = self.target_node
6160
    migration_info = self.migration_info
6161

    
6162
    abort_result = self.rpc.call_finalize_migration(target_node,
6163
                                                    instance,
6164
                                                    migration_info,
6165
                                                    False)
6166
    abort_msg = abort_result.fail_msg
6167
    if abort_msg:
6168
      logging.error("Aborting migration failed on target node %s: %s",
6169
                    target_node, abort_msg)
6170
      # Don't raise an exception here, as we stil have to try to revert the
6171
      # disk status, even if this step failed.
6172

    
6173
  def _ExecMigration(self):
6174
    """Migrate an instance.
6175

6176
    The migrate is done by:
6177
      - change the disks into dual-master mode
6178
      - wait until disks are fully synchronized again
6179
      - migrate the instance
6180
      - change disks on the new secondary node (the old primary) to secondary
6181
      - wait until disks are fully synchronized
6182
      - change disks into single-master mode
6183

6184
    """
6185
    instance = self.instance
6186
    target_node = self.target_node
6187
    source_node = self.source_node
6188

    
6189
    self.feedback_fn("* checking disk consistency between source and target")
6190
    for dev in instance.disks:
6191
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6192
        raise errors.OpExecError("Disk %s is degraded or not fully"
6193
                                 " synchronized on target node,"
6194
                                 " aborting migrate." % dev.iv_name)
6195

    
6196
    # First get the migration information from the remote node
6197
    result = self.rpc.call_migration_info(source_node, instance)
6198
    msg = result.fail_msg
6199
    if msg:
6200
      log_err = ("Failed fetching source migration information from %s: %s" %
6201
                 (source_node, msg))
6202
      logging.error(log_err)
6203
      raise errors.OpExecError(log_err)
6204

    
6205
    self.migration_info = migration_info = result.payload
6206

    
6207
    # Then switch the disks to master/master mode
6208
    self._EnsureSecondary(target_node)
6209
    self._GoStandalone()
6210
    self._GoReconnect(True)
6211
    self._WaitUntilSync()
6212

    
6213
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6214
    result = self.rpc.call_accept_instance(target_node,
6215
                                           instance,
6216
                                           migration_info,
6217
                                           self.nodes_ip[target_node])
6218

    
6219
    msg = result.fail_msg
6220
    if msg:
6221
      logging.error("Instance pre-migration failed, trying to revert"
6222
                    " disk status: %s", msg)
6223
      self.feedback_fn("Pre-migration failed, aborting")
6224
      self._AbortMigration()
6225
      self._RevertDiskStatus()
6226
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6227
                               (instance.name, msg))
6228

    
6229
    self.feedback_fn("* migrating instance to %s" % target_node)
6230
    time.sleep(10)
6231
    result = self.rpc.call_instance_migrate(source_node, instance,
6232
                                            self.nodes_ip[target_node],
6233
                                            self.live)
6234
    msg = result.fail_msg
6235
    if msg:
6236
      logging.error("Instance migration failed, trying to revert"
6237
                    " disk status: %s", msg)
6238
      self.feedback_fn("Migration failed, aborting")
6239
      self._AbortMigration()
6240
      self._RevertDiskStatus()
6241
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6242
                               (instance.name, msg))
6243
    time.sleep(10)
6244

    
6245
    instance.primary_node = target_node
6246
    # distribute new instance config to the other nodes
6247
    self.cfg.Update(instance, self.feedback_fn)
6248

    
6249
    result = self.rpc.call_finalize_migration(target_node,
6250
                                              instance,
6251
                                              migration_info,
6252
                                              True)
6253
    msg = result.fail_msg
6254
    if msg:
6255
      logging.error("Instance migration succeeded, but finalization failed:"
6256
                    " %s", msg)
6257
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6258
                               msg)
6259

    
6260
    self._EnsureSecondary(source_node)
6261
    self._WaitUntilSync()
6262
    self._GoStandalone()
6263
    self._GoReconnect(False)
6264
    self._WaitUntilSync()
6265

    
6266
    self.feedback_fn("* done")
6267

    
6268
  def Exec(self, feedback_fn):
6269
    """Perform the migration.
6270

6271
    """
6272
    feedback_fn("Migrating instance %s" % self.instance.name)
6273

    
6274
    self.feedback_fn = feedback_fn
6275

    
6276
    self.source_node = self.instance.primary_node
6277
    self.target_node = self.instance.secondary_nodes[0]
6278
    self.all_nodes = [self.source_node, self.target_node]
6279
    self.nodes_ip = {
6280
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6281
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6282
      }
6283

    
6284
    if self.cleanup:
6285
      return self._ExecCleanup()
6286
    else:
6287
      return self._ExecMigration()
6288

    
6289

    
6290
def _CreateBlockDev(lu, node, instance, device, force_create,
6291
                    info, force_open):
6292
  """Create a tree of block devices on a given node.
6293

6294
  If this device type has to be created on secondaries, create it and
6295
  all its children.
6296

6297
  If not, just recurse to children keeping the same 'force' value.
6298

6299
  @param lu: the lu on whose behalf we execute
6300
  @param node: the node on which to create the device
6301
  @type instance: L{objects.Instance}
6302
  @param instance: the instance which owns the device
6303
  @type device: L{objects.Disk}
6304
  @param device: the device to create
6305
  @type force_create: boolean
6306
  @param force_create: whether to force creation of this device; this
6307
      will be change to True whenever we find a device which has
6308
      CreateOnSecondary() attribute
6309
  @param info: the extra 'metadata' we should attach to the device
6310
      (this will be represented as a LVM tag)
6311
  @type force_open: boolean
6312
  @param force_open: this parameter will be passes to the
6313
      L{backend.BlockdevCreate} function where it specifies
6314
      whether we run on primary or not, and it affects both
6315
      the child assembly and the device own Open() execution
6316

6317
  """
6318
  if device.CreateOnSecondary():
6319
    force_create = True
6320

    
6321
  if device.children:
6322
    for child in device.children:
6323
      _CreateBlockDev(lu, node, instance, child, force_create,
6324
                      info, force_open)
6325

    
6326
  if not force_create:
6327
    return
6328

    
6329
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6330

    
6331

    
6332
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6333
  """Create a single block device on a given node.
6334

6335
  This will not recurse over children of the device, so they must be
6336
  created in advance.
6337

6338
  @param lu: the lu on whose behalf we execute
6339
  @param node: the node on which to create the device
6340
  @type instance: L{objects.Instance}
6341
  @param instance: the instance which owns the device
6342
  @type device: L{objects.Disk}
6343
  @param device: the device to create
6344
  @param info: the extra 'metadata' we should attach to the device
6345
      (this will be represented as a LVM tag)
6346
  @type force_open: boolean
6347
  @param force_open: this parameter will be passes to the
6348
      L{backend.BlockdevCreate} function where it specifies
6349
      whether we run on primary or not, and it affects both
6350
      the child assembly and the device own Open() execution
6351

6352
  """
6353
  lu.cfg.SetDiskID(device, node)
6354
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6355
                                       instance.name, force_open, info)
6356
  result.Raise("Can't create block device %s on"
6357
               " node %s for instance %s" % (device, node, instance.name))
6358
  if device.physical_id is None:
6359
    device.physical_id = result.payload
6360

    
6361

    
6362
def _GenerateUniqueNames(lu, exts):
6363
  """Generate a suitable LV name.
6364

6365
  This will generate a logical volume name for the given instance.
6366

6367
  """
6368
  results = []
6369
  for val in exts:
6370
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6371
    results.append("%s%s" % (new_id, val))
6372
  return results
6373

    
6374

    
6375
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6376
                         p_minor, s_minor):
6377
  """Generate a drbd8 device complete with its children.
6378

6379
  """
6380
  port = lu.cfg.AllocatePort()
6381
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6382
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6383
                          logical_id=(vgname, names[0]))
6384
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6385
                          logical_id=(vgname, names[1]))
6386
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6387
                          logical_id=(primary, secondary, port,
6388
                                      p_minor, s_minor,
6389
                                      shared_secret),
6390
                          children=[dev_data, dev_meta],
6391
                          iv_name=iv_name)
6392
  return drbd_dev
6393

    
6394

    
6395
def _GenerateDiskTemplate(lu, template_name,
6396
                          instance_name, primary_node,
6397
                          secondary_nodes, disk_info,
6398
                          file_storage_dir, file_driver,
6399
                          base_index, feedback_fn):
6400
  """Generate the entire disk layout for a given template type.
6401

6402
  """
6403
  #TODO: compute space requirements
6404

    
6405
  vgname = lu.cfg.GetVGName()
6406
  disk_count = len(disk_info)
6407
  disks = []
6408
  if template_name == constants.DT_DISKLESS:
6409
    pass
6410
  elif template_name == constants.DT_PLAIN:
6411
    if len(secondary_nodes) != 0:
6412
      raise errors.ProgrammerError("Wrong template configuration")
6413

    
6414
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6415
                                      for i in range(disk_count)])
6416
    for idx, disk in enumerate(disk_info):
6417
      disk_index = idx + base_index
6418
      vg = disk.get("vg", vgname)
6419
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6420
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6421
                              logical_id=(vg, names[idx]),
6422
                              iv_name="disk/%d" % disk_index,
6423
                              mode=disk["mode"])
6424
      disks.append(disk_dev)
6425
  elif template_name == constants.DT_DRBD8:
6426
    if len(secondary_nodes) != 1:
6427
      raise errors.ProgrammerError("Wrong template configuration")
6428
    remote_node = secondary_nodes[0]
6429
    minors = lu.cfg.AllocateDRBDMinor(
6430
      [primary_node, remote_node] * len(disk_info), instance_name)
6431

    
6432
    names = []
6433
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6434
                                               for i in range(disk_count)]):
6435
      names.append(lv_prefix + "_data")
6436
      names.append(lv_prefix + "_meta")
6437
    for idx, disk in enumerate(disk_info):
6438
      disk_index = idx + base_index
6439
      vg = disk.get("vg", vgname)
6440
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6441
                                      disk["size"], vg, names[idx*2:idx*2+2],
6442
                                      "disk/%d" % disk_index,
6443
                                      minors[idx*2], minors[idx*2+1])
6444
      disk_dev.mode = disk["mode"]
6445
      disks.append(disk_dev)
6446
  elif template_name == constants.DT_FILE:
6447
    if len(secondary_nodes) != 0:
6448
      raise errors.ProgrammerError("Wrong template configuration")
6449

    
6450
    opcodes.RequireFileStorage()
6451

    
6452
    for idx, disk in enumerate(disk_info):
6453
      disk_index = idx + base_index
6454
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6455
                              iv_name="disk/%d" % disk_index,
6456
                              logical_id=(file_driver,
6457
                                          "%s/disk%d" % (file_storage_dir,
6458
                                                         disk_index)),
6459
                              mode=disk["mode"])
6460
      disks.append(disk_dev)
6461
  else:
6462
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6463
  return disks
6464

    
6465

    
6466
def _GetInstanceInfoText(instance):
6467
  """Compute that text that should be added to the disk's metadata.
6468

6469
  """
6470
  return "originstname+%s" % instance.name
6471

    
6472

    
6473
def _CalcEta(time_taken, written, total_size):
6474
  """Calculates the ETA based on size written and total size.
6475

6476
  @param time_taken: The time taken so far
6477
  @param written: amount written so far
6478
  @param total_size: The total size of data to be written
6479
  @return: The remaining time in seconds
6480

6481
  """
6482
  avg_time = time_taken / float(written)
6483
  return (total_size - written) * avg_time
6484

    
6485

    
6486
def _WipeDisks(lu, instance):
6487
  """Wipes instance disks.
6488

6489
  @type lu: L{LogicalUnit}
6490
  @param lu: the logical unit on whose behalf we execute
6491
  @type instance: L{objects.Instance}
6492
  @param instance: the instance whose disks we should create
6493
  @return: the success of the wipe
6494

6495
  """
6496
  node = instance.primary_node
6497
  for idx, device in enumerate(instance.disks):
6498
    lu.LogInfo("* Wiping disk %d", idx)
6499
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6500

    
6501
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6502
    # MAX_WIPE_CHUNK at max
6503
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6504
                          constants.MIN_WIPE_CHUNK_PERCENT)
6505

    
6506
    offset = 0
6507
    size = device.size
6508
    last_output = 0
6509
    start_time = time.time()
6510

    
6511
    while offset < size:
6512
      wipe_size = min(wipe_chunk_size, size - offset)
6513
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6514
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6515
                   (idx, offset, wipe_size))
6516
      now = time.time()
6517
      offset += wipe_size
6518
      if now - last_output >= 60:
6519
        eta = _CalcEta(now - start_time, offset, size)
6520
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6521
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6522
        last_output = now
6523

    
6524

    
6525
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6526
  """Create all disks for an instance.
6527

6528
  This abstracts away some work from AddInstance.
6529

6530
  @type lu: L{LogicalUnit}
6531
  @param lu: the logical unit on whose behalf we execute
6532
  @type instance: L{objects.Instance}
6533
  @param instance: the instance whose disks we should create
6534
  @type to_skip: list
6535
  @param to_skip: list of indices to skip
6536
  @type target_node: string
6537
  @param target_node: if passed, overrides the target node for creation
6538
  @rtype: boolean
6539
  @return: the success of the creation
6540

6541
  """
6542
  info = _GetInstanceInfoText(instance)
6543
  if target_node is None:
6544
    pnode = instance.primary_node
6545
    all_nodes = instance.all_nodes
6546
  else:
6547
    pnode = target_node
6548
    all_nodes = [pnode]
6549

    
6550
  if instance.disk_template == constants.DT_FILE:
6551
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6552
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6553

    
6554
    result.Raise("Failed to create directory '%s' on"
6555
                 " node %s" % (file_storage_dir, pnode))
6556

    
6557
  # Note: this needs to be kept in sync with adding of disks in
6558
  # LUSetInstanceParams
6559
  for idx, device in enumerate(instance.disks):
6560
    if to_skip and idx in to_skip:
6561
      continue
6562
    logging.info("Creating volume %s for instance %s",
6563
                 device.iv_name, instance.name)
6564
    #HARDCODE
6565
    for node in all_nodes:
6566
      f_create = node == pnode
6567
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6568

    
6569

    
6570
def _RemoveDisks(lu, instance, target_node=None):
6571
  """Remove all disks for an instance.
6572

6573
  This abstracts away some work from `AddInstance()` and
6574
  `RemoveInstance()`. Note that in case some of the devices couldn't
6575
  be removed, the removal will continue with the other ones (compare
6576
  with `_CreateDisks()`).
6577

6578
  @type lu: L{LogicalUnit}
6579
  @param lu: the logical unit on whose behalf we execute
6580
  @type instance: L{objects.Instance}
6581
  @param instance: the instance whose disks we should remove
6582
  @type target_node: string
6583
  @param target_node: used to override the node on which to remove the disks
6584
  @rtype: boolean
6585
  @return: the success of the removal
6586

6587
  """
6588
  logging.info("Removing block devices for instance %s", instance.name)
6589

    
6590
  all_result = True
6591
  for device in instance.disks:
6592
    if target_node:
6593
      edata = [(target_node, device)]
6594
    else:
6595
      edata = device.ComputeNodeTree(instance.primary_node)
6596
    for node, disk in edata:
6597
      lu.cfg.SetDiskID(disk, node)
6598
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6599
      if msg:
6600
        lu.LogWarning("Could not remove block device %s on node %s,"
6601
                      " continuing anyway: %s", device.iv_name, node, msg)
6602
        all_result = False
6603

    
6604
  if instance.disk_template == constants.DT_FILE:
6605
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6606
    if target_node:
6607
      tgt = target_node
6608
    else:
6609
      tgt = instance.primary_node
6610
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6611
    if result.fail_msg:
6612
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6613
                    file_storage_dir, instance.primary_node, result.fail_msg)
6614
      all_result = False
6615

    
6616
  return all_result
6617

    
6618

    
6619
def _ComputeDiskSizePerVG(disk_template, disks):
6620
  """Compute disk size requirements in the volume group
6621

6622
  """
6623
  def _compute(disks, payload):
6624
    """Universal algorithm
6625

6626
    """
6627
    vgs = {}
6628
    for disk in disks:
6629
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
6630

    
6631
    return vgs
6632

    
6633
  # Required free disk space as a function of disk and swap space
6634
  req_size_dict = {
6635
    constants.DT_DISKLESS: None,
6636
    constants.DT_PLAIN: _compute(disks, 0),
6637
    # 128 MB are added for drbd metadata for each disk
6638
    constants.DT_DRBD8: _compute(disks, 128),
6639
    constants.DT_FILE: None,
6640
  }
6641

    
6642
  if disk_template not in req_size_dict:
6643
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6644
                                 " is unknown" %  disk_template)
6645

    
6646
  return req_size_dict[disk_template]
6647

    
6648

    
6649
def _ComputeDiskSize(disk_template, disks):
6650
  """Compute disk size requirements in the volume group
6651

6652
  """
6653
  # Required free disk space as a function of disk and swap space
6654
  req_size_dict = {
6655
    constants.DT_DISKLESS: None,
6656
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6657
    # 128 MB are added for drbd metadata for each disk
6658
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6659
    constants.DT_FILE: None,
6660
  }
6661

    
6662
  if disk_template not in req_size_dict:
6663
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6664
                                 " is unknown" %  disk_template)
6665

    
6666
  return req_size_dict[disk_template]
6667

    
6668

    
6669
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6670
  """Hypervisor parameter validation.
6671

6672
  This function abstract the hypervisor parameter validation to be
6673
  used in both instance create and instance modify.
6674

6675
  @type lu: L{LogicalUnit}
6676
  @param lu: the logical unit for which we check
6677
  @type nodenames: list
6678
  @param nodenames: the list of nodes on which we should check
6679
  @type hvname: string
6680
  @param hvname: the name of the hypervisor we should use
6681
  @type hvparams: dict
6682
  @param hvparams: the parameters which we need to check
6683
  @raise errors.OpPrereqError: if the parameters are not valid
6684

6685
  """
6686
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6687
                                                  hvname,
6688
                                                  hvparams)
6689
  for node in nodenames:
6690
    info = hvinfo[node]
6691
    if info.offline:
6692
      continue
6693
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6694

    
6695

    
6696
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6697
  """OS parameters validation.
6698

6699
  @type lu: L{LogicalUnit}
6700
  @param lu: the logical unit for which we check
6701
  @type required: boolean
6702
  @param required: whether the validation should fail if the OS is not
6703
      found
6704
  @type nodenames: list
6705
  @param nodenames: the list of nodes on which we should check
6706
  @type osname: string
6707
  @param osname: the name of the hypervisor we should use
6708
  @type osparams: dict
6709
  @param osparams: the parameters which we need to check
6710
  @raise errors.OpPrereqError: if the parameters are not valid
6711

6712
  """
6713
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6714
                                   [constants.OS_VALIDATE_PARAMETERS],
6715
                                   osparams)
6716
  for node, nres in result.items():
6717
    # we don't check for offline cases since this should be run only
6718
    # against the master node and/or an instance's nodes
6719
    nres.Raise("OS Parameters validation failed on node %s" % node)
6720
    if not nres.payload:
6721
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6722
                 osname, node)
6723

    
6724

    
6725
class LUCreateInstance(LogicalUnit):
6726
  """Create an instance.
6727

6728
  """
6729
  HPATH = "instance-add"
6730
  HTYPE = constants.HTYPE_INSTANCE
6731
  REQ_BGL = False
6732

    
6733
  def CheckArguments(self):
6734
    """Check arguments.
6735

6736
    """
6737
    # do not require name_check to ease forward/backward compatibility
6738
    # for tools
6739
    if self.op.no_install and self.op.start:
6740
      self.LogInfo("No-installation mode selected, disabling startup")
6741
      self.op.start = False
6742
    # validate/normalize the instance name
6743
    self.op.instance_name = \
6744
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6745

    
6746
    if self.op.ip_check and not self.op.name_check:
6747
      # TODO: make the ip check more flexible and not depend on the name check
6748
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6749
                                 errors.ECODE_INVAL)
6750

    
6751
    # check nics' parameter names
6752
    for nic in self.op.nics:
6753
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6754

    
6755
    # check disks. parameter names and consistent adopt/no-adopt strategy
6756
    has_adopt = has_no_adopt = False
6757
    for disk in self.op.disks:
6758
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6759
      if "adopt" in disk:
6760
        has_adopt = True
6761
      else:
6762
        has_no_adopt = True
6763
    if has_adopt and has_no_adopt:
6764
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6765
                                 errors.ECODE_INVAL)
6766
    if has_adopt:
6767
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6768
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6769
                                   " '%s' disk template" %
6770
                                   self.op.disk_template,
6771
                                   errors.ECODE_INVAL)
6772
      if self.op.iallocator is not None:
6773
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6774
                                   " iallocator script", errors.ECODE_INVAL)
6775
      if self.op.mode == constants.INSTANCE_IMPORT:
6776
        raise errors.OpPrereqError("Disk adoption not allowed for"
6777
                                   " instance import", errors.ECODE_INVAL)
6778

    
6779
    self.adopt_disks = has_adopt
6780

    
6781
    # instance name verification
6782
    if self.op.name_check:
6783
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6784
      self.op.instance_name = self.hostname1.name
6785
      # used in CheckPrereq for ip ping check
6786
      self.check_ip = self.hostname1.ip
6787
    else:
6788
      self.check_ip = None
6789

    
6790
    # file storage checks
6791
    if (self.op.file_driver and
6792
        not self.op.file_driver in constants.FILE_DRIVER):
6793
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6794
                                 self.op.file_driver, errors.ECODE_INVAL)
6795

    
6796
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6797
      raise errors.OpPrereqError("File storage directory path not absolute",
6798
                                 errors.ECODE_INVAL)
6799

    
6800
    ### Node/iallocator related checks
6801
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6802

    
6803
    if self.op.pnode is not None:
6804
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6805
        if self.op.snode is None:
6806
          raise errors.OpPrereqError("The networked disk templates need"
6807
                                     " a mirror node", errors.ECODE_INVAL)
6808
      elif self.op.snode:
6809
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6810
                        " template")
6811
        self.op.snode = None
6812

    
6813
    self._cds = _GetClusterDomainSecret()
6814

    
6815
    if self.op.mode == constants.INSTANCE_IMPORT:
6816
      # On import force_variant must be True, because if we forced it at
6817
      # initial install, our only chance when importing it back is that it
6818
      # works again!
6819
      self.op.force_variant = True
6820

    
6821
      if self.op.no_install:
6822
        self.LogInfo("No-installation mode has no effect during import")
6823

    
6824
    elif self.op.mode == constants.INSTANCE_CREATE:
6825
      if self.op.os_type is None:
6826
        raise errors.OpPrereqError("No guest OS specified",
6827
                                   errors.ECODE_INVAL)
6828
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6829
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6830
                                   " installation" % self.op.os_type,
6831
                                   errors.ECODE_STATE)
6832
      if self.op.disk_template is None:
6833
        raise errors.OpPrereqError("No disk template specified",
6834
                                   errors.ECODE_INVAL)
6835

    
6836
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6837
      # Check handshake to ensure both clusters have the same domain secret
6838
      src_handshake = self.op.source_handshake
6839
      if not src_handshake:
6840
        raise errors.OpPrereqError("Missing source handshake",
6841
                                   errors.ECODE_INVAL)
6842

    
6843
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6844
                                                           src_handshake)
6845
      if errmsg:
6846
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6847
                                   errors.ECODE_INVAL)
6848

    
6849
      # Load and check source CA
6850
      self.source_x509_ca_pem = self.op.source_x509_ca
6851
      if not self.source_x509_ca_pem:
6852
        raise errors.OpPrereqError("Missing source X509 CA",
6853
                                   errors.ECODE_INVAL)
6854

    
6855
      try:
6856
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6857
                                                    self._cds)
6858
      except OpenSSL.crypto.Error, err:
6859
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6860
                                   (err, ), errors.ECODE_INVAL)
6861

    
6862
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6863
      if errcode is not None:
6864
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6865
                                   errors.ECODE_INVAL)
6866

    
6867
      self.source_x509_ca = cert
6868

    
6869
      src_instance_name = self.op.source_instance_name
6870
      if not src_instance_name:
6871
        raise errors.OpPrereqError("Missing source instance name",
6872
                                   errors.ECODE_INVAL)
6873

    
6874
      self.source_instance_name = \
6875
          netutils.GetHostname(name=src_instance_name).name
6876

    
6877
    else:
6878
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6879
                                 self.op.mode, errors.ECODE_INVAL)
6880

    
6881
  def ExpandNames(self):
6882
    """ExpandNames for CreateInstance.
6883

6884
    Figure out the right locks for instance creation.
6885

6886
    """
6887
    self.needed_locks = {}
6888

    
6889
    instance_name = self.op.instance_name
6890
    # this is just a preventive check, but someone might still add this
6891
    # instance in the meantime, and creation will fail at lock-add time
6892
    if instance_name in self.cfg.GetInstanceList():
6893
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6894
                                 instance_name, errors.ECODE_EXISTS)
6895

    
6896
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6897

    
6898
    if self.op.iallocator:
6899
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6900
    else:
6901
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6902
      nodelist = [self.op.pnode]
6903
      if self.op.snode is not None:
6904
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6905
        nodelist.append(self.op.snode)
6906
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6907

    
6908
    # in case of import lock the source node too
6909
    if self.op.mode == constants.INSTANCE_IMPORT:
6910
      src_node = self.op.src_node
6911
      src_path = self.op.src_path
6912

    
6913
      if src_path is None:
6914
        self.op.src_path = src_path = self.op.instance_name
6915

    
6916
      if src_node is None:
6917
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6918
        self.op.src_node = None
6919
        if os.path.isabs(src_path):
6920
          raise errors.OpPrereqError("Importing an instance from an absolute"
6921
                                     " path requires a source node option.",
6922
                                     errors.ECODE_INVAL)
6923
      else:
6924
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6925
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6926
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6927
        if not os.path.isabs(src_path):
6928
          self.op.src_path = src_path = \
6929
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6930

    
6931
  def _RunAllocator(self):
6932
    """Run the allocator based on input opcode.
6933

6934
    """
6935
    nics = [n.ToDict() for n in self.nics]
6936
    ial = IAllocator(self.cfg, self.rpc,
6937
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6938
                     name=self.op.instance_name,
6939
                     disk_template=self.op.disk_template,
6940
                     tags=[],
6941
                     os=self.op.os_type,
6942
                     vcpus=self.be_full[constants.BE_VCPUS],
6943
                     mem_size=self.be_full[constants.BE_MEMORY],
6944
                     disks=self.disks,
6945
                     nics=nics,
6946
                     hypervisor=self.op.hypervisor,
6947
                     )
6948

    
6949
    ial.Run(self.op.iallocator)
6950

    
6951
    if not ial.success:
6952
      raise errors.OpPrereqError("Can't compute nodes using"
6953
                                 " iallocator '%s': %s" %
6954
                                 (self.op.iallocator, ial.info),
6955
                                 errors.ECODE_NORES)
6956
    if len(ial.result) != ial.required_nodes:
6957
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6958
                                 " of nodes (%s), required %s" %
6959
                                 (self.op.iallocator, len(ial.result),
6960
                                  ial.required_nodes), errors.ECODE_FAULT)
6961
    self.op.pnode = ial.result[0]
6962
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6963
                 self.op.instance_name, self.op.iallocator,
6964
                 utils.CommaJoin(ial.result))
6965
    if ial.required_nodes == 2:
6966
      self.op.snode = ial.result[1]
6967

    
6968
  def BuildHooksEnv(self):
6969
    """Build hooks env.
6970

6971
    This runs on master, primary and secondary nodes of the instance.
6972

6973
    """
6974
    env = {
6975
      "ADD_MODE": self.op.mode,
6976
      }
6977
    if self.op.mode == constants.INSTANCE_IMPORT:
6978
      env["SRC_NODE"] = self.op.src_node
6979
      env["SRC_PATH"] = self.op.src_path
6980
      env["SRC_IMAGES"] = self.src_images
6981

    
6982
    env.update(_BuildInstanceHookEnv(
6983
      name=self.op.instance_name,
6984
      primary_node=self.op.pnode,
6985
      secondary_nodes=self.secondaries,
6986
      status=self.op.start,
6987
      os_type=self.op.os_type,
6988
      memory=self.be_full[constants.BE_MEMORY],
6989
      vcpus=self.be_full[constants.BE_VCPUS],
6990
      nics=_NICListToTuple(self, self.nics),
6991
      disk_template=self.op.disk_template,
6992
      disks=[(d["size"], d["mode"]) for d in self.disks],
6993
      bep=self.be_full,
6994
      hvp=self.hv_full,
6995
      hypervisor_name=self.op.hypervisor,
6996
    ))
6997

    
6998
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6999
          self.secondaries)
7000
    return env, nl, nl
7001

    
7002
  def _ReadExportInfo(self):
7003
    """Reads the export information from disk.
7004

7005
    It will override the opcode source node and path with the actual
7006
    information, if these two were not specified before.
7007

7008
    @return: the export information
7009

7010
    """
7011
    assert self.op.mode == constants.INSTANCE_IMPORT
7012

    
7013
    src_node = self.op.src_node
7014
    src_path = self.op.src_path
7015

    
7016
    if src_node is None:
7017
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7018
      exp_list = self.rpc.call_export_list(locked_nodes)
7019
      found = False
7020
      for node in exp_list:
7021
        if exp_list[node].fail_msg:
7022
          continue
7023
        if src_path in exp_list[node].payload:
7024
          found = True
7025
          self.op.src_node = src_node = node
7026
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7027
                                                       src_path)
7028
          break
7029
      if not found:
7030
        raise errors.OpPrereqError("No export found for relative path %s" %
7031
                                    src_path, errors.ECODE_INVAL)
7032

    
7033
    _CheckNodeOnline(self, src_node)
7034
    result = self.rpc.call_export_info(src_node, src_path)
7035
    result.Raise("No export or invalid export found in dir %s" % src_path)
7036

    
7037
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7038
    if not export_info.has_section(constants.INISECT_EXP):
7039
      raise errors.ProgrammerError("Corrupted export config",
7040
                                   errors.ECODE_ENVIRON)
7041

    
7042
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7043
    if (int(ei_version) != constants.EXPORT_VERSION):
7044
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7045
                                 (ei_version, constants.EXPORT_VERSION),
7046
                                 errors.ECODE_ENVIRON)
7047
    return export_info
7048

    
7049
  def _ReadExportParams(self, einfo):
7050
    """Use export parameters as defaults.
7051

7052
    In case the opcode doesn't specify (as in override) some instance
7053
    parameters, then try to use them from the export information, if
7054
    that declares them.
7055

7056
    """
7057
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7058

    
7059
    if self.op.disk_template is None:
7060
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7061
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7062
                                          "disk_template")
7063
      else:
7064
        raise errors.OpPrereqError("No disk template specified and the export"
7065
                                   " is missing the disk_template information",
7066
                                   errors.ECODE_INVAL)
7067

    
7068
    if not self.op.disks:
7069
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7070
        disks = []
7071
        # TODO: import the disk iv_name too
7072
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7073
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7074
          disks.append({"size": disk_sz})
7075
        self.op.disks = disks
7076
      else:
7077
        raise errors.OpPrereqError("No disk info specified and the export"
7078
                                   " is missing the disk information",
7079
                                   errors.ECODE_INVAL)
7080

    
7081
    if (not self.op.nics and
7082
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7083
      nics = []
7084
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7085
        ndict = {}
7086
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7087
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7088
          ndict[name] = v
7089
        nics.append(ndict)
7090
      self.op.nics = nics
7091

    
7092
    if (self.op.hypervisor is None and
7093
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7094
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7095
    if einfo.has_section(constants.INISECT_HYP):
7096
      # use the export parameters but do not override the ones
7097
      # specified by the user
7098
      for name, value in einfo.items(constants.INISECT_HYP):
7099
        if name not in self.op.hvparams:
7100
          self.op.hvparams[name] = value
7101

    
7102
    if einfo.has_section(constants.INISECT_BEP):
7103
      # use the parameters, without overriding
7104
      for name, value in einfo.items(constants.INISECT_BEP):
7105
        if name not in self.op.beparams:
7106
          self.op.beparams[name] = value
7107
    else:
7108
      # try to read the parameters old style, from the main section
7109
      for name in constants.BES_PARAMETERS:
7110
        if (name not in self.op.beparams and
7111
            einfo.has_option(constants.INISECT_INS, name)):
7112
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7113

    
7114
    if einfo.has_section(constants.INISECT_OSP):
7115
      # use the parameters, without overriding
7116
      for name, value in einfo.items(constants.INISECT_OSP):
7117
        if name not in self.op.osparams:
7118
          self.op.osparams[name] = value
7119

    
7120
  def _RevertToDefaults(self, cluster):
7121
    """Revert the instance parameters to the default values.
7122

7123
    """
7124
    # hvparams
7125
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7126
    for name in self.op.hvparams.keys():
7127
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7128
        del self.op.hvparams[name]
7129
    # beparams
7130
    be_defs = cluster.SimpleFillBE({})
7131
    for name in self.op.beparams.keys():
7132
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7133
        del self.op.beparams[name]
7134
    # nic params
7135
    nic_defs = cluster.SimpleFillNIC({})
7136
    for nic in self.op.nics:
7137
      for name in constants.NICS_PARAMETERS:
7138
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7139
          del nic[name]
7140
    # osparams
7141
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7142
    for name in self.op.osparams.keys():
7143
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7144
        del self.op.osparams[name]
7145

    
7146
  def CheckPrereq(self):
7147
    """Check prerequisites.
7148

7149
    """
7150
    if self.op.mode == constants.INSTANCE_IMPORT:
7151
      export_info = self._ReadExportInfo()
7152
      self._ReadExportParams(export_info)
7153

    
7154
    if (not self.cfg.GetVGName() and
7155
        self.op.disk_template not in constants.DTS_NOT_LVM):
7156
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7157
                                 " instances", errors.ECODE_STATE)
7158

    
7159
    if self.op.hypervisor is None:
7160
      self.op.hypervisor = self.cfg.GetHypervisorType()
7161

    
7162
    cluster = self.cfg.GetClusterInfo()
7163
    enabled_hvs = cluster.enabled_hypervisors
7164
    if self.op.hypervisor not in enabled_hvs:
7165
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7166
                                 " cluster (%s)" % (self.op.hypervisor,
7167
                                  ",".join(enabled_hvs)),
7168
                                 errors.ECODE_STATE)
7169

    
7170
    # check hypervisor parameter syntax (locally)
7171
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7172
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7173
                                      self.op.hvparams)
7174
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7175
    hv_type.CheckParameterSyntax(filled_hvp)
7176
    self.hv_full = filled_hvp
7177
    # check that we don't specify global parameters on an instance
7178
    _CheckGlobalHvParams(self.op.hvparams)
7179

    
7180
    # fill and remember the beparams dict
7181
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7182
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7183

    
7184
    # build os parameters
7185
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7186

    
7187
    # now that hvp/bep are in final format, let's reset to defaults,
7188
    # if told to do so
7189
    if self.op.identify_defaults:
7190
      self._RevertToDefaults(cluster)
7191

    
7192
    # NIC buildup
7193
    self.nics = []
7194
    for idx, nic in enumerate(self.op.nics):
7195
      nic_mode_req = nic.get("mode", None)
7196
      nic_mode = nic_mode_req
7197
      if nic_mode is None:
7198
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7199

    
7200
      # in routed mode, for the first nic, the default ip is 'auto'
7201
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7202
        default_ip_mode = constants.VALUE_AUTO
7203
      else:
7204
        default_ip_mode = constants.VALUE_NONE
7205

    
7206
      # ip validity checks
7207
      ip = nic.get("ip", default_ip_mode)
7208
      if ip is None or ip.lower() == constants.VALUE_NONE:
7209
        nic_ip = None
7210
      elif ip.lower() == constants.VALUE_AUTO:
7211
        if not self.op.name_check:
7212
          raise errors.OpPrereqError("IP address set to auto but name checks"
7213
                                     " have been skipped",
7214
                                     errors.ECODE_INVAL)
7215
        nic_ip = self.hostname1.ip
7216
      else:
7217
        if not netutils.IPAddress.IsValid(ip):
7218
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7219
                                     errors.ECODE_INVAL)
7220
        nic_ip = ip
7221

    
7222
      # TODO: check the ip address for uniqueness
7223
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7224
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7225
                                   errors.ECODE_INVAL)
7226

    
7227
      # MAC address verification
7228
      mac = nic.get("mac", constants.VALUE_AUTO)
7229
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7230
        mac = utils.NormalizeAndValidateMac(mac)
7231

    
7232
        try:
7233
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7234
        except errors.ReservationError:
7235
          raise errors.OpPrereqError("MAC address %s already in use"
7236
                                     " in cluster" % mac,
7237
                                     errors.ECODE_NOTUNIQUE)
7238

    
7239
      # bridge verification
7240
      bridge = nic.get("bridge", None)
7241
      link = nic.get("link", None)
7242
      if bridge and link:
7243
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7244
                                   " at the same time", errors.ECODE_INVAL)
7245
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7246
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7247
                                   errors.ECODE_INVAL)
7248
      elif bridge:
7249
        link = bridge
7250

    
7251
      nicparams = {}
7252
      if nic_mode_req:
7253
        nicparams[constants.NIC_MODE] = nic_mode_req
7254
      if link:
7255
        nicparams[constants.NIC_LINK] = link
7256

    
7257
      check_params = cluster.SimpleFillNIC(nicparams)
7258
      objects.NIC.CheckParameterSyntax(check_params)
7259
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7260

    
7261
    # disk checks/pre-build
7262
    self.disks = []
7263
    for disk in self.op.disks:
7264
      mode = disk.get("mode", constants.DISK_RDWR)
7265
      if mode not in constants.DISK_ACCESS_SET:
7266
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7267
                                   mode, errors.ECODE_INVAL)
7268
      size = disk.get("size", None)
7269
      if size is None:
7270
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7271
      try:
7272
        size = int(size)
7273
      except (TypeError, ValueError):
7274
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7275
                                   errors.ECODE_INVAL)
7276
      vg = disk.get("vg", self.cfg.GetVGName())
7277
      new_disk = {"size": size, "mode": mode, "vg": vg}
7278
      if "adopt" in disk:
7279
        new_disk["adopt"] = disk["adopt"]
7280
      self.disks.append(new_disk)
7281

    
7282
    if self.op.mode == constants.INSTANCE_IMPORT:
7283

    
7284
      # Check that the new instance doesn't have less disks than the export
7285
      instance_disks = len(self.disks)
7286
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7287
      if instance_disks < export_disks:
7288
        raise errors.OpPrereqError("Not enough disks to import."
7289
                                   " (instance: %d, export: %d)" %
7290
                                   (instance_disks, export_disks),
7291
                                   errors.ECODE_INVAL)
7292

    
7293
      disk_images = []
7294
      for idx in range(export_disks):
7295
        option = 'disk%d_dump' % idx
7296
        if export_info.has_option(constants.INISECT_INS, option):
7297
          # FIXME: are the old os-es, disk sizes, etc. useful?
7298
          export_name = export_info.get(constants.INISECT_INS, option)
7299
          image = utils.PathJoin(self.op.src_path, export_name)
7300
          disk_images.append(image)
7301
        else:
7302
          disk_images.append(False)
7303

    
7304
      self.src_images = disk_images
7305

    
7306
      old_name = export_info.get(constants.INISECT_INS, 'name')
7307
      try:
7308
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7309
      except (TypeError, ValueError), err:
7310
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7311
                                   " an integer: %s" % str(err),
7312
                                   errors.ECODE_STATE)
7313
      if self.op.instance_name == old_name:
7314
        for idx, nic in enumerate(self.nics):
7315
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7316
            nic_mac_ini = 'nic%d_mac' % idx
7317
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7318

    
7319
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7320

    
7321
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7322
    if self.op.ip_check:
7323
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7324
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7325
                                   (self.check_ip, self.op.instance_name),
7326
                                   errors.ECODE_NOTUNIQUE)
7327

    
7328
    #### mac address generation
7329
    # By generating here the mac address both the allocator and the hooks get
7330
    # the real final mac address rather than the 'auto' or 'generate' value.
7331
    # There is a race condition between the generation and the instance object
7332
    # creation, which means that we know the mac is valid now, but we're not
7333
    # sure it will be when we actually add the instance. If things go bad
7334
    # adding the instance will abort because of a duplicate mac, and the
7335
    # creation job will fail.
7336
    for nic in self.nics:
7337
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7338
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7339

    
7340
    #### allocator run
7341

    
7342
    if self.op.iallocator is not None:
7343
      self._RunAllocator()
7344

    
7345
    #### node related checks
7346

    
7347
    # check primary node
7348
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7349
    assert self.pnode is not None, \
7350
      "Cannot retrieve locked node %s" % self.op.pnode
7351
    if pnode.offline:
7352
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7353
                                 pnode.name, errors.ECODE_STATE)
7354
    if pnode.drained:
7355
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7356
                                 pnode.name, errors.ECODE_STATE)
7357
    if not pnode.vm_capable:
7358
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7359
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7360

    
7361
    self.secondaries = []
7362

    
7363
    # mirror node verification
7364
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7365
      if self.op.snode == pnode.name:
7366
        raise errors.OpPrereqError("The secondary node cannot be the"
7367
                                   " primary node.", errors.ECODE_INVAL)
7368
      _CheckNodeOnline(self, self.op.snode)
7369
      _CheckNodeNotDrained(self, self.op.snode)
7370
      _CheckNodeVmCapable(self, self.op.snode)
7371
      self.secondaries.append(self.op.snode)
7372

    
7373
    nodenames = [pnode.name] + self.secondaries
7374

    
7375
    if not self.adopt_disks:
7376
      # Check lv size requirements, if not adopting
7377
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7378
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7379

    
7380
    else: # instead, we must check the adoption data
7381
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7382
      if len(all_lvs) != len(self.disks):
7383
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7384
                                   errors.ECODE_INVAL)
7385
      for lv_name in all_lvs:
7386
        try:
7387
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7388
          # to ReserveLV uses the same syntax
7389
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7390
        except errors.ReservationError:
7391
          raise errors.OpPrereqError("LV named %s used by another instance" %
7392
                                     lv_name, errors.ECODE_NOTUNIQUE)
7393

    
7394
      vg_names = self.rpc.call_vg_list([pnode.name])
7395
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7396

    
7397
      node_lvs = self.rpc.call_lv_list([pnode.name],
7398
                                       vg_names[pnode.name].payload.keys()
7399
                                      )[pnode.name]
7400
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7401
      node_lvs = node_lvs.payload
7402

    
7403
      delta = all_lvs.difference(node_lvs.keys())
7404
      if delta:
7405
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7406
                                   utils.CommaJoin(delta),
7407
                                   errors.ECODE_INVAL)
7408
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7409
      if online_lvs:
7410
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7411
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7412
                                   errors.ECODE_STATE)
7413
      # update the size of disk based on what is found
7414
      for dsk in self.disks:
7415
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7416

    
7417
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7418

    
7419
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7420
    # check OS parameters (remotely)
7421
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7422

    
7423
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7424

    
7425
    # memory check on primary node
7426
    if self.op.start:
7427
      _CheckNodeFreeMemory(self, self.pnode.name,
7428
                           "creating instance %s" % self.op.instance_name,
7429
                           self.be_full[constants.BE_MEMORY],
7430
                           self.op.hypervisor)
7431

    
7432
    self.dry_run_result = list(nodenames)
7433

    
7434
  def Exec(self, feedback_fn):
7435
    """Create and add the instance to the cluster.
7436

7437
    """
7438
    instance = self.op.instance_name
7439
    pnode_name = self.pnode.name
7440

    
7441
    ht_kind = self.op.hypervisor
7442
    if ht_kind in constants.HTS_REQ_PORT:
7443
      network_port = self.cfg.AllocatePort()
7444
    else:
7445
      network_port = None
7446

    
7447
    if constants.ENABLE_FILE_STORAGE:
7448
      # this is needed because os.path.join does not accept None arguments
7449
      if self.op.file_storage_dir is None:
7450
        string_file_storage_dir = ""
7451
      else:
7452
        string_file_storage_dir = self.op.file_storage_dir
7453

    
7454
      # build the full file storage dir path
7455
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7456
                                        string_file_storage_dir, instance)
7457
    else:
7458
      file_storage_dir = ""
7459

    
7460
    disks = _GenerateDiskTemplate(self,
7461
                                  self.op.disk_template,
7462
                                  instance, pnode_name,
7463
                                  self.secondaries,
7464
                                  self.disks,
7465
                                  file_storage_dir,
7466
                                  self.op.file_driver,
7467
                                  0,
7468
                                  feedback_fn)
7469

    
7470
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7471
                            primary_node=pnode_name,
7472
                            nics=self.nics, disks=disks,
7473
                            disk_template=self.op.disk_template,
7474
                            admin_up=False,
7475
                            network_port=network_port,
7476
                            beparams=self.op.beparams,
7477
                            hvparams=self.op.hvparams,
7478
                            hypervisor=self.op.hypervisor,
7479
                            osparams=self.op.osparams,
7480
                            )
7481

    
7482
    if self.adopt_disks:
7483
      # rename LVs to the newly-generated names; we need to construct
7484
      # 'fake' LV disks with the old data, plus the new unique_id
7485
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7486
      rename_to = []
7487
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7488
        rename_to.append(t_dsk.logical_id)
7489
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7490
        self.cfg.SetDiskID(t_dsk, pnode_name)
7491
      result = self.rpc.call_blockdev_rename(pnode_name,
7492
                                             zip(tmp_disks, rename_to))
7493
      result.Raise("Failed to rename adoped LVs")
7494
    else:
7495
      feedback_fn("* creating instance disks...")
7496
      try:
7497
        _CreateDisks(self, iobj)
7498
      except errors.OpExecError:
7499
        self.LogWarning("Device creation failed, reverting...")
7500
        try:
7501
          _RemoveDisks(self, iobj)
7502
        finally:
7503
          self.cfg.ReleaseDRBDMinors(instance)
7504
          raise
7505

    
7506
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7507
        feedback_fn("* wiping instance disks...")
7508
        try:
7509
          _WipeDisks(self, iobj)
7510
        except errors.OpExecError:
7511
          self.LogWarning("Device wiping failed, reverting...")
7512
          try:
7513
            _RemoveDisks(self, iobj)
7514
          finally:
7515
            self.cfg.ReleaseDRBDMinors(instance)
7516
            raise
7517

    
7518
    feedback_fn("adding instance %s to cluster config" % instance)
7519

    
7520
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7521

    
7522
    # Declare that we don't want to remove the instance lock anymore, as we've
7523
    # added the instance to the config
7524
    del self.remove_locks[locking.LEVEL_INSTANCE]
7525
    # Unlock all the nodes
7526
    if self.op.mode == constants.INSTANCE_IMPORT:
7527
      nodes_keep = [self.op.src_node]
7528
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7529
                       if node != self.op.src_node]
7530
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7531
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7532
    else:
7533
      self.context.glm.release(locking.LEVEL_NODE)
7534
      del self.acquired_locks[locking.LEVEL_NODE]
7535

    
7536
    if self.op.wait_for_sync:
7537
      disk_abort = not _WaitForSync(self, iobj)
7538
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7539
      # make sure the disks are not degraded (still sync-ing is ok)
7540
      time.sleep(15)
7541
      feedback_fn("* checking mirrors status")
7542
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7543
    else:
7544
      disk_abort = False
7545

    
7546
    if disk_abort:
7547
      _RemoveDisks(self, iobj)
7548
      self.cfg.RemoveInstance(iobj.name)
7549
      # Make sure the instance lock gets removed
7550
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7551
      raise errors.OpExecError("There are some degraded disks for"
7552
                               " this instance")
7553

    
7554
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7555
      if self.op.mode == constants.INSTANCE_CREATE:
7556
        if not self.op.no_install:
7557
          feedback_fn("* running the instance OS create scripts...")
7558
          # FIXME: pass debug option from opcode to backend
7559
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7560
                                                 self.op.debug_level)
7561
          result.Raise("Could not add os for instance %s"
7562
                       " on node %s" % (instance, pnode_name))
7563

    
7564
      elif self.op.mode == constants.INSTANCE_IMPORT:
7565
        feedback_fn("* running the instance OS import scripts...")
7566

    
7567
        transfers = []
7568

    
7569
        for idx, image in enumerate(self.src_images):
7570
          if not image:
7571
            continue
7572

    
7573
          # FIXME: pass debug option from opcode to backend
7574
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7575
                                             constants.IEIO_FILE, (image, ),
7576
                                             constants.IEIO_SCRIPT,
7577
                                             (iobj.disks[idx], idx),
7578
                                             None)
7579
          transfers.append(dt)
7580

    
7581
        import_result = \
7582
          masterd.instance.TransferInstanceData(self, feedback_fn,
7583
                                                self.op.src_node, pnode_name,
7584
                                                self.pnode.secondary_ip,
7585
                                                iobj, transfers)
7586
        if not compat.all(import_result):
7587
          self.LogWarning("Some disks for instance %s on node %s were not"
7588
                          " imported successfully" % (instance, pnode_name))
7589

    
7590
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7591
        feedback_fn("* preparing remote import...")
7592
        # The source cluster will stop the instance before attempting to make a
7593
        # connection. In some cases stopping an instance can take a long time,
7594
        # hence the shutdown timeout is added to the connection timeout.
7595
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
7596
                           self.op.source_shutdown_timeout)
7597
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7598

    
7599
        assert iobj.primary_node == self.pnode.name
7600
        disk_results = \
7601
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
7602
                                        self.source_x509_ca,
7603
                                        self._cds, timeouts)
7604
        if not compat.all(disk_results):
7605
          # TODO: Should the instance still be started, even if some disks
7606
          # failed to import (valid for local imports, too)?
7607
          self.LogWarning("Some disks for instance %s on node %s were not"
7608
                          " imported successfully" % (instance, pnode_name))
7609

    
7610
        # Run rename script on newly imported instance
7611
        assert iobj.name == instance
7612
        feedback_fn("Running rename script for %s" % instance)
7613
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7614
                                                   self.source_instance_name,
7615
                                                   self.op.debug_level)
7616
        if result.fail_msg:
7617
          self.LogWarning("Failed to run rename script for %s on node"
7618
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7619

    
7620
      else:
7621
        # also checked in the prereq part
7622
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7623
                                     % self.op.mode)
7624

    
7625
    if self.op.start:
7626
      iobj.admin_up = True
7627
      self.cfg.Update(iobj, feedback_fn)
7628
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7629
      feedback_fn("* starting instance...")
7630
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7631
      result.Raise("Could not start instance")
7632

    
7633
    return list(iobj.all_nodes)
7634

    
7635

    
7636
class LUConnectConsole(NoHooksLU):
7637
  """Connect to an instance's console.
7638

7639
  This is somewhat special in that it returns the command line that
7640
  you need to run on the master node in order to connect to the
7641
  console.
7642

7643
  """
7644
  REQ_BGL = False
7645

    
7646
  def ExpandNames(self):
7647
    self._ExpandAndLockInstance()
7648

    
7649
  def CheckPrereq(self):
7650
    """Check prerequisites.
7651

7652
    This checks that the instance is in the cluster.
7653

7654
    """
7655
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7656
    assert self.instance is not None, \
7657
      "Cannot retrieve locked instance %s" % self.op.instance_name
7658
    _CheckNodeOnline(self, self.instance.primary_node)
7659

    
7660
  def Exec(self, feedback_fn):
7661
    """Connect to the console of an instance
7662

7663
    """
7664
    instance = self.instance
7665
    node = instance.primary_node
7666

    
7667
    node_insts = self.rpc.call_instance_list([node],
7668
                                             [instance.hypervisor])[node]
7669
    node_insts.Raise("Can't get node information from %s" % node)
7670

    
7671
    if instance.name not in node_insts.payload:
7672
      if instance.admin_up:
7673
        state = "ERROR_down"
7674
      else:
7675
        state = "ADMIN_down"
7676
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7677
                               (instance.name, state))
7678

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

    
7681
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7682
    cluster = self.cfg.GetClusterInfo()
7683
    # beparams and hvparams are passed separately, to avoid editing the
7684
    # instance and then saving the defaults in the instance itself.
7685
    hvparams = cluster.FillHV(instance)
7686
    beparams = cluster.FillBE(instance)
7687
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7688

    
7689
    # build ssh cmdline
7690
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7691

    
7692

    
7693
class LUReplaceDisks(LogicalUnit):
7694
  """Replace the disks of an instance.
7695

7696
  """
7697
  HPATH = "mirrors-replace"
7698
  HTYPE = constants.HTYPE_INSTANCE
7699
  REQ_BGL = False
7700

    
7701
  def CheckArguments(self):
7702
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7703
                                  self.op.iallocator)
7704

    
7705
  def ExpandNames(self):
7706
    self._ExpandAndLockInstance()
7707

    
7708
    if self.op.iallocator is not None:
7709
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7710

    
7711
    elif self.op.remote_node is not None:
7712
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7713
      self.op.remote_node = remote_node
7714

    
7715
      # Warning: do not remove the locking of the new secondary here
7716
      # unless DRBD8.AddChildren is changed to work in parallel;
7717
      # currently it doesn't since parallel invocations of
7718
      # FindUnusedMinor will conflict
7719
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7720
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7721

    
7722
    else:
7723
      self.needed_locks[locking.LEVEL_NODE] = []
7724
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7725

    
7726
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7727
                                   self.op.iallocator, self.op.remote_node,
7728
                                   self.op.disks, False, self.op.early_release)
7729

    
7730
    self.tasklets = [self.replacer]
7731

    
7732
  def DeclareLocks(self, level):
7733
    # If we're not already locking all nodes in the set we have to declare the
7734
    # instance's primary/secondary nodes.
7735
    if (level == locking.LEVEL_NODE and
7736
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7737
      self._LockInstancesNodes()
7738

    
7739
  def BuildHooksEnv(self):
7740
    """Build hooks env.
7741

7742
    This runs on the master, the primary and all the secondaries.
7743

7744
    """
7745
    instance = self.replacer.instance
7746
    env = {
7747
      "MODE": self.op.mode,
7748
      "NEW_SECONDARY": self.op.remote_node,
7749
      "OLD_SECONDARY": instance.secondary_nodes[0],
7750
      }
7751
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7752
    nl = [
7753
      self.cfg.GetMasterNode(),
7754
      instance.primary_node,
7755
      ]
7756
    if self.op.remote_node is not None:
7757
      nl.append(self.op.remote_node)
7758
    return env, nl, nl
7759

    
7760

    
7761
class TLReplaceDisks(Tasklet):
7762
  """Replaces disks for an instance.
7763

7764
  Note: Locking is not within the scope of this class.
7765

7766
  """
7767
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7768
               disks, delay_iallocator, early_release):
7769
    """Initializes this class.
7770

7771
    """
7772
    Tasklet.__init__(self, lu)
7773

    
7774
    # Parameters
7775
    self.instance_name = instance_name
7776
    self.mode = mode
7777
    self.iallocator_name = iallocator_name
7778
    self.remote_node = remote_node
7779
    self.disks = disks
7780
    self.delay_iallocator = delay_iallocator
7781
    self.early_release = early_release
7782

    
7783
    # Runtime data
7784
    self.instance = None
7785
    self.new_node = None
7786
    self.target_node = None
7787
    self.other_node = None
7788
    self.remote_node_info = None
7789
    self.node_secondary_ip = None
7790

    
7791
  @staticmethod
7792
  def CheckArguments(mode, remote_node, iallocator):
7793
    """Helper function for users of this class.
7794

7795
    """
7796
    # check for valid parameter combination
7797
    if mode == constants.REPLACE_DISK_CHG:
7798
      if remote_node is None and iallocator is None:
7799
        raise errors.OpPrereqError("When changing the secondary either an"
7800
                                   " iallocator script must be used or the"
7801
                                   " new node given", errors.ECODE_INVAL)
7802

    
7803
      if remote_node is not None and iallocator is not None:
7804
        raise errors.OpPrereqError("Give either the iallocator or the new"
7805
                                   " secondary, not both", errors.ECODE_INVAL)
7806

    
7807
    elif remote_node is not None or iallocator is not None:
7808
      # Not replacing the secondary
7809
      raise errors.OpPrereqError("The iallocator and new node options can"
7810
                                 " only be used when changing the"
7811
                                 " secondary node", errors.ECODE_INVAL)
7812

    
7813
  @staticmethod
7814
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7815
    """Compute a new secondary node using an IAllocator.
7816

7817
    """
7818
    ial = IAllocator(lu.cfg, lu.rpc,
7819
                     mode=constants.IALLOCATOR_MODE_RELOC,
7820
                     name=instance_name,
7821
                     relocate_from=relocate_from)
7822

    
7823
    ial.Run(iallocator_name)
7824

    
7825
    if not ial.success:
7826
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7827
                                 " %s" % (iallocator_name, ial.info),
7828
                                 errors.ECODE_NORES)
7829

    
7830
    if len(ial.result) != ial.required_nodes:
7831
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7832
                                 " of nodes (%s), required %s" %
7833
                                 (iallocator_name,
7834
                                  len(ial.result), ial.required_nodes),
7835
                                 errors.ECODE_FAULT)
7836

    
7837
    remote_node_name = ial.result[0]
7838

    
7839
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7840
               instance_name, remote_node_name)
7841

    
7842
    return remote_node_name
7843

    
7844
  def _FindFaultyDisks(self, node_name):
7845
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7846
                                    node_name, True)
7847

    
7848
  def CheckPrereq(self):
7849
    """Check prerequisites.
7850

7851
    This checks that the instance is in the cluster.
7852

7853
    """
7854
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7855
    assert instance is not None, \
7856
      "Cannot retrieve locked instance %s" % self.instance_name
7857

    
7858
    if instance.disk_template != constants.DT_DRBD8:
7859
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7860
                                 " instances", errors.ECODE_INVAL)
7861

    
7862
    if len(instance.secondary_nodes) != 1:
7863
      raise errors.OpPrereqError("The instance has a strange layout,"
7864
                                 " expected one secondary but found %d" %
7865
                                 len(instance.secondary_nodes),
7866
                                 errors.ECODE_FAULT)
7867

    
7868
    if not self.delay_iallocator:
7869
      self._CheckPrereq2()
7870

    
7871
  def _CheckPrereq2(self):
7872
    """Check prerequisites, second part.
7873

7874
    This function should always be part of CheckPrereq. It was separated and is
7875
    now called from Exec because during node evacuation iallocator was only
7876
    called with an unmodified cluster model, not taking planned changes into
7877
    account.
7878

7879
    """
7880
    instance = self.instance
7881
    secondary_node = instance.secondary_nodes[0]
7882

    
7883
    if self.iallocator_name is None:
7884
      remote_node = self.remote_node
7885
    else:
7886
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7887
                                       instance.name, instance.secondary_nodes)
7888

    
7889
    if remote_node is not None:
7890
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7891
      assert self.remote_node_info is not None, \
7892
        "Cannot retrieve locked node %s" % remote_node
7893
    else:
7894
      self.remote_node_info = None
7895

    
7896
    if remote_node == self.instance.primary_node:
7897
      raise errors.OpPrereqError("The specified node is the primary node of"
7898
                                 " the instance.", errors.ECODE_INVAL)
7899

    
7900
    if remote_node == secondary_node:
7901
      raise errors.OpPrereqError("The specified node is already the"
7902
                                 " secondary node of the instance.",
7903
                                 errors.ECODE_INVAL)
7904

    
7905
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7906
                                    constants.REPLACE_DISK_CHG):
7907
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7908
                                 errors.ECODE_INVAL)
7909

    
7910
    if self.mode == constants.REPLACE_DISK_AUTO:
7911
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7912
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7913

    
7914
      if faulty_primary and faulty_secondary:
7915
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7916
                                   " one node and can not be repaired"
7917
                                   " automatically" % self.instance_name,
7918
                                   errors.ECODE_STATE)
7919

    
7920
      if faulty_primary:
7921
        self.disks = faulty_primary
7922
        self.target_node = instance.primary_node
7923
        self.other_node = secondary_node
7924
        check_nodes = [self.target_node, self.other_node]
7925
      elif faulty_secondary:
7926
        self.disks = faulty_secondary
7927
        self.target_node = secondary_node
7928
        self.other_node = instance.primary_node
7929
        check_nodes = [self.target_node, self.other_node]
7930
      else:
7931
        self.disks = []
7932
        check_nodes = []
7933

    
7934
    else:
7935
      # Non-automatic modes
7936
      if self.mode == constants.REPLACE_DISK_PRI:
7937
        self.target_node = instance.primary_node
7938
        self.other_node = secondary_node
7939
        check_nodes = [self.target_node, self.other_node]
7940

    
7941
      elif self.mode == constants.REPLACE_DISK_SEC:
7942
        self.target_node = secondary_node
7943
        self.other_node = instance.primary_node
7944
        check_nodes = [self.target_node, self.other_node]
7945

    
7946
      elif self.mode == constants.REPLACE_DISK_CHG:
7947
        self.new_node = remote_node
7948
        self.other_node = instance.primary_node
7949
        self.target_node = secondary_node
7950
        check_nodes = [self.new_node, self.other_node]
7951

    
7952
        _CheckNodeNotDrained(self.lu, remote_node)
7953
        _CheckNodeVmCapable(self.lu, remote_node)
7954

    
7955
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7956
        assert old_node_info is not None
7957
        if old_node_info.offline and not self.early_release:
7958
          # doesn't make sense to delay the release
7959
          self.early_release = True
7960
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7961
                          " early-release mode", secondary_node)
7962

    
7963
      else:
7964
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7965
                                     self.mode)
7966

    
7967
      # If not specified all disks should be replaced
7968
      if not self.disks:
7969
        self.disks = range(len(self.instance.disks))
7970

    
7971
    for node in check_nodes:
7972
      _CheckNodeOnline(self.lu, node)
7973

    
7974
    # Check whether disks are valid
7975
    for disk_idx in self.disks:
7976
      instance.FindDisk(disk_idx)
7977

    
7978
    # Get secondary node IP addresses
7979
    node_2nd_ip = {}
7980

    
7981
    for node_name in [self.target_node, self.other_node, self.new_node]:
7982
      if node_name is not None:
7983
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7984

    
7985
    self.node_secondary_ip = node_2nd_ip
7986

    
7987
  def Exec(self, feedback_fn):
7988
    """Execute disk replacement.
7989

7990
    This dispatches the disk replacement to the appropriate handler.
7991

7992
    """
7993
    if self.delay_iallocator:
7994
      self._CheckPrereq2()
7995

    
7996
    if not self.disks:
7997
      feedback_fn("No disks need replacement")
7998
      return
7999

    
8000
    feedback_fn("Replacing disk(s) %s for %s" %
8001
                (utils.CommaJoin(self.disks), self.instance.name))
8002

    
8003
    activate_disks = (not self.instance.admin_up)
8004

    
8005
    # Activate the instance disks if we're replacing them on a down instance
8006
    if activate_disks:
8007
      _StartInstanceDisks(self.lu, self.instance, True)
8008

    
8009
    try:
8010
      # Should we replace the secondary node?
8011
      if self.new_node is not None:
8012
        fn = self._ExecDrbd8Secondary
8013
      else:
8014
        fn = self._ExecDrbd8DiskOnly
8015

    
8016
      return fn(feedback_fn)
8017

    
8018
    finally:
8019
      # Deactivate the instance disks if we're replacing them on a
8020
      # down instance
8021
      if activate_disks:
8022
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8023

    
8024
  def _CheckVolumeGroup(self, nodes):
8025
    self.lu.LogInfo("Checking volume groups")
8026

    
8027
    vgname = self.cfg.GetVGName()
8028

    
8029
    # Make sure volume group exists on all involved nodes
8030
    results = self.rpc.call_vg_list(nodes)
8031
    if not results:
8032
      raise errors.OpExecError("Can't list volume groups on the nodes")
8033

    
8034
    for node in nodes:
8035
      res = results[node]
8036
      res.Raise("Error checking node %s" % node)
8037
      if vgname not in res.payload:
8038
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8039
                                 (vgname, node))
8040

    
8041
  def _CheckDisksExistence(self, nodes):
8042
    # Check disk existence
8043
    for idx, dev in enumerate(self.instance.disks):
8044
      if idx not in self.disks:
8045
        continue
8046

    
8047
      for node in nodes:
8048
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8049
        self.cfg.SetDiskID(dev, node)
8050

    
8051
        result = self.rpc.call_blockdev_find(node, dev)
8052

    
8053
        msg = result.fail_msg
8054
        if msg or not result.payload:
8055
          if not msg:
8056
            msg = "disk not found"
8057
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8058
                                   (idx, node, msg))
8059

    
8060
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8061
    for idx, dev in enumerate(self.instance.disks):
8062
      if idx not in self.disks:
8063
        continue
8064

    
8065
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8066
                      (idx, node_name))
8067

    
8068
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8069
                                   ldisk=ldisk):
8070
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8071
                                 " replace disks for instance %s" %
8072
                                 (node_name, self.instance.name))
8073

    
8074
  def _CreateNewStorage(self, node_name):
8075
    vgname = self.cfg.GetVGName()
8076
    iv_names = {}
8077

    
8078
    for idx, dev in enumerate(self.instance.disks):
8079
      if idx not in self.disks:
8080
        continue
8081

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

    
8084
      self.cfg.SetDiskID(dev, node_name)
8085

    
8086
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8087
      names = _GenerateUniqueNames(self.lu, lv_names)
8088

    
8089
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8090
                             logical_id=(vgname, names[0]))
8091
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8092
                             logical_id=(vgname, names[1]))
8093

    
8094
      new_lvs = [lv_data, lv_meta]
8095
      old_lvs = dev.children
8096
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8097

    
8098
      # we pass force_create=True to force the LVM creation
8099
      for new_lv in new_lvs:
8100
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8101
                        _GetInstanceInfoText(self.instance), False)
8102

    
8103
    return iv_names
8104

    
8105
  def _CheckDevices(self, node_name, iv_names):
8106
    for name, (dev, _, _) in iv_names.iteritems():
8107
      self.cfg.SetDiskID(dev, node_name)
8108

    
8109
      result = self.rpc.call_blockdev_find(node_name, dev)
8110

    
8111
      msg = result.fail_msg
8112
      if msg or not result.payload:
8113
        if not msg:
8114
          msg = "disk not found"
8115
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8116
                                 (name, msg))
8117

    
8118
      if result.payload.is_degraded:
8119
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8120

    
8121
  def _RemoveOldStorage(self, node_name, iv_names):
8122
    for name, (_, old_lvs, _) in iv_names.iteritems():
8123
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8124

    
8125
      for lv in old_lvs:
8126
        self.cfg.SetDiskID(lv, node_name)
8127

    
8128
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8129
        if msg:
8130
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8131
                             hint="remove unused LVs manually")
8132

    
8133
  def _ReleaseNodeLock(self, node_name):
8134
    """Releases the lock for a given node."""
8135
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8136

    
8137
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8138
    """Replace a disk on the primary or secondary for DRBD 8.
8139

8140
    The algorithm for replace is quite complicated:
8141

8142
      1. for each disk to be replaced:
8143

8144
        1. create new LVs on the target node with unique names
8145
        1. detach old LVs from the drbd device
8146
        1. rename old LVs to name_replaced.<time_t>
8147
        1. rename new LVs to old LVs
8148
        1. attach the new LVs (with the old names now) to the drbd device
8149

8150
      1. wait for sync across all devices
8151

8152
      1. for each modified disk:
8153

8154
        1. remove old LVs (which have the name name_replaces.<time_t>)
8155

8156
    Failures are not very well handled.
8157

8158
    """
8159
    steps_total = 6
8160

    
8161
    # Step: check device activation
8162
    self.lu.LogStep(1, steps_total, "Check device existence")
8163
    self._CheckDisksExistence([self.other_node, self.target_node])
8164
    self._CheckVolumeGroup([self.target_node, self.other_node])
8165

    
8166
    # Step: check other node consistency
8167
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8168
    self._CheckDisksConsistency(self.other_node,
8169
                                self.other_node == self.instance.primary_node,
8170
                                False)
8171

    
8172
    # Step: create new storage
8173
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8174
    iv_names = self._CreateNewStorage(self.target_node)
8175

    
8176
    # Step: for each lv, detach+rename*2+attach
8177
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8178
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8179
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8180

    
8181
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8182
                                                     old_lvs)
8183
      result.Raise("Can't detach drbd from local storage on node"
8184
                   " %s for device %s" % (self.target_node, dev.iv_name))
8185
      #dev.children = []
8186
      #cfg.Update(instance)
8187

    
8188
      # ok, we created the new LVs, so now we know we have the needed
8189
      # storage; as such, we proceed on the target node to rename
8190
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8191
      # using the assumption that logical_id == physical_id (which in
8192
      # turn is the unique_id on that node)
8193

    
8194
      # FIXME(iustin): use a better name for the replaced LVs
8195
      temp_suffix = int(time.time())
8196
      ren_fn = lambda d, suff: (d.physical_id[0],
8197
                                d.physical_id[1] + "_replaced-%s" % suff)
8198

    
8199
      # Build the rename list based on what LVs exist on the node
8200
      rename_old_to_new = []
8201
      for to_ren in old_lvs:
8202
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8203
        if not result.fail_msg and result.payload:
8204
          # device exists
8205
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8206

    
8207
      self.lu.LogInfo("Renaming the old LVs on the target node")
8208
      result = self.rpc.call_blockdev_rename(self.target_node,
8209
                                             rename_old_to_new)
8210
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8211

    
8212
      # Now we rename the new LVs to the old LVs
8213
      self.lu.LogInfo("Renaming the new LVs on the target node")
8214
      rename_new_to_old = [(new, old.physical_id)
8215
                           for old, new in zip(old_lvs, new_lvs)]
8216
      result = self.rpc.call_blockdev_rename(self.target_node,
8217
                                             rename_new_to_old)
8218
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8219

    
8220
      for old, new in zip(old_lvs, new_lvs):
8221
        new.logical_id = old.logical_id
8222
        self.cfg.SetDiskID(new, self.target_node)
8223

    
8224
      for disk in old_lvs:
8225
        disk.logical_id = ren_fn(disk, temp_suffix)
8226
        self.cfg.SetDiskID(disk, self.target_node)
8227

    
8228
      # Now that the new lvs have the old name, we can add them to the device
8229
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8230
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8231
                                                  new_lvs)
8232
      msg = result.fail_msg
8233
      if msg:
8234
        for new_lv in new_lvs:
8235
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8236
                                               new_lv).fail_msg
8237
          if msg2:
8238
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8239
                               hint=("cleanup manually the unused logical"
8240
                                     "volumes"))
8241
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8242

    
8243
      dev.children = new_lvs
8244

    
8245
      self.cfg.Update(self.instance, feedback_fn)
8246

    
8247
    cstep = 5
8248
    if self.early_release:
8249
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8250
      cstep += 1
8251
      self._RemoveOldStorage(self.target_node, iv_names)
8252
      # WARNING: we release both node locks here, do not do other RPCs
8253
      # than WaitForSync to the primary node
8254
      self._ReleaseNodeLock([self.target_node, self.other_node])
8255

    
8256
    # Wait for sync
8257
    # This can fail as the old devices are degraded and _WaitForSync
8258
    # does a combined result over all disks, so we don't check its return value
8259
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8260
    cstep += 1
8261
    _WaitForSync(self.lu, self.instance)
8262

    
8263
    # Check all devices manually
8264
    self._CheckDevices(self.instance.primary_node, iv_names)
8265

    
8266
    # Step: remove old storage
8267
    if not self.early_release:
8268
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8269
      cstep += 1
8270
      self._RemoveOldStorage(self.target_node, iv_names)
8271

    
8272
  def _ExecDrbd8Secondary(self, feedback_fn):
8273
    """Replace the secondary node for DRBD 8.
8274

8275
    The algorithm for replace is quite complicated:
8276
      - for all disks of the instance:
8277
        - create new LVs on the new node with same names
8278
        - shutdown the drbd device on the old secondary
8279
        - disconnect the drbd network on the primary
8280
        - create the drbd device on the new secondary
8281
        - network attach the drbd on the primary, using an artifice:
8282
          the drbd code for Attach() will connect to the network if it
8283
          finds a device which is connected to the good local disks but
8284
          not network enabled
8285
      - wait for sync across all devices
8286
      - remove all disks from the old secondary
8287

8288
    Failures are not very well handled.
8289

8290
    """
8291
    steps_total = 6
8292

    
8293
    # Step: check device activation
8294
    self.lu.LogStep(1, steps_total, "Check device existence")
8295
    self._CheckDisksExistence([self.instance.primary_node])
8296
    self._CheckVolumeGroup([self.instance.primary_node])
8297

    
8298
    # Step: check other node consistency
8299
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8300
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8301

    
8302
    # Step: create new storage
8303
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8304
    for idx, dev in enumerate(self.instance.disks):
8305
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8306
                      (self.new_node, idx))
8307
      # we pass force_create=True to force LVM creation
8308
      for new_lv in dev.children:
8309
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8310
                        _GetInstanceInfoText(self.instance), False)
8311

    
8312
    # Step 4: dbrd minors and drbd setups changes
8313
    # after this, we must manually remove the drbd minors on both the
8314
    # error and the success paths
8315
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8316
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8317
                                         for dev in self.instance.disks],
8318
                                        self.instance.name)
8319
    logging.debug("Allocated minors %r", minors)
8320

    
8321
    iv_names = {}
8322
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8323
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8324
                      (self.new_node, idx))
8325
      # create new devices on new_node; note that we create two IDs:
8326
      # one without port, so the drbd will be activated without
8327
      # networking information on the new node at this stage, and one
8328
      # with network, for the latter activation in step 4
8329
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8330
      if self.instance.primary_node == o_node1:
8331
        p_minor = o_minor1
8332
      else:
8333
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8334
        p_minor = o_minor2
8335

    
8336
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8337
                      p_minor, new_minor, o_secret)
8338
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8339
                    p_minor, new_minor, o_secret)
8340

    
8341
      iv_names[idx] = (dev, dev.children, new_net_id)
8342
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8343
                    new_net_id)
8344
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8345
                              logical_id=new_alone_id,
8346
                              children=dev.children,
8347
                              size=dev.size)
8348
      try:
8349
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8350
                              _GetInstanceInfoText(self.instance), False)
8351
      except errors.GenericError:
8352
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8353
        raise
8354

    
8355
    # We have new devices, shutdown the drbd on the old secondary
8356
    for idx, dev in enumerate(self.instance.disks):
8357
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8358
      self.cfg.SetDiskID(dev, self.target_node)
8359
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8360
      if msg:
8361
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8362
                           "node: %s" % (idx, msg),
8363
                           hint=("Please cleanup this device manually as"
8364
                                 " soon as possible"))
8365

    
8366
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8367
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8368
                                               self.node_secondary_ip,
8369
                                               self.instance.disks)\
8370
                                              [self.instance.primary_node]
8371

    
8372
    msg = result.fail_msg
8373
    if msg:
8374
      # detaches didn't succeed (unlikely)
8375
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8376
      raise errors.OpExecError("Can't detach the disks from the network on"
8377
                               " old node: %s" % (msg,))
8378

    
8379
    # if we managed to detach at least one, we update all the disks of
8380
    # the instance to point to the new secondary
8381
    self.lu.LogInfo("Updating instance configuration")
8382
    for dev, _, new_logical_id in iv_names.itervalues():
8383
      dev.logical_id = new_logical_id
8384
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8385

    
8386
    self.cfg.Update(self.instance, feedback_fn)
8387

    
8388
    # and now perform the drbd attach
8389
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8390
                    " (standalone => connected)")
8391
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8392
                                            self.new_node],
8393
                                           self.node_secondary_ip,
8394
                                           self.instance.disks,
8395
                                           self.instance.name,
8396
                                           False)
8397
    for to_node, to_result in result.items():
8398
      msg = to_result.fail_msg
8399
      if msg:
8400
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8401
                           to_node, msg,
8402
                           hint=("please do a gnt-instance info to see the"
8403
                                 " status of disks"))
8404
    cstep = 5
8405
    if self.early_release:
8406
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8407
      cstep += 1
8408
      self._RemoveOldStorage(self.target_node, iv_names)
8409
      # WARNING: we release all node locks here, do not do other RPCs
8410
      # than WaitForSync to the primary node
8411
      self._ReleaseNodeLock([self.instance.primary_node,
8412
                             self.target_node,
8413
                             self.new_node])
8414

    
8415
    # Wait for sync
8416
    # This can fail as the old devices are degraded and _WaitForSync
8417
    # does a combined result over all disks, so we don't check its return value
8418
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8419
    cstep += 1
8420
    _WaitForSync(self.lu, self.instance)
8421

    
8422
    # Check all devices manually
8423
    self._CheckDevices(self.instance.primary_node, iv_names)
8424

    
8425
    # Step: remove old storage
8426
    if not self.early_release:
8427
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8428
      self._RemoveOldStorage(self.target_node, iv_names)
8429

    
8430

    
8431
class LURepairNodeStorage(NoHooksLU):
8432
  """Repairs the volume group on a node.
8433

8434
  """
8435
  REQ_BGL = False
8436

    
8437
  def CheckArguments(self):
8438
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8439

    
8440
    storage_type = self.op.storage_type
8441

    
8442
    if (constants.SO_FIX_CONSISTENCY not in
8443
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8444
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8445
                                 " repaired" % storage_type,
8446
                                 errors.ECODE_INVAL)
8447

    
8448
  def ExpandNames(self):
8449
    self.needed_locks = {
8450
      locking.LEVEL_NODE: [self.op.node_name],
8451
      }
8452

    
8453
  def _CheckFaultyDisks(self, instance, node_name):
8454
    """Ensure faulty disks abort the opcode or at least warn."""
8455
    try:
8456
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8457
                                  node_name, True):
8458
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8459
                                   " node '%s'" % (instance.name, node_name),
8460
                                   errors.ECODE_STATE)
8461
    except errors.OpPrereqError, err:
8462
      if self.op.ignore_consistency:
8463
        self.proc.LogWarning(str(err.args[0]))
8464
      else:
8465
        raise
8466

    
8467
  def CheckPrereq(self):
8468
    """Check prerequisites.
8469

8470
    """
8471
    # Check whether any instance on this node has faulty disks
8472
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8473
      if not inst.admin_up:
8474
        continue
8475
      check_nodes = set(inst.all_nodes)
8476
      check_nodes.discard(self.op.node_name)
8477
      for inst_node_name in check_nodes:
8478
        self._CheckFaultyDisks(inst, inst_node_name)
8479

    
8480
  def Exec(self, feedback_fn):
8481
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8482
                (self.op.name, self.op.node_name))
8483

    
8484
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8485
    result = self.rpc.call_storage_execute(self.op.node_name,
8486
                                           self.op.storage_type, st_args,
8487
                                           self.op.name,
8488
                                           constants.SO_FIX_CONSISTENCY)
8489
    result.Raise("Failed to repair storage unit '%s' on %s" %
8490
                 (self.op.name, self.op.node_name))
8491

    
8492

    
8493
class LUNodeEvacuationStrategy(NoHooksLU):
8494
  """Computes the node evacuation strategy.
8495

8496
  """
8497
  REQ_BGL = False
8498

    
8499
  def CheckArguments(self):
8500
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8501

    
8502
  def ExpandNames(self):
8503
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8504
    self.needed_locks = locks = {}
8505
    if self.op.remote_node is None:
8506
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8507
    else:
8508
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8509
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8510

    
8511
  def Exec(self, feedback_fn):
8512
    if self.op.remote_node is not None:
8513
      instances = []
8514
      for node in self.op.nodes:
8515
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8516
      result = []
8517
      for i in instances:
8518
        if i.primary_node == self.op.remote_node:
8519
          raise errors.OpPrereqError("Node %s is the primary node of"
8520
                                     " instance %s, cannot use it as"
8521
                                     " secondary" %
8522
                                     (self.op.remote_node, i.name),
8523
                                     errors.ECODE_INVAL)
8524
        result.append([i.name, self.op.remote_node])
8525
    else:
8526
      ial = IAllocator(self.cfg, self.rpc,
8527
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8528
                       evac_nodes=self.op.nodes)
8529
      ial.Run(self.op.iallocator, validate=True)
8530
      if not ial.success:
8531
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8532
                                 errors.ECODE_NORES)
8533
      result = ial.result
8534
    return result
8535

    
8536

    
8537
class LUGrowDisk(LogicalUnit):
8538
  """Grow a disk of an instance.
8539

8540
  """
8541
  HPATH = "disk-grow"
8542
  HTYPE = constants.HTYPE_INSTANCE
8543
  REQ_BGL = False
8544

    
8545
  def ExpandNames(self):
8546
    self._ExpandAndLockInstance()
8547
    self.needed_locks[locking.LEVEL_NODE] = []
8548
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8549

    
8550
  def DeclareLocks(self, level):
8551
    if level == locking.LEVEL_NODE:
8552
      self._LockInstancesNodes()
8553

    
8554
  def BuildHooksEnv(self):
8555
    """Build hooks env.
8556

8557
    This runs on the master, the primary and all the secondaries.
8558

8559
    """
8560
    env = {
8561
      "DISK": self.op.disk,
8562
      "AMOUNT": self.op.amount,
8563
      }
8564
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8565
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8566
    return env, nl, nl
8567

    
8568
  def CheckPrereq(self):
8569
    """Check prerequisites.
8570

8571
    This checks that the instance is in the cluster.
8572

8573
    """
8574
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8575
    assert instance is not None, \
8576
      "Cannot retrieve locked instance %s" % self.op.instance_name
8577
    nodenames = list(instance.all_nodes)
8578
    for node in nodenames:
8579
      _CheckNodeOnline(self, node)
8580

    
8581
    self.instance = instance
8582

    
8583
    if instance.disk_template not in constants.DTS_GROWABLE:
8584
      raise errors.OpPrereqError("Instance's disk layout does not support"
8585
                                 " growing.", errors.ECODE_INVAL)
8586

    
8587
    self.disk = instance.FindDisk(self.op.disk)
8588

    
8589
    if instance.disk_template != constants.DT_FILE:
8590
      # TODO: check the free disk space for file, when that feature
8591
      # will be supported
8592
      _CheckNodesFreeDiskPerVG(self, nodenames,
8593
                               {self.disk.physical_id[0]: self.op.amount})
8594

    
8595
  def Exec(self, feedback_fn):
8596
    """Execute disk grow.
8597

8598
    """
8599
    instance = self.instance
8600
    disk = self.disk
8601

    
8602
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8603
    if not disks_ok:
8604
      raise errors.OpExecError("Cannot activate block device to grow")
8605

    
8606
    for node in instance.all_nodes:
8607
      self.cfg.SetDiskID(disk, node)
8608
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8609
      result.Raise("Grow request failed to node %s" % node)
8610

    
8611
      # TODO: Rewrite code to work properly
8612
      # DRBD goes into sync mode for a short amount of time after executing the
8613
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8614
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8615
      # time is a work-around.
8616
      time.sleep(5)
8617

    
8618
    disk.RecordGrow(self.op.amount)
8619
    self.cfg.Update(instance, feedback_fn)
8620
    if self.op.wait_for_sync:
8621
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8622
      if disk_abort:
8623
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8624
                             " status.\nPlease check the instance.")
8625
      if not instance.admin_up:
8626
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8627
    elif not instance.admin_up:
8628
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8629
                           " not supposed to be running because no wait for"
8630
                           " sync mode was requested.")
8631

    
8632

    
8633
class LUQueryInstanceData(NoHooksLU):
8634
  """Query runtime instance data.
8635

8636
  """
8637
  REQ_BGL = False
8638

    
8639
  def ExpandNames(self):
8640
    self.needed_locks = {}
8641
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8642

    
8643
    if self.op.instances:
8644
      self.wanted_names = []
8645
      for name in self.op.instances:
8646
        full_name = _ExpandInstanceName(self.cfg, name)
8647
        self.wanted_names.append(full_name)
8648
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8649
    else:
8650
      self.wanted_names = None
8651
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8652

    
8653
    self.needed_locks[locking.LEVEL_NODE] = []
8654
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8655

    
8656
  def DeclareLocks(self, level):
8657
    if level == locking.LEVEL_NODE:
8658
      self._LockInstancesNodes()
8659

    
8660
  def CheckPrereq(self):
8661
    """Check prerequisites.
8662

8663
    This only checks the optional instance list against the existing names.
8664

8665
    """
8666
    if self.wanted_names is None:
8667
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8668

    
8669
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8670
                             in self.wanted_names]
8671

    
8672
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8673
    """Returns the status of a block device
8674

8675
    """
8676
    if self.op.static or not node:
8677
      return None
8678

    
8679
    self.cfg.SetDiskID(dev, node)
8680

    
8681
    result = self.rpc.call_blockdev_find(node, dev)
8682
    if result.offline:
8683
      return None
8684

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

    
8687
    status = result.payload
8688
    if status is None:
8689
      return None
8690

    
8691
    return (status.dev_path, status.major, status.minor,
8692
            status.sync_percent, status.estimated_time,
8693
            status.is_degraded, status.ldisk_status)
8694

    
8695
  def _ComputeDiskStatus(self, instance, snode, dev):
8696
    """Compute block device status.
8697

8698
    """
8699
    if dev.dev_type in constants.LDS_DRBD:
8700
      # we change the snode then (otherwise we use the one passed in)
8701
      if dev.logical_id[0] == instance.primary_node:
8702
        snode = dev.logical_id[1]
8703
      else:
8704
        snode = dev.logical_id[0]
8705

    
8706
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8707
                                              instance.name, dev)
8708
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8709

    
8710
    if dev.children:
8711
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8712
                      for child in dev.children]
8713
    else:
8714
      dev_children = []
8715

    
8716
    data = {
8717
      "iv_name": dev.iv_name,
8718
      "dev_type": dev.dev_type,
8719
      "logical_id": dev.logical_id,
8720
      "physical_id": dev.physical_id,
8721
      "pstatus": dev_pstatus,
8722
      "sstatus": dev_sstatus,
8723
      "children": dev_children,
8724
      "mode": dev.mode,
8725
      "size": dev.size,
8726
      }
8727

    
8728
    return data
8729

    
8730
  def Exec(self, feedback_fn):
8731
    """Gather and return data"""
8732
    result = {}
8733

    
8734
    cluster = self.cfg.GetClusterInfo()
8735

    
8736
    for instance in self.wanted_instances:
8737
      if not self.op.static:
8738
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8739
                                                  instance.name,
8740
                                                  instance.hypervisor)
8741
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8742
        remote_info = remote_info.payload
8743
        if remote_info and "state" in remote_info:
8744
          remote_state = "up"
8745
        else:
8746
          remote_state = "down"
8747
      else:
8748
        remote_state = None
8749
      if instance.admin_up:
8750
        config_state = "up"
8751
      else:
8752
        config_state = "down"
8753

    
8754
      disks = [self._ComputeDiskStatus(instance, None, device)
8755
               for device in instance.disks]
8756

    
8757
      idict = {
8758
        "name": instance.name,
8759
        "config_state": config_state,
8760
        "run_state": remote_state,
8761
        "pnode": instance.primary_node,
8762
        "snodes": instance.secondary_nodes,
8763
        "os": instance.os,
8764
        # this happens to be the same format used for hooks
8765
        "nics": _NICListToTuple(self, instance.nics),
8766
        "disk_template": instance.disk_template,
8767
        "disks": disks,
8768
        "hypervisor": instance.hypervisor,
8769
        "network_port": instance.network_port,
8770
        "hv_instance": instance.hvparams,
8771
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8772
        "be_instance": instance.beparams,
8773
        "be_actual": cluster.FillBE(instance),
8774
        "os_instance": instance.osparams,
8775
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8776
        "serial_no": instance.serial_no,
8777
        "mtime": instance.mtime,
8778
        "ctime": instance.ctime,
8779
        "uuid": instance.uuid,
8780
        }
8781

    
8782
      result[instance.name] = idict
8783

    
8784
    return result
8785

    
8786

    
8787
class LUSetInstanceParams(LogicalUnit):
8788
  """Modifies an instances's parameters.
8789

8790
  """
8791
  HPATH = "instance-modify"
8792
  HTYPE = constants.HTYPE_INSTANCE
8793
  REQ_BGL = False
8794

    
8795
  def CheckArguments(self):
8796
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8797
            self.op.hvparams or self.op.beparams or self.op.os_name):
8798
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8799

    
8800
    if self.op.hvparams:
8801
      _CheckGlobalHvParams(self.op.hvparams)
8802

    
8803
    # Disk validation
8804
    disk_addremove = 0
8805
    for disk_op, disk_dict in self.op.disks:
8806
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8807
      if disk_op == constants.DDM_REMOVE:
8808
        disk_addremove += 1
8809
        continue
8810
      elif disk_op == constants.DDM_ADD:
8811
        disk_addremove += 1
8812
      else:
8813
        if not isinstance(disk_op, int):
8814
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8815
        if not isinstance(disk_dict, dict):
8816
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8817
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8818

    
8819
      if disk_op == constants.DDM_ADD:
8820
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8821
        if mode not in constants.DISK_ACCESS_SET:
8822
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8823
                                     errors.ECODE_INVAL)
8824
        size = disk_dict.get('size', None)
8825
        if size is None:
8826
          raise errors.OpPrereqError("Required disk parameter size missing",
8827
                                     errors.ECODE_INVAL)
8828
        try:
8829
          size = int(size)
8830
        except (TypeError, ValueError), err:
8831
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8832
                                     str(err), errors.ECODE_INVAL)
8833
        disk_dict['size'] = size
8834
      else:
8835
        # modification of disk
8836
        if 'size' in disk_dict:
8837
          raise errors.OpPrereqError("Disk size change not possible, use"
8838
                                     " grow-disk", errors.ECODE_INVAL)
8839

    
8840
    if disk_addremove > 1:
8841
      raise errors.OpPrereqError("Only one disk add or remove operation"
8842
                                 " supported at a time", errors.ECODE_INVAL)
8843

    
8844
    if self.op.disks and self.op.disk_template is not None:
8845
      raise errors.OpPrereqError("Disk template conversion and other disk"
8846
                                 " changes not supported at the same time",
8847
                                 errors.ECODE_INVAL)
8848

    
8849
    if (self.op.disk_template and
8850
        self.op.disk_template in constants.DTS_NET_MIRROR and
8851
        self.op.remote_node is None):
8852
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
8853
                                 " one requires specifying a secondary node",
8854
                                 errors.ECODE_INVAL)
8855

    
8856
    # NIC validation
8857
    nic_addremove = 0
8858
    for nic_op, nic_dict in self.op.nics:
8859
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8860
      if nic_op == constants.DDM_REMOVE:
8861
        nic_addremove += 1
8862
        continue
8863
      elif nic_op == constants.DDM_ADD:
8864
        nic_addremove += 1
8865
      else:
8866
        if not isinstance(nic_op, int):
8867
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8868
        if not isinstance(nic_dict, dict):
8869
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8870
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8871

    
8872
      # nic_dict should be a dict
8873
      nic_ip = nic_dict.get('ip', None)
8874
      if nic_ip is not None:
8875
        if nic_ip.lower() == constants.VALUE_NONE:
8876
          nic_dict['ip'] = None
8877
        else:
8878
          if not netutils.IPAddress.IsValid(nic_ip):
8879
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8880
                                       errors.ECODE_INVAL)
8881

    
8882
      nic_bridge = nic_dict.get('bridge', None)
8883
      nic_link = nic_dict.get('link', None)
8884
      if nic_bridge and nic_link:
8885
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8886
                                   " at the same time", errors.ECODE_INVAL)
8887
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8888
        nic_dict['bridge'] = None
8889
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8890
        nic_dict['link'] = None
8891

    
8892
      if nic_op == constants.DDM_ADD:
8893
        nic_mac = nic_dict.get('mac', None)
8894
        if nic_mac is None:
8895
          nic_dict['mac'] = constants.VALUE_AUTO
8896

    
8897
      if 'mac' in nic_dict:
8898
        nic_mac = nic_dict['mac']
8899
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8900
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8901

    
8902
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8903
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8904
                                     " modifying an existing nic",
8905
                                     errors.ECODE_INVAL)
8906

    
8907
    if nic_addremove > 1:
8908
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8909
                                 " supported at a time", errors.ECODE_INVAL)
8910

    
8911
  def ExpandNames(self):
8912
    self._ExpandAndLockInstance()
8913
    self.needed_locks[locking.LEVEL_NODE] = []
8914
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8915

    
8916
  def DeclareLocks(self, level):
8917
    if level == locking.LEVEL_NODE:
8918
      self._LockInstancesNodes()
8919
      if self.op.disk_template and self.op.remote_node:
8920
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8921
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8922

    
8923
  def BuildHooksEnv(self):
8924
    """Build hooks env.
8925

8926
    This runs on the master, primary and secondaries.
8927

8928
    """
8929
    args = dict()
8930
    if constants.BE_MEMORY in self.be_new:
8931
      args['memory'] = self.be_new[constants.BE_MEMORY]
8932
    if constants.BE_VCPUS in self.be_new:
8933
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8934
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8935
    # information at all.
8936
    if self.op.nics:
8937
      args['nics'] = []
8938
      nic_override = dict(self.op.nics)
8939
      for idx, nic in enumerate(self.instance.nics):
8940
        if idx in nic_override:
8941
          this_nic_override = nic_override[idx]
8942
        else:
8943
          this_nic_override = {}
8944
        if 'ip' in this_nic_override:
8945
          ip = this_nic_override['ip']
8946
        else:
8947
          ip = nic.ip
8948
        if 'mac' in this_nic_override:
8949
          mac = this_nic_override['mac']
8950
        else:
8951
          mac = nic.mac
8952
        if idx in self.nic_pnew:
8953
          nicparams = self.nic_pnew[idx]
8954
        else:
8955
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8956
        mode = nicparams[constants.NIC_MODE]
8957
        link = nicparams[constants.NIC_LINK]
8958
        args['nics'].append((ip, mac, mode, link))
8959
      if constants.DDM_ADD in nic_override:
8960
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8961
        mac = nic_override[constants.DDM_ADD]['mac']
8962
        nicparams = self.nic_pnew[constants.DDM_ADD]
8963
        mode = nicparams[constants.NIC_MODE]
8964
        link = nicparams[constants.NIC_LINK]
8965
        args['nics'].append((ip, mac, mode, link))
8966
      elif constants.DDM_REMOVE in nic_override:
8967
        del args['nics'][-1]
8968

    
8969
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8970
    if self.op.disk_template:
8971
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8972
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8973
    return env, nl, nl
8974

    
8975
  def CheckPrereq(self):
8976
    """Check prerequisites.
8977

8978
    This only checks the instance list against the existing names.
8979

8980
    """
8981
    # checking the new params on the primary/secondary nodes
8982

    
8983
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8984
    cluster = self.cluster = self.cfg.GetClusterInfo()
8985
    assert self.instance is not None, \
8986
      "Cannot retrieve locked instance %s" % self.op.instance_name
8987
    pnode = instance.primary_node
8988
    nodelist = list(instance.all_nodes)
8989

    
8990
    # OS change
8991
    if self.op.os_name and not self.op.force:
8992
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8993
                      self.op.force_variant)
8994
      instance_os = self.op.os_name
8995
    else:
8996
      instance_os = instance.os
8997

    
8998
    if self.op.disk_template:
8999
      if instance.disk_template == self.op.disk_template:
9000
        raise errors.OpPrereqError("Instance already has disk template %s" %
9001
                                   instance.disk_template, errors.ECODE_INVAL)
9002

    
9003
      if (instance.disk_template,
9004
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9005
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9006
                                   " %s to %s" % (instance.disk_template,
9007
                                                  self.op.disk_template),
9008
                                   errors.ECODE_INVAL)
9009
      _CheckInstanceDown(self, instance, "cannot change disk template")
9010
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9011
        if self.op.remote_node == pnode:
9012
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9013
                                     " as the primary node of the instance" %
9014
                                     self.op.remote_node, errors.ECODE_STATE)
9015
        _CheckNodeOnline(self, self.op.remote_node)
9016
        _CheckNodeNotDrained(self, self.op.remote_node)
9017
        # FIXME: here we assume that the old instance type is DT_PLAIN
9018
        assert instance.disk_template == constants.DT_PLAIN
9019
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9020
                 for d in instance.disks]
9021
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9022
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9023

    
9024
    # hvparams processing
9025
    if self.op.hvparams:
9026
      hv_type = instance.hypervisor
9027
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9028
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9029
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9030

    
9031
      # local check
9032
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9033
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9034
      self.hv_new = hv_new # the new actual values
9035
      self.hv_inst = i_hvdict # the new dict (without defaults)
9036
    else:
9037
      self.hv_new = self.hv_inst = {}
9038

    
9039
    # beparams processing
9040
    if self.op.beparams:
9041
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9042
                                   use_none=True)
9043
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9044
      be_new = cluster.SimpleFillBE(i_bedict)
9045
      self.be_new = be_new # the new actual values
9046
      self.be_inst = i_bedict # the new dict (without defaults)
9047
    else:
9048
      self.be_new = self.be_inst = {}
9049

    
9050
    # osparams processing
9051
    if self.op.osparams:
9052
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9053
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9054
      self.os_inst = i_osdict # the new dict (without defaults)
9055
    else:
9056
      self.os_inst = {}
9057

    
9058
    self.warn = []
9059

    
9060
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9061
      mem_check_list = [pnode]
9062
      if be_new[constants.BE_AUTO_BALANCE]:
9063
        # either we changed auto_balance to yes or it was from before
9064
        mem_check_list.extend(instance.secondary_nodes)
9065
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9066
                                                  instance.hypervisor)
9067
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9068
                                         instance.hypervisor)
9069
      pninfo = nodeinfo[pnode]
9070
      msg = pninfo.fail_msg
9071
      if msg:
9072
        # Assume the primary node is unreachable and go ahead
9073
        self.warn.append("Can't get info from primary node %s: %s" %
9074
                         (pnode,  msg))
9075
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9076
        self.warn.append("Node data from primary node %s doesn't contain"
9077
                         " free memory information" % pnode)
9078
      elif instance_info.fail_msg:
9079
        self.warn.append("Can't get instance runtime information: %s" %
9080
                        instance_info.fail_msg)
9081
      else:
9082
        if instance_info.payload:
9083
          current_mem = int(instance_info.payload['memory'])
9084
        else:
9085
          # Assume instance not running
9086
          # (there is a slight race condition here, but it's not very probable,
9087
          # and we have no other way to check)
9088
          current_mem = 0
9089
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9090
                    pninfo.payload['memory_free'])
9091
        if miss_mem > 0:
9092
          raise errors.OpPrereqError("This change will prevent the instance"
9093
                                     " from starting, due to %d MB of memory"
9094
                                     " missing on its primary node" % miss_mem,
9095
                                     errors.ECODE_NORES)
9096

    
9097
      if be_new[constants.BE_AUTO_BALANCE]:
9098
        for node, nres in nodeinfo.items():
9099
          if node not in instance.secondary_nodes:
9100
            continue
9101
          msg = nres.fail_msg
9102
          if msg:
9103
            self.warn.append("Can't get info from secondary node %s: %s" %
9104
                             (node, msg))
9105
          elif not isinstance(nres.payload.get('memory_free', None), int):
9106
            self.warn.append("Secondary node %s didn't return free"
9107
                             " memory information" % node)
9108
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9109
            self.warn.append("Not enough memory to failover instance to"
9110
                             " secondary node %s" % node)
9111

    
9112
    # NIC processing
9113
    self.nic_pnew = {}
9114
    self.nic_pinst = {}
9115
    for nic_op, nic_dict in self.op.nics:
9116
      if nic_op == constants.DDM_REMOVE:
9117
        if not instance.nics:
9118
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9119
                                     errors.ECODE_INVAL)
9120
        continue
9121
      if nic_op != constants.DDM_ADD:
9122
        # an existing nic
9123
        if not instance.nics:
9124
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9125
                                     " no NICs" % nic_op,
9126
                                     errors.ECODE_INVAL)
9127
        if nic_op < 0 or nic_op >= len(instance.nics):
9128
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9129
                                     " are 0 to %d" %
9130
                                     (nic_op, len(instance.nics) - 1),
9131
                                     errors.ECODE_INVAL)
9132
        old_nic_params = instance.nics[nic_op].nicparams
9133
        old_nic_ip = instance.nics[nic_op].ip
9134
      else:
9135
        old_nic_params = {}
9136
        old_nic_ip = None
9137

    
9138
      update_params_dict = dict([(key, nic_dict[key])
9139
                                 for key in constants.NICS_PARAMETERS
9140
                                 if key in nic_dict])
9141

    
9142
      if 'bridge' in nic_dict:
9143
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9144

    
9145
      new_nic_params = _GetUpdatedParams(old_nic_params,
9146
                                         update_params_dict)
9147
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9148
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9149
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9150
      self.nic_pinst[nic_op] = new_nic_params
9151
      self.nic_pnew[nic_op] = new_filled_nic_params
9152
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9153

    
9154
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9155
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9156
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9157
        if msg:
9158
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9159
          if self.op.force:
9160
            self.warn.append(msg)
9161
          else:
9162
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9163
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9164
        if 'ip' in nic_dict:
9165
          nic_ip = nic_dict['ip']
9166
        else:
9167
          nic_ip = old_nic_ip
9168
        if nic_ip is None:
9169
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9170
                                     ' on a routed nic', errors.ECODE_INVAL)
9171
      if 'mac' in nic_dict:
9172
        nic_mac = nic_dict['mac']
9173
        if nic_mac is None:
9174
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9175
                                     errors.ECODE_INVAL)
9176
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9177
          # otherwise generate the mac
9178
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9179
        else:
9180
          # or validate/reserve the current one
9181
          try:
9182
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9183
          except errors.ReservationError:
9184
            raise errors.OpPrereqError("MAC address %s already in use"
9185
                                       " in cluster" % nic_mac,
9186
                                       errors.ECODE_NOTUNIQUE)
9187

    
9188
    # DISK processing
9189
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9190
      raise errors.OpPrereqError("Disk operations not supported for"
9191
                                 " diskless instances",
9192
                                 errors.ECODE_INVAL)
9193
    for disk_op, _ in self.op.disks:
9194
      if disk_op == constants.DDM_REMOVE:
9195
        if len(instance.disks) == 1:
9196
          raise errors.OpPrereqError("Cannot remove the last disk of"
9197
                                     " an instance", errors.ECODE_INVAL)
9198
        _CheckInstanceDown(self, instance, "cannot remove disks")
9199

    
9200
      if (disk_op == constants.DDM_ADD and
9201
          len(instance.nics) >= constants.MAX_DISKS):
9202
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9203
                                   " add more" % constants.MAX_DISKS,
9204
                                   errors.ECODE_STATE)
9205
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9206
        # an existing disk
9207
        if disk_op < 0 or disk_op >= len(instance.disks):
9208
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9209
                                     " are 0 to %d" %
9210
                                     (disk_op, len(instance.disks)),
9211
                                     errors.ECODE_INVAL)
9212

    
9213
    return
9214

    
9215
  def _ConvertPlainToDrbd(self, feedback_fn):
9216
    """Converts an instance from plain to drbd.
9217

9218
    """
9219
    feedback_fn("Converting template to drbd")
9220
    instance = self.instance
9221
    pnode = instance.primary_node
9222
    snode = self.op.remote_node
9223

    
9224
    # create a fake disk info for _GenerateDiskTemplate
9225
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9226
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9227
                                      instance.name, pnode, [snode],
9228
                                      disk_info, None, None, 0, feedback_fn)
9229
    info = _GetInstanceInfoText(instance)
9230
    feedback_fn("Creating aditional volumes...")
9231
    # first, create the missing data and meta devices
9232
    for disk in new_disks:
9233
      # unfortunately this is... not too nice
9234
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9235
                            info, True)
9236
      for child in disk.children:
9237
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9238
    # at this stage, all new LVs have been created, we can rename the
9239
    # old ones
9240
    feedback_fn("Renaming original volumes...")
9241
    rename_list = [(o, n.children[0].logical_id)
9242
                   for (o, n) in zip(instance.disks, new_disks)]
9243
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9244
    result.Raise("Failed to rename original LVs")
9245

    
9246
    feedback_fn("Initializing DRBD devices...")
9247
    # all child devices are in place, we can now create the DRBD devices
9248
    for disk in new_disks:
9249
      for node in [pnode, snode]:
9250
        f_create = node == pnode
9251
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9252

    
9253
    # at this point, the instance has been modified
9254
    instance.disk_template = constants.DT_DRBD8
9255
    instance.disks = new_disks
9256
    self.cfg.Update(instance, feedback_fn)
9257

    
9258
    # disks are created, waiting for sync
9259
    disk_abort = not _WaitForSync(self, instance)
9260
    if disk_abort:
9261
      raise errors.OpExecError("There are some degraded disks for"
9262
                               " this instance, please cleanup manually")
9263

    
9264
  def _ConvertDrbdToPlain(self, feedback_fn):
9265
    """Converts an instance from drbd to plain.
9266

9267
    """
9268
    instance = self.instance
9269
    assert len(instance.secondary_nodes) == 1
9270
    pnode = instance.primary_node
9271
    snode = instance.secondary_nodes[0]
9272
    feedback_fn("Converting template to plain")
9273

    
9274
    old_disks = instance.disks
9275
    new_disks = [d.children[0] for d in old_disks]
9276

    
9277
    # copy over size and mode
9278
    for parent, child in zip(old_disks, new_disks):
9279
      child.size = parent.size
9280
      child.mode = parent.mode
9281

    
9282
    # update instance structure
9283
    instance.disks = new_disks
9284
    instance.disk_template = constants.DT_PLAIN
9285
    self.cfg.Update(instance, feedback_fn)
9286

    
9287
    feedback_fn("Removing volumes on the secondary node...")
9288
    for disk in old_disks:
9289
      self.cfg.SetDiskID(disk, snode)
9290
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9291
      if msg:
9292
        self.LogWarning("Could not remove block device %s on node %s,"
9293
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9294

    
9295
    feedback_fn("Removing unneeded volumes on the primary node...")
9296
    for idx, disk in enumerate(old_disks):
9297
      meta = disk.children[1]
9298
      self.cfg.SetDiskID(meta, pnode)
9299
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9300
      if msg:
9301
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9302
                        " continuing anyway: %s", idx, pnode, msg)
9303

    
9304
  def Exec(self, feedback_fn):
9305
    """Modifies an instance.
9306

9307
    All parameters take effect only at the next restart of the instance.
9308

9309
    """
9310
    # Process here the warnings from CheckPrereq, as we don't have a
9311
    # feedback_fn there.
9312
    for warn in self.warn:
9313
      feedback_fn("WARNING: %s" % warn)
9314

    
9315
    result = []
9316
    instance = self.instance
9317
    # disk changes
9318
    for disk_op, disk_dict in self.op.disks:
9319
      if disk_op == constants.DDM_REMOVE:
9320
        # remove the last disk
9321
        device = instance.disks.pop()
9322
        device_idx = len(instance.disks)
9323
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9324
          self.cfg.SetDiskID(disk, node)
9325
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9326
          if msg:
9327
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9328
                            " continuing anyway", device_idx, node, msg)
9329
        result.append(("disk/%d" % device_idx, "remove"))
9330
      elif disk_op == constants.DDM_ADD:
9331
        # add a new disk
9332
        if instance.disk_template == constants.DT_FILE:
9333
          file_driver, file_path = instance.disks[0].logical_id
9334
          file_path = os.path.dirname(file_path)
9335
        else:
9336
          file_driver = file_path = None
9337
        disk_idx_base = len(instance.disks)
9338
        new_disk = _GenerateDiskTemplate(self,
9339
                                         instance.disk_template,
9340
                                         instance.name, instance.primary_node,
9341
                                         instance.secondary_nodes,
9342
                                         [disk_dict],
9343
                                         file_path,
9344
                                         file_driver,
9345
                                         disk_idx_base, feedback_fn)[0]
9346
        instance.disks.append(new_disk)
9347
        info = _GetInstanceInfoText(instance)
9348

    
9349
        logging.info("Creating volume %s for instance %s",
9350
                     new_disk.iv_name, instance.name)
9351
        # Note: this needs to be kept in sync with _CreateDisks
9352
        #HARDCODE
9353
        for node in instance.all_nodes:
9354
          f_create = node == instance.primary_node
9355
          try:
9356
            _CreateBlockDev(self, node, instance, new_disk,
9357
                            f_create, info, f_create)
9358
          except errors.OpExecError, err:
9359
            self.LogWarning("Failed to create volume %s (%s) on"
9360
                            " node %s: %s",
9361
                            new_disk.iv_name, new_disk, node, err)
9362
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9363
                       (new_disk.size, new_disk.mode)))
9364
      else:
9365
        # change a given disk
9366
        instance.disks[disk_op].mode = disk_dict['mode']
9367
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9368

    
9369
    if self.op.disk_template:
9370
      r_shut = _ShutdownInstanceDisks(self, instance)
9371
      if not r_shut:
9372
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
9373
                                 " proceed with disk template conversion")
9374
      mode = (instance.disk_template, self.op.disk_template)
9375
      try:
9376
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9377
      except:
9378
        self.cfg.ReleaseDRBDMinors(instance.name)
9379
        raise
9380
      result.append(("disk_template", self.op.disk_template))
9381

    
9382
    # NIC changes
9383
    for nic_op, nic_dict in self.op.nics:
9384
      if nic_op == constants.DDM_REMOVE:
9385
        # remove the last nic
9386
        del instance.nics[-1]
9387
        result.append(("nic.%d" % len(instance.nics), "remove"))
9388
      elif nic_op == constants.DDM_ADD:
9389
        # mac and bridge should be set, by now
9390
        mac = nic_dict['mac']
9391
        ip = nic_dict.get('ip', None)
9392
        nicparams = self.nic_pinst[constants.DDM_ADD]
9393
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9394
        instance.nics.append(new_nic)
9395
        result.append(("nic.%d" % (len(instance.nics) - 1),
9396
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9397
                       (new_nic.mac, new_nic.ip,
9398
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9399
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9400
                       )))
9401
      else:
9402
        for key in 'mac', 'ip':
9403
          if key in nic_dict:
9404
            setattr(instance.nics[nic_op], key, nic_dict[key])
9405
        if nic_op in self.nic_pinst:
9406
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9407
        for key, val in nic_dict.iteritems():
9408
          result.append(("nic.%s/%d" % (key, nic_op), val))
9409

    
9410
    # hvparams changes
9411
    if self.op.hvparams:
9412
      instance.hvparams = self.hv_inst
9413
      for key, val in self.op.hvparams.iteritems():
9414
        result.append(("hv/%s" % key, val))
9415

    
9416
    # beparams changes
9417
    if self.op.beparams:
9418
      instance.beparams = self.be_inst
9419
      for key, val in self.op.beparams.iteritems():
9420
        result.append(("be/%s" % key, val))
9421

    
9422
    # OS change
9423
    if self.op.os_name:
9424
      instance.os = self.op.os_name
9425

    
9426
    # osparams changes
9427
    if self.op.osparams:
9428
      instance.osparams = self.os_inst
9429
      for key, val in self.op.osparams.iteritems():
9430
        result.append(("os/%s" % key, val))
9431

    
9432
    self.cfg.Update(instance, feedback_fn)
9433

    
9434
    return result
9435

    
9436
  _DISK_CONVERSIONS = {
9437
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9438
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9439
    }
9440

    
9441

    
9442
class LUQueryExports(NoHooksLU):
9443
  """Query the exports list
9444

9445
  """
9446
  REQ_BGL = False
9447

    
9448
  def ExpandNames(self):
9449
    self.needed_locks = {}
9450
    self.share_locks[locking.LEVEL_NODE] = 1
9451
    if not self.op.nodes:
9452
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9453
    else:
9454
      self.needed_locks[locking.LEVEL_NODE] = \
9455
        _GetWantedNodes(self, self.op.nodes)
9456

    
9457
  def Exec(self, feedback_fn):
9458
    """Compute the list of all the exported system images.
9459

9460
    @rtype: dict
9461
    @return: a dictionary with the structure node->(export-list)
9462
        where export-list is a list of the instances exported on
9463
        that node.
9464

9465
    """
9466
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9467
    rpcresult = self.rpc.call_export_list(self.nodes)
9468
    result = {}
9469
    for node in rpcresult:
9470
      if rpcresult[node].fail_msg:
9471
        result[node] = False
9472
      else:
9473
        result[node] = rpcresult[node].payload
9474

    
9475
    return result
9476

    
9477

    
9478
class LUPrepareExport(NoHooksLU):
9479
  """Prepares an instance for an export and returns useful information.
9480

9481
  """
9482
  REQ_BGL = False
9483

    
9484
  def ExpandNames(self):
9485
    self._ExpandAndLockInstance()
9486

    
9487
  def CheckPrereq(self):
9488
    """Check prerequisites.
9489

9490
    """
9491
    instance_name = self.op.instance_name
9492

    
9493
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9494
    assert self.instance is not None, \
9495
          "Cannot retrieve locked instance %s" % self.op.instance_name
9496
    _CheckNodeOnline(self, self.instance.primary_node)
9497

    
9498
    self._cds = _GetClusterDomainSecret()
9499

    
9500
  def Exec(self, feedback_fn):
9501
    """Prepares an instance for an export.
9502

9503
    """
9504
    instance = self.instance
9505

    
9506
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9507
      salt = utils.GenerateSecret(8)
9508

    
9509
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9510
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9511
                                              constants.RIE_CERT_VALIDITY)
9512
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9513

    
9514
      (name, cert_pem) = result.payload
9515

    
9516
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9517
                                             cert_pem)
9518

    
9519
      return {
9520
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9521
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9522
                          salt),
9523
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9524
        }
9525

    
9526
    return None
9527

    
9528

    
9529
class LUExportInstance(LogicalUnit):
9530
  """Export an instance to an image in the cluster.
9531

9532
  """
9533
  HPATH = "instance-export"
9534
  HTYPE = constants.HTYPE_INSTANCE
9535
  REQ_BGL = False
9536

    
9537
  def CheckArguments(self):
9538
    """Check the arguments.
9539

9540
    """
9541
    self.x509_key_name = self.op.x509_key_name
9542
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9543

    
9544
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9545
      if not self.x509_key_name:
9546
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9547
                                   errors.ECODE_INVAL)
9548

    
9549
      if not self.dest_x509_ca_pem:
9550
        raise errors.OpPrereqError("Missing destination X509 CA",
9551
                                   errors.ECODE_INVAL)
9552

    
9553
  def ExpandNames(self):
9554
    self._ExpandAndLockInstance()
9555

    
9556
    # Lock all nodes for local exports
9557
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9558
      # FIXME: lock only instance primary and destination node
9559
      #
9560
      # Sad but true, for now we have do lock all nodes, as we don't know where
9561
      # the previous export might be, and in this LU we search for it and
9562
      # remove it from its current node. In the future we could fix this by:
9563
      #  - making a tasklet to search (share-lock all), then create the
9564
      #    new one, then one to remove, after
9565
      #  - removing the removal operation altogether
9566
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9567

    
9568
  def DeclareLocks(self, level):
9569
    """Last minute lock declaration."""
9570
    # All nodes are locked anyway, so nothing to do here.
9571

    
9572
  def BuildHooksEnv(self):
9573
    """Build hooks env.
9574

9575
    This will run on the master, primary node and target node.
9576

9577
    """
9578
    env = {
9579
      "EXPORT_MODE": self.op.mode,
9580
      "EXPORT_NODE": self.op.target_node,
9581
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9582
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9583
      # TODO: Generic function for boolean env variables
9584
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9585
      }
9586

    
9587
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9588

    
9589
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9590

    
9591
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9592
      nl.append(self.op.target_node)
9593

    
9594
    return env, nl, nl
9595

    
9596
  def CheckPrereq(self):
9597
    """Check prerequisites.
9598

9599
    This checks that the instance and node names are valid.
9600

9601
    """
9602
    instance_name = self.op.instance_name
9603

    
9604
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9605
    assert self.instance is not None, \
9606
          "Cannot retrieve locked instance %s" % self.op.instance_name
9607
    _CheckNodeOnline(self, self.instance.primary_node)
9608

    
9609
    if (self.op.remove_instance and self.instance.admin_up and
9610
        not self.op.shutdown):
9611
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9612
                                 " down before")
9613

    
9614
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9615
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9616
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9617
      assert self.dst_node is not None
9618

    
9619
      _CheckNodeOnline(self, self.dst_node.name)
9620
      _CheckNodeNotDrained(self, self.dst_node.name)
9621

    
9622
      self._cds = None
9623
      self.dest_disk_info = None
9624
      self.dest_x509_ca = None
9625

    
9626
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9627
      self.dst_node = None
9628

    
9629
      if len(self.op.target_node) != len(self.instance.disks):
9630
        raise errors.OpPrereqError(("Received destination information for %s"
9631
                                    " disks, but instance %s has %s disks") %
9632
                                   (len(self.op.target_node), instance_name,
9633
                                    len(self.instance.disks)),
9634
                                   errors.ECODE_INVAL)
9635

    
9636
      cds = _GetClusterDomainSecret()
9637

    
9638
      # Check X509 key name
9639
      try:
9640
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9641
      except (TypeError, ValueError), err:
9642
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9643

    
9644
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9645
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9646
                                   errors.ECODE_INVAL)
9647

    
9648
      # Load and verify CA
9649
      try:
9650
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9651
      except OpenSSL.crypto.Error, err:
9652
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9653
                                   (err, ), errors.ECODE_INVAL)
9654

    
9655
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9656
      if errcode is not None:
9657
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9658
                                   (msg, ), errors.ECODE_INVAL)
9659

    
9660
      self.dest_x509_ca = cert
9661

    
9662
      # Verify target information
9663
      disk_info = []
9664
      for idx, disk_data in enumerate(self.op.target_node):
9665
        try:
9666
          (host, port, magic) = \
9667
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9668
        except errors.GenericError, err:
9669
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9670
                                     (idx, err), errors.ECODE_INVAL)
9671

    
9672
        disk_info.append((host, port, magic))
9673

    
9674
      assert len(disk_info) == len(self.op.target_node)
9675
      self.dest_disk_info = disk_info
9676

    
9677
    else:
9678
      raise errors.ProgrammerError("Unhandled export mode %r" %
9679
                                   self.op.mode)
9680

    
9681
    # instance disk type verification
9682
    # TODO: Implement export support for file-based disks
9683
    for disk in self.instance.disks:
9684
      if disk.dev_type == constants.LD_FILE:
9685
        raise errors.OpPrereqError("Export not supported for instances with"
9686
                                   " file-based disks", errors.ECODE_INVAL)
9687

    
9688
  def _CleanupExports(self, feedback_fn):
9689
    """Removes exports of current instance from all other nodes.
9690

9691
    If an instance in a cluster with nodes A..D was exported to node C, its
9692
    exports will be removed from the nodes A, B and D.
9693

9694
    """
9695
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9696

    
9697
    nodelist = self.cfg.GetNodeList()
9698
    nodelist.remove(self.dst_node.name)
9699

    
9700
    # on one-node clusters nodelist will be empty after the removal
9701
    # if we proceed the backup would be removed because OpQueryExports
9702
    # substitutes an empty list with the full cluster node list.
9703
    iname = self.instance.name
9704
    if nodelist:
9705
      feedback_fn("Removing old exports for instance %s" % iname)
9706
      exportlist = self.rpc.call_export_list(nodelist)
9707
      for node in exportlist:
9708
        if exportlist[node].fail_msg:
9709
          continue
9710
        if iname in exportlist[node].payload:
9711
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9712
          if msg:
9713
            self.LogWarning("Could not remove older export for instance %s"
9714
                            " on node %s: %s", iname, node, msg)
9715

    
9716
  def Exec(self, feedback_fn):
9717
    """Export an instance to an image in the cluster.
9718

9719
    """
9720
    assert self.op.mode in constants.EXPORT_MODES
9721

    
9722
    instance = self.instance
9723
    src_node = instance.primary_node
9724

    
9725
    if self.op.shutdown:
9726
      # shutdown the instance, but not the disks
9727
      feedback_fn("Shutting down instance %s" % instance.name)
9728
      result = self.rpc.call_instance_shutdown(src_node, instance,
9729
                                               self.op.shutdown_timeout)
9730
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9731
      result.Raise("Could not shutdown instance %s on"
9732
                   " node %s" % (instance.name, src_node))
9733

    
9734
    # set the disks ID correctly since call_instance_start needs the
9735
    # correct drbd minor to create the symlinks
9736
    for disk in instance.disks:
9737
      self.cfg.SetDiskID(disk, src_node)
9738

    
9739
    activate_disks = (not instance.admin_up)
9740

    
9741
    if activate_disks:
9742
      # Activate the instance disks if we'exporting a stopped instance
9743
      feedback_fn("Activating disks for %s" % instance.name)
9744
      _StartInstanceDisks(self, instance, None)
9745

    
9746
    try:
9747
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9748
                                                     instance)
9749

    
9750
      helper.CreateSnapshots()
9751
      try:
9752
        if (self.op.shutdown and instance.admin_up and
9753
            not self.op.remove_instance):
9754
          assert not activate_disks
9755
          feedback_fn("Starting instance %s" % instance.name)
9756
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9757
          msg = result.fail_msg
9758
          if msg:
9759
            feedback_fn("Failed to start instance: %s" % msg)
9760
            _ShutdownInstanceDisks(self, instance)
9761
            raise errors.OpExecError("Could not start instance: %s" % msg)
9762

    
9763
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9764
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9765
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9766
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9767
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9768

    
9769
          (key_name, _, _) = self.x509_key_name
9770

    
9771
          dest_ca_pem = \
9772
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9773
                                            self.dest_x509_ca)
9774

    
9775
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9776
                                                     key_name, dest_ca_pem,
9777
                                                     timeouts)
9778
      finally:
9779
        helper.Cleanup()
9780

    
9781
      # Check for backwards compatibility
9782
      assert len(dresults) == len(instance.disks)
9783
      assert compat.all(isinstance(i, bool) for i in dresults), \
9784
             "Not all results are boolean: %r" % dresults
9785

    
9786
    finally:
9787
      if activate_disks:
9788
        feedback_fn("Deactivating disks for %s" % instance.name)
9789
        _ShutdownInstanceDisks(self, instance)
9790

    
9791
    if not (compat.all(dresults) and fin_resu):
9792
      failures = []
9793
      if not fin_resu:
9794
        failures.append("export finalization")
9795
      if not compat.all(dresults):
9796
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9797
                               if not dsk)
9798
        failures.append("disk export: disk(s) %s" % fdsk)
9799

    
9800
      raise errors.OpExecError("Export failed, errors in %s" %
9801
                               utils.CommaJoin(failures))
9802

    
9803
    # At this point, the export was successful, we can cleanup/finish
9804

    
9805
    # Remove instance if requested
9806
    if self.op.remove_instance:
9807
      feedback_fn("Removing instance %s" % instance.name)
9808
      _RemoveInstance(self, feedback_fn, instance,
9809
                      self.op.ignore_remove_failures)
9810

    
9811
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9812
      self._CleanupExports(feedback_fn)
9813

    
9814
    return fin_resu, dresults
9815

    
9816

    
9817
class LURemoveExport(NoHooksLU):
9818
  """Remove exports related to the named instance.
9819

9820
  """
9821
  REQ_BGL = False
9822

    
9823
  def ExpandNames(self):
9824
    self.needed_locks = {}
9825
    # We need all nodes to be locked in order for RemoveExport to work, but we
9826
    # don't need to lock the instance itself, as nothing will happen to it (and
9827
    # we can remove exports also for a removed instance)
9828
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9829

    
9830
  def Exec(self, feedback_fn):
9831
    """Remove any export.
9832

9833
    """
9834
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9835
    # If the instance was not found we'll try with the name that was passed in.
9836
    # This will only work if it was an FQDN, though.
9837
    fqdn_warn = False
9838
    if not instance_name:
9839
      fqdn_warn = True
9840
      instance_name = self.op.instance_name
9841

    
9842
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9843
    exportlist = self.rpc.call_export_list(locked_nodes)
9844
    found = False
9845
    for node in exportlist:
9846
      msg = exportlist[node].fail_msg
9847
      if msg:
9848
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9849
        continue
9850
      if instance_name in exportlist[node].payload:
9851
        found = True
9852
        result = self.rpc.call_export_remove(node, instance_name)
9853
        msg = result.fail_msg
9854
        if msg:
9855
          logging.error("Could not remove export for instance %s"
9856
                        " on node %s: %s", instance_name, node, msg)
9857

    
9858
    if fqdn_warn and not found:
9859
      feedback_fn("Export not found. If trying to remove an export belonging"
9860
                  " to a deleted instance please use its Fully Qualified"
9861
                  " Domain Name.")
9862

    
9863

    
9864
class LUAddGroup(LogicalUnit):
9865
  """Logical unit for creating node groups.
9866

9867
  """
9868
  HPATH = "group-add"
9869
  HTYPE = constants.HTYPE_GROUP
9870
  REQ_BGL = False
9871

    
9872
  def ExpandNames(self):
9873
    # We need the new group's UUID here so that we can create and acquire the
9874
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
9875
    # that it should not check whether the UUID exists in the configuration.
9876
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
9877
    self.needed_locks = {}
9878
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
9879

    
9880
  def CheckPrereq(self):
9881
    """Check prerequisites.
9882

9883
    This checks that the given group name is not an existing node group
9884
    already.
9885

9886
    """
9887
    try:
9888
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
9889
    except errors.OpPrereqError:
9890
      pass
9891
    else:
9892
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
9893
                                 " node group (UUID: %s)" %
9894
                                 (self.op.group_name, existing_uuid),
9895
                                 errors.ECODE_EXISTS)
9896

    
9897
    if self.op.ndparams:
9898
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
9899

    
9900
  def BuildHooksEnv(self):
9901
    """Build hooks env.
9902

9903
    """
9904
    env = {
9905
      "GROUP_NAME": self.op.group_name,
9906
      }
9907
    mn = self.cfg.GetMasterNode()
9908
    return env, [mn], [mn]
9909

    
9910
  def Exec(self, feedback_fn):
9911
    """Add the node group to the cluster.
9912

9913
    """
9914
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
9915
                                  uuid=self.group_uuid,
9916
                                  alloc_policy=self.op.alloc_policy,
9917
                                  ndparams=self.op.ndparams)
9918

    
9919
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
9920
    del self.remove_locks[locking.LEVEL_NODEGROUP]
9921

    
9922

    
9923
class _GroupQuery(_QueryBase):
9924

    
9925
  FIELDS = query.GROUP_FIELDS
9926

    
9927
  def ExpandNames(self, lu):
9928
    lu.needed_locks = {}
9929

    
9930
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
9931
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
9932

    
9933
    if not self.names:
9934
      self.wanted = [name_to_uuid[name]
9935
                     for name in utils.NiceSort(name_to_uuid.keys())]
9936
    else:
9937
      # Accept names to be either names or UUIDs.
9938
      missing = []
9939
      self.wanted = []
9940
      all_uuid = frozenset(self._all_groups.keys())
9941

    
9942
      for name in self.names:
9943
        if name in all_uuid:
9944
          self.wanted.append(name)
9945
        elif name in name_to_uuid:
9946
          self.wanted.append(name_to_uuid[name])
9947
        else:
9948
          missing.append(name)
9949

    
9950
      if missing:
9951
        raise errors.OpPrereqError("Some groups do not exist: %s" % missing,
9952
                                   errors.ECODE_NOENT)
9953

    
9954
  def DeclareLocks(self, lu, level):
9955
    pass
9956

    
9957
  def _GetQueryData(self, lu):
9958
    """Computes the list of node groups and their attributes.
9959

9960
    """
9961
    do_nodes = query.GQ_NODE in self.requested_data
9962
    do_instances = query.GQ_INST in self.requested_data
9963

    
9964
    group_to_nodes = None
9965
    group_to_instances = None
9966

    
9967
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
9968
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
9969
    # latter GetAllInstancesInfo() is not enough, for we have to go through
9970
    # instance->node. Hence, we will need to process nodes even if we only need
9971
    # instance information.
9972
    if do_nodes or do_instances:
9973
      all_nodes = lu.cfg.GetAllNodesInfo()
9974
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
9975
      node_to_group = {}
9976

    
9977
      for node in all_nodes.values():
9978
        if node.group in group_to_nodes:
9979
          group_to_nodes[node.group].append(node.name)
9980
          node_to_group[node.name] = node.group
9981

    
9982
      if do_instances:
9983
        all_instances = lu.cfg.GetAllInstancesInfo()
9984
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
9985

    
9986
        for instance in all_instances.values():
9987
          node = instance.primary_node
9988
          if node in node_to_group:
9989
            group_to_instances[node_to_group[node]].append(instance.name)
9990

    
9991
        if not do_nodes:
9992
          # Do not pass on node information if it was not requested.
9993
          group_to_nodes = None
9994

    
9995
    return query.GroupQueryData([self._all_groups[uuid]
9996
                                 for uuid in self.wanted],
9997
                                group_to_nodes, group_to_instances)
9998

    
9999

    
10000
class LUQueryGroups(NoHooksLU):
10001
  """Logical unit for querying node groups.
10002

10003
  """
10004
  REQ_BGL = False
10005

    
10006
  def CheckArguments(self):
10007
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10008

    
10009
  def ExpandNames(self):
10010
    self.gq.ExpandNames(self)
10011

    
10012
  def Exec(self, feedback_fn):
10013
    return self.gq.OldStyleQuery(self)
10014

    
10015

    
10016
class LUSetGroupParams(LogicalUnit):
10017
  """Modifies the parameters of a node group.
10018

10019
  """
10020
  HPATH = "group-modify"
10021
  HTYPE = constants.HTYPE_GROUP
10022
  REQ_BGL = False
10023

    
10024
  def CheckArguments(self):
10025
    all_changes = [
10026
      self.op.ndparams,
10027
      self.op.alloc_policy,
10028
      ]
10029

    
10030
    if all_changes.count(None) == len(all_changes):
10031
      raise errors.OpPrereqError("Please pass at least one modification",
10032
                                 errors.ECODE_INVAL)
10033

    
10034
  def ExpandNames(self):
10035
    # This raises errors.OpPrereqError on its own:
10036
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10037

    
10038
    self.needed_locks = {
10039
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10040
      }
10041

    
10042
  def CheckPrereq(self):
10043
    """Check prerequisites.
10044

10045
    """
10046
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10047

    
10048
    if self.group is None:
10049
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10050
                               (self.op.group_name, self.group_uuid))
10051

    
10052
    if self.op.ndparams:
10053
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10054
      self.new_ndparams = self.group.SimpleFillND(self.op.ndparams)
10055

    
10056
  def BuildHooksEnv(self):
10057
    """Build hooks env.
10058

10059
    """
10060
    env = {
10061
      "GROUP_NAME": self.op.group_name,
10062
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10063
      }
10064
    mn = self.cfg.GetMasterNode()
10065
    return env, [mn], [mn]
10066

    
10067
  def Exec(self, feedback_fn):
10068
    """Modifies the node group.
10069

10070
    """
10071
    result = []
10072

    
10073
    if self.op.ndparams:
10074
      self.group.ndparams = self.new_ndparams
10075
      result.append(("ndparams", str(self.group.ndparams)))
10076

    
10077
    if self.op.alloc_policy:
10078
      self.group.alloc_policy = self.op.alloc_policy
10079

    
10080
    self.cfg.Update(self.group, feedback_fn)
10081
    return result
10082

    
10083

    
10084

    
10085
class LURemoveGroup(LogicalUnit):
10086
  HPATH = "group-remove"
10087
  HTYPE = constants.HTYPE_GROUP
10088
  REQ_BGL = False
10089

    
10090
  def ExpandNames(self):
10091
    # This will raises errors.OpPrereqError on its own:
10092
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10093
    self.needed_locks = {
10094
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10095
      }
10096

    
10097
  def CheckPrereq(self):
10098
    """Check prerequisites.
10099

10100
    This checks that the given group name exists as a node group, that is
10101
    empty (i.e., contains no nodes), and that is not the last group of the
10102
    cluster.
10103

10104
    """
10105
    # Verify that the group is empty.
10106
    group_nodes = [node.name
10107
                   for node in self.cfg.GetAllNodesInfo().values()
10108
                   if node.group == self.group_uuid]
10109

    
10110
    if group_nodes:
10111
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10112
                                 " nodes: %s" %
10113
                                 (self.op.group_name,
10114
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10115
                                 errors.ECODE_STATE)
10116

    
10117
    # Verify the cluster would not be left group-less.
10118
    if len(self.cfg.GetNodeGroupList()) == 1:
10119
      raise errors.OpPrereqError("Group '%s' is the last group in the cluster,"
10120
                                 " which cannot be left without at least one"
10121
                                 " group" % self.op.group_name,
10122
                                 errors.ECODE_STATE)
10123

    
10124
  def BuildHooksEnv(self):
10125
    """Build hooks env.
10126

10127
    """
10128
    env = {
10129
      "GROUP_NAME": self.op.group_name,
10130
      }
10131
    mn = self.cfg.GetMasterNode()
10132
    return env, [mn], [mn]
10133

    
10134
  def Exec(self, feedback_fn):
10135
    """Remove the node group.
10136

10137
    """
10138
    try:
10139
      self.cfg.RemoveNodeGroup(self.group_uuid)
10140
    except errors.ConfigurationError:
10141
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10142
                               (self.op.group_name, self.group_uuid))
10143

    
10144
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10145

    
10146

    
10147
class LURenameGroup(LogicalUnit):
10148
  HPATH = "group-rename"
10149
  HTYPE = constants.HTYPE_GROUP
10150
  REQ_BGL = False
10151

    
10152
  def ExpandNames(self):
10153
    # This raises errors.OpPrereqError on its own:
10154
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10155

    
10156
    self.needed_locks = {
10157
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10158
      }
10159

    
10160
  def CheckPrereq(self):
10161
    """Check prerequisites.
10162

10163
    This checks that the given old_name exists as a node group, and that
10164
    new_name doesn't.
10165

10166
    """
10167
    try:
10168
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
10169
    except errors.OpPrereqError:
10170
      pass
10171
    else:
10172
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
10173
                                 " node group (UUID: %s)" %
10174
                                 (self.op.new_name, new_name_uuid),
10175
                                 errors.ECODE_EXISTS)
10176

    
10177
  def BuildHooksEnv(self):
10178
    """Build hooks env.
10179

10180
    """
10181
    env = {
10182
      "OLD_NAME": self.op.old_name,
10183
      "NEW_NAME": self.op.new_name,
10184
      }
10185

    
10186
    mn = self.cfg.GetMasterNode()
10187
    all_nodes = self.cfg.GetAllNodesInfo()
10188
    run_nodes = [mn]
10189
    all_nodes.pop(mn, None)
10190

    
10191
    for node in all_nodes.values():
10192
      if node.group == self.group_uuid:
10193
        run_nodes.append(node.name)
10194

    
10195
    return env, run_nodes, run_nodes
10196

    
10197
  def Exec(self, feedback_fn):
10198
    """Rename the node group.
10199

10200
    """
10201
    group = self.cfg.GetNodeGroup(self.group_uuid)
10202

    
10203
    if group is None:
10204
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10205
                               (self.op.old_name, self.group_uuid))
10206

    
10207
    group.name = self.op.new_name
10208
    self.cfg.Update(group, feedback_fn)
10209

    
10210
    return self.op.new_name
10211

    
10212

    
10213
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10214
  """Generic tags LU.
10215

10216
  This is an abstract class which is the parent of all the other tags LUs.
10217

10218
  """
10219

    
10220
  def ExpandNames(self):
10221
    self.needed_locks = {}
10222
    if self.op.kind == constants.TAG_NODE:
10223
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10224
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10225
    elif self.op.kind == constants.TAG_INSTANCE:
10226
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10227
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10228

    
10229
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10230
    # not possible to acquire the BGL based on opcode parameters)
10231

    
10232
  def CheckPrereq(self):
10233
    """Check prerequisites.
10234

10235
    """
10236
    if self.op.kind == constants.TAG_CLUSTER:
10237
      self.target = self.cfg.GetClusterInfo()
10238
    elif self.op.kind == constants.TAG_NODE:
10239
      self.target = self.cfg.GetNodeInfo(self.op.name)
10240
    elif self.op.kind == constants.TAG_INSTANCE:
10241
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10242
    else:
10243
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10244
                                 str(self.op.kind), errors.ECODE_INVAL)
10245

    
10246

    
10247
class LUGetTags(TagsLU):
10248
  """Returns the tags of a given object.
10249

10250
  """
10251
  REQ_BGL = False
10252

    
10253
  def ExpandNames(self):
10254
    TagsLU.ExpandNames(self)
10255

    
10256
    # Share locks as this is only a read operation
10257
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10258

    
10259
  def Exec(self, feedback_fn):
10260
    """Returns the tag list.
10261

10262
    """
10263
    return list(self.target.GetTags())
10264

    
10265

    
10266
class LUSearchTags(NoHooksLU):
10267
  """Searches the tags for a given pattern.
10268

10269
  """
10270
  REQ_BGL = False
10271

    
10272
  def ExpandNames(self):
10273
    self.needed_locks = {}
10274

    
10275
  def CheckPrereq(self):
10276
    """Check prerequisites.
10277

10278
    This checks the pattern passed for validity by compiling it.
10279

10280
    """
10281
    try:
10282
      self.re = re.compile(self.op.pattern)
10283
    except re.error, err:
10284
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10285
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10286

    
10287
  def Exec(self, feedback_fn):
10288
    """Returns the tag list.
10289

10290
    """
10291
    cfg = self.cfg
10292
    tgts = [("/cluster", cfg.GetClusterInfo())]
10293
    ilist = cfg.GetAllInstancesInfo().values()
10294
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10295
    nlist = cfg.GetAllNodesInfo().values()
10296
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10297
    results = []
10298
    for path, target in tgts:
10299
      for tag in target.GetTags():
10300
        if self.re.search(tag):
10301
          results.append((path, tag))
10302
    return results
10303

    
10304

    
10305
class LUAddTags(TagsLU):
10306
  """Sets a tag on a given object.
10307

10308
  """
10309
  REQ_BGL = False
10310

    
10311
  def CheckPrereq(self):
10312
    """Check prerequisites.
10313

10314
    This checks the type and length of the tag name and value.
10315

10316
    """
10317
    TagsLU.CheckPrereq(self)
10318
    for tag in self.op.tags:
10319
      objects.TaggableObject.ValidateTag(tag)
10320

    
10321
  def Exec(self, feedback_fn):
10322
    """Sets the tag.
10323

10324
    """
10325
    try:
10326
      for tag in self.op.tags:
10327
        self.target.AddTag(tag)
10328
    except errors.TagError, err:
10329
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10330
    self.cfg.Update(self.target, feedback_fn)
10331

    
10332

    
10333
class LUDelTags(TagsLU):
10334
  """Delete a list of tags from a given object.
10335

10336
  """
10337
  REQ_BGL = False
10338

    
10339
  def CheckPrereq(self):
10340
    """Check prerequisites.
10341

10342
    This checks that we have the given tag.
10343

10344
    """
10345
    TagsLU.CheckPrereq(self)
10346
    for tag in self.op.tags:
10347
      objects.TaggableObject.ValidateTag(tag)
10348
    del_tags = frozenset(self.op.tags)
10349
    cur_tags = self.target.GetTags()
10350

    
10351
    diff_tags = del_tags - cur_tags
10352
    if diff_tags:
10353
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10354
      raise errors.OpPrereqError("Tag(s) %s not found" %
10355
                                 (utils.CommaJoin(diff_names), ),
10356
                                 errors.ECODE_NOENT)
10357

    
10358
  def Exec(self, feedback_fn):
10359
    """Remove the tag from the object.
10360

10361
    """
10362
    for tag in self.op.tags:
10363
      self.target.RemoveTag(tag)
10364
    self.cfg.Update(self.target, feedback_fn)
10365

    
10366

    
10367
class LUTestDelay(NoHooksLU):
10368
  """Sleep for a specified amount of time.
10369

10370
  This LU sleeps on the master and/or nodes for a specified amount of
10371
  time.
10372

10373
  """
10374
  REQ_BGL = False
10375

    
10376
  def ExpandNames(self):
10377
    """Expand names and set required locks.
10378

10379
    This expands the node list, if any.
10380

10381
    """
10382
    self.needed_locks = {}
10383
    if self.op.on_nodes:
10384
      # _GetWantedNodes can be used here, but is not always appropriate to use
10385
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10386
      # more information.
10387
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10388
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10389

    
10390
  def _TestDelay(self):
10391
    """Do the actual sleep.
10392

10393
    """
10394
    if self.op.on_master:
10395
      if not utils.TestDelay(self.op.duration):
10396
        raise errors.OpExecError("Error during master delay test")
10397
    if self.op.on_nodes:
10398
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10399
      for node, node_result in result.items():
10400
        node_result.Raise("Failure during rpc call to node %s" % node)
10401

    
10402
  def Exec(self, feedback_fn):
10403
    """Execute the test delay opcode, with the wanted repetitions.
10404

10405
    """
10406
    if self.op.repeat == 0:
10407
      self._TestDelay()
10408
    else:
10409
      top_value = self.op.repeat - 1
10410
      for i in range(self.op.repeat):
10411
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10412
        self._TestDelay()
10413

    
10414

    
10415
class LUTestJobqueue(NoHooksLU):
10416
  """Utility LU to test some aspects of the job queue.
10417

10418
  """
10419
  REQ_BGL = False
10420

    
10421
  # Must be lower than default timeout for WaitForJobChange to see whether it
10422
  # notices changed jobs
10423
  _CLIENT_CONNECT_TIMEOUT = 20.0
10424
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10425

    
10426
  @classmethod
10427
  def _NotifyUsingSocket(cls, cb, errcls):
10428
    """Opens a Unix socket and waits for another program to connect.
10429

10430
    @type cb: callable
10431
    @param cb: Callback to send socket name to client
10432
    @type errcls: class
10433
    @param errcls: Exception class to use for errors
10434

10435
    """
10436
    # Using a temporary directory as there's no easy way to create temporary
10437
    # sockets without writing a custom loop around tempfile.mktemp and
10438
    # socket.bind
10439
    tmpdir = tempfile.mkdtemp()
10440
    try:
10441
      tmpsock = utils.PathJoin(tmpdir, "sock")
10442

    
10443
      logging.debug("Creating temporary socket at %s", tmpsock)
10444
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10445
      try:
10446
        sock.bind(tmpsock)
10447
        sock.listen(1)
10448

    
10449
        # Send details to client
10450
        cb(tmpsock)
10451

    
10452
        # Wait for client to connect before continuing
10453
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10454
        try:
10455
          (conn, _) = sock.accept()
10456
        except socket.error, err:
10457
          raise errcls("Client didn't connect in time (%s)" % err)
10458
      finally:
10459
        sock.close()
10460
    finally:
10461
      # Remove as soon as client is connected
10462
      shutil.rmtree(tmpdir)
10463

    
10464
    # Wait for client to close
10465
    try:
10466
      try:
10467
        # pylint: disable-msg=E1101
10468
        # Instance of '_socketobject' has no ... member
10469
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10470
        conn.recv(1)
10471
      except socket.error, err:
10472
        raise errcls("Client failed to confirm notification (%s)" % err)
10473
    finally:
10474
      conn.close()
10475

    
10476
  def _SendNotification(self, test, arg, sockname):
10477
    """Sends a notification to the client.
10478

10479
    @type test: string
10480
    @param test: Test name
10481
    @param arg: Test argument (depends on test)
10482
    @type sockname: string
10483
    @param sockname: Socket path
10484

10485
    """
10486
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10487

    
10488
  def _Notify(self, prereq, test, arg):
10489
    """Notifies the client of a test.
10490

10491
    @type prereq: bool
10492
    @param prereq: Whether this is a prereq-phase test
10493
    @type test: string
10494
    @param test: Test name
10495
    @param arg: Test argument (depends on test)
10496

10497
    """
10498
    if prereq:
10499
      errcls = errors.OpPrereqError
10500
    else:
10501
      errcls = errors.OpExecError
10502

    
10503
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10504
                                                  test, arg),
10505
                                   errcls)
10506

    
10507
  def CheckArguments(self):
10508
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10509
    self.expandnames_calls = 0
10510

    
10511
  def ExpandNames(self):
10512
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10513
    if checkargs_calls < 1:
10514
      raise errors.ProgrammerError("CheckArguments was not called")
10515

    
10516
    self.expandnames_calls += 1
10517

    
10518
    if self.op.notify_waitlock:
10519
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10520

    
10521
    self.LogInfo("Expanding names")
10522

    
10523
    # Get lock on master node (just to get a lock, not for a particular reason)
10524
    self.needed_locks = {
10525
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10526
      }
10527

    
10528
  def Exec(self, feedback_fn):
10529
    if self.expandnames_calls < 1:
10530
      raise errors.ProgrammerError("ExpandNames was not called")
10531

    
10532
    if self.op.notify_exec:
10533
      self._Notify(False, constants.JQT_EXEC, None)
10534

    
10535
    self.LogInfo("Executing")
10536

    
10537
    if self.op.log_messages:
10538
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10539
      for idx, msg in enumerate(self.op.log_messages):
10540
        self.LogInfo("Sending log message %s", idx + 1)
10541
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10542
        # Report how many test messages have been sent
10543
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10544

    
10545
    if self.op.fail:
10546
      raise errors.OpExecError("Opcode failure was requested")
10547

    
10548
    return True
10549

    
10550

    
10551
class IAllocator(object):
10552
  """IAllocator framework.
10553

10554
  An IAllocator instance has three sets of attributes:
10555
    - cfg that is needed to query the cluster
10556
    - input data (all members of the _KEYS class attribute are required)
10557
    - four buffer attributes (in|out_data|text), that represent the
10558
      input (to the external script) in text and data structure format,
10559
      and the output from it, again in two formats
10560
    - the result variables from the script (success, info, nodes) for
10561
      easy usage
10562

10563
  """
10564
  # pylint: disable-msg=R0902
10565
  # lots of instance attributes
10566
  _ALLO_KEYS = [
10567
    "name", "mem_size", "disks", "disk_template",
10568
    "os", "tags", "nics", "vcpus", "hypervisor",
10569
    ]
10570
  _RELO_KEYS = [
10571
    "name", "relocate_from",
10572
    ]
10573
  _EVAC_KEYS = [
10574
    "evac_nodes",
10575
    ]
10576

    
10577
  def __init__(self, cfg, rpc, mode, **kwargs):
10578
    self.cfg = cfg
10579
    self.rpc = rpc
10580
    # init buffer variables
10581
    self.in_text = self.out_text = self.in_data = self.out_data = None
10582
    # init all input fields so that pylint is happy
10583
    self.mode = mode
10584
    self.mem_size = self.disks = self.disk_template = None
10585
    self.os = self.tags = self.nics = self.vcpus = None
10586
    self.hypervisor = None
10587
    self.relocate_from = None
10588
    self.name = None
10589
    self.evac_nodes = None
10590
    # computed fields
10591
    self.required_nodes = None
10592
    # init result fields
10593
    self.success = self.info = self.result = None
10594
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10595
      keyset = self._ALLO_KEYS
10596
      fn = self._AddNewInstance
10597
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10598
      keyset = self._RELO_KEYS
10599
      fn = self._AddRelocateInstance
10600
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10601
      keyset = self._EVAC_KEYS
10602
      fn = self._AddEvacuateNodes
10603
    else:
10604
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10605
                                   " IAllocator" % self.mode)
10606
    for key in kwargs:
10607
      if key not in keyset:
10608
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10609
                                     " IAllocator" % key)
10610
      setattr(self, key, kwargs[key])
10611

    
10612
    for key in keyset:
10613
      if key not in kwargs:
10614
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10615
                                     " IAllocator" % key)
10616
    self._BuildInputData(fn)
10617

    
10618
  def _ComputeClusterData(self):
10619
    """Compute the generic allocator input data.
10620

10621
    This is the data that is independent of the actual operation.
10622

10623
    """
10624
    cfg = self.cfg
10625
    cluster_info = cfg.GetClusterInfo()
10626
    # cluster data
10627
    data = {
10628
      "version": constants.IALLOCATOR_VERSION,
10629
      "cluster_name": cfg.GetClusterName(),
10630
      "cluster_tags": list(cluster_info.GetTags()),
10631
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10632
      # we don't have job IDs
10633
      }
10634
    iinfo = cfg.GetAllInstancesInfo().values()
10635
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10636

    
10637
    # node data
10638
    node_list = cfg.GetNodeList()
10639

    
10640
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10641
      hypervisor_name = self.hypervisor
10642
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10643
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10644
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10645
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10646

    
10647
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10648
                                        hypervisor_name)
10649
    node_iinfo = \
10650
      self.rpc.call_all_instances_info(node_list,
10651
                                       cluster_info.enabled_hypervisors)
10652

    
10653
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10654

    
10655
    data["nodes"] = self._ComputeNodeData(cfg, node_data, node_iinfo, i_list)
10656

    
10657
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10658

    
10659
    self.in_data = data
10660

    
10661
  @staticmethod
10662
  def _ComputeNodeGroupData(cfg):
10663
    """Compute node groups data.
10664

10665
    """
10666
    ng = {}
10667
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10668
      ng[guuid] = {
10669
        "name": gdata.name,
10670
        "alloc_policy": gdata.alloc_policy,
10671
        }
10672
    return ng
10673

    
10674
  @staticmethod
10675
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10676
    """Compute global node data.
10677

10678
    """
10679
    node_results = {}
10680
    for nname, nresult in node_data.items():
10681
      # first fill in static (config-based) values
10682
      ninfo = cfg.GetNodeInfo(nname)
10683
      pnr = {
10684
        "tags": list(ninfo.GetTags()),
10685
        "primary_ip": ninfo.primary_ip,
10686
        "secondary_ip": ninfo.secondary_ip,
10687
        "offline": ninfo.offline,
10688
        "drained": ninfo.drained,
10689
        "master_candidate": ninfo.master_candidate,
10690
        "group": ninfo.group,
10691
        "master_capable": ninfo.master_capable,
10692
        "vm_capable": ninfo.vm_capable,
10693
        }
10694

    
10695
      if not (ninfo.offline or ninfo.drained):
10696
        nresult.Raise("Can't get data for node %s" % nname)
10697
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10698
                                nname)
10699
        remote_info = nresult.payload
10700

    
10701
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10702
                     'vg_size', 'vg_free', 'cpu_total']:
10703
          if attr not in remote_info:
10704
            raise errors.OpExecError("Node '%s' didn't return attribute"
10705
                                     " '%s'" % (nname, attr))
10706
          if not isinstance(remote_info[attr], int):
10707
            raise errors.OpExecError("Node '%s' returned invalid value"
10708
                                     " for '%s': %s" %
10709
                                     (nname, attr, remote_info[attr]))
10710
        # compute memory used by primary instances
10711
        i_p_mem = i_p_up_mem = 0
10712
        for iinfo, beinfo in i_list:
10713
          if iinfo.primary_node == nname:
10714
            i_p_mem += beinfo[constants.BE_MEMORY]
10715
            if iinfo.name not in node_iinfo[nname].payload:
10716
              i_used_mem = 0
10717
            else:
10718
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10719
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10720
            remote_info['memory_free'] -= max(0, i_mem_diff)
10721

    
10722
            if iinfo.admin_up:
10723
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10724

    
10725
        # compute memory used by instances
10726
        pnr_dyn = {
10727
          "total_memory": remote_info['memory_total'],
10728
          "reserved_memory": remote_info['memory_dom0'],
10729
          "free_memory": remote_info['memory_free'],
10730
          "total_disk": remote_info['vg_size'],
10731
          "free_disk": remote_info['vg_free'],
10732
          "total_cpus": remote_info['cpu_total'],
10733
          "i_pri_memory": i_p_mem,
10734
          "i_pri_up_memory": i_p_up_mem,
10735
          }
10736
        pnr.update(pnr_dyn)
10737

    
10738
      node_results[nname] = pnr
10739

    
10740
    return node_results
10741

    
10742
  @staticmethod
10743
  def _ComputeInstanceData(cluster_info, i_list):
10744
    """Compute global instance data.
10745

10746
    """
10747
    instance_data = {}
10748
    for iinfo, beinfo in i_list:
10749
      nic_data = []
10750
      for nic in iinfo.nics:
10751
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10752
        nic_dict = {"mac": nic.mac,
10753
                    "ip": nic.ip,
10754
                    "mode": filled_params[constants.NIC_MODE],
10755
                    "link": filled_params[constants.NIC_LINK],
10756
                   }
10757
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10758
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10759
        nic_data.append(nic_dict)
10760
      pir = {
10761
        "tags": list(iinfo.GetTags()),
10762
        "admin_up": iinfo.admin_up,
10763
        "vcpus": beinfo[constants.BE_VCPUS],
10764
        "memory": beinfo[constants.BE_MEMORY],
10765
        "os": iinfo.os,
10766
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10767
        "nics": nic_data,
10768
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10769
        "disk_template": iinfo.disk_template,
10770
        "hypervisor": iinfo.hypervisor,
10771
        }
10772
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10773
                                                 pir["disks"])
10774
      instance_data[iinfo.name] = pir
10775

    
10776
    return instance_data
10777

    
10778
  def _AddNewInstance(self):
10779
    """Add new instance data to allocator structure.
10780

10781
    This in combination with _AllocatorGetClusterData will create the
10782
    correct structure needed as input for the allocator.
10783

10784
    The checks for the completeness of the opcode must have already been
10785
    done.
10786

10787
    """
10788
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10789

    
10790
    if self.disk_template in constants.DTS_NET_MIRROR:
10791
      self.required_nodes = 2
10792
    else:
10793
      self.required_nodes = 1
10794
    request = {
10795
      "name": self.name,
10796
      "disk_template": self.disk_template,
10797
      "tags": self.tags,
10798
      "os": self.os,
10799
      "vcpus": self.vcpus,
10800
      "memory": self.mem_size,
10801
      "disks": self.disks,
10802
      "disk_space_total": disk_space,
10803
      "nics": self.nics,
10804
      "required_nodes": self.required_nodes,
10805
      }
10806
    return request
10807

    
10808
  def _AddRelocateInstance(self):
10809
    """Add relocate instance data to allocator structure.
10810

10811
    This in combination with _IAllocatorGetClusterData will create the
10812
    correct structure needed as input for the allocator.
10813

10814
    The checks for the completeness of the opcode must have already been
10815
    done.
10816

10817
    """
10818
    instance = self.cfg.GetInstanceInfo(self.name)
10819
    if instance is None:
10820
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10821
                                   " IAllocator" % self.name)
10822

    
10823
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10824
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10825
                                 errors.ECODE_INVAL)
10826

    
10827
    if len(instance.secondary_nodes) != 1:
10828
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10829
                                 errors.ECODE_STATE)
10830

    
10831
    self.required_nodes = 1
10832
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10833
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10834

    
10835
    request = {
10836
      "name": self.name,
10837
      "disk_space_total": disk_space,
10838
      "required_nodes": self.required_nodes,
10839
      "relocate_from": self.relocate_from,
10840
      }
10841
    return request
10842

    
10843
  def _AddEvacuateNodes(self):
10844
    """Add evacuate nodes data to allocator structure.
10845

10846
    """
10847
    request = {
10848
      "evac_nodes": self.evac_nodes
10849
      }
10850
    return request
10851

    
10852
  def _BuildInputData(self, fn):
10853
    """Build input data structures.
10854

10855
    """
10856
    self._ComputeClusterData()
10857

    
10858
    request = fn()
10859
    request["type"] = self.mode
10860
    self.in_data["request"] = request
10861

    
10862
    self.in_text = serializer.Dump(self.in_data)
10863

    
10864
  def Run(self, name, validate=True, call_fn=None):
10865
    """Run an instance allocator and return the results.
10866

10867
    """
10868
    if call_fn is None:
10869
      call_fn = self.rpc.call_iallocator_runner
10870

    
10871
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10872
    result.Raise("Failure while running the iallocator script")
10873

    
10874
    self.out_text = result.payload
10875
    if validate:
10876
      self._ValidateResult()
10877

    
10878
  def _ValidateResult(self):
10879
    """Process the allocator results.
10880

10881
    This will process and if successful save the result in
10882
    self.out_data and the other parameters.
10883

10884
    """
10885
    try:
10886
      rdict = serializer.Load(self.out_text)
10887
    except Exception, err:
10888
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10889

    
10890
    if not isinstance(rdict, dict):
10891
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10892

    
10893
    # TODO: remove backwards compatiblity in later versions
10894
    if "nodes" in rdict and "result" not in rdict:
10895
      rdict["result"] = rdict["nodes"]
10896
      del rdict["nodes"]
10897

    
10898
    for key in "success", "info", "result":
10899
      if key not in rdict:
10900
        raise errors.OpExecError("Can't parse iallocator results:"
10901
                                 " missing key '%s'" % key)
10902
      setattr(self, key, rdict[key])
10903

    
10904
    if not isinstance(rdict["result"], list):
10905
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10906
                               " is not a list")
10907
    self.out_data = rdict
10908

    
10909

    
10910
class LUTestAllocator(NoHooksLU):
10911
  """Run allocator tests.
10912

10913
  This LU runs the allocator tests
10914

10915
  """
10916
  def CheckPrereq(self):
10917
    """Check prerequisites.
10918

10919
    This checks the opcode parameters depending on the director and mode test.
10920

10921
    """
10922
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10923
      for attr in ["mem_size", "disks", "disk_template",
10924
                   "os", "tags", "nics", "vcpus"]:
10925
        if not hasattr(self.op, attr):
10926
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10927
                                     attr, errors.ECODE_INVAL)
10928
      iname = self.cfg.ExpandInstanceName(self.op.name)
10929
      if iname is not None:
10930
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10931
                                   iname, errors.ECODE_EXISTS)
10932
      if not isinstance(self.op.nics, list):
10933
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10934
                                   errors.ECODE_INVAL)
10935
      if not isinstance(self.op.disks, list):
10936
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10937
                                   errors.ECODE_INVAL)
10938
      for row in self.op.disks:
10939
        if (not isinstance(row, dict) or
10940
            "size" not in row or
10941
            not isinstance(row["size"], int) or
10942
            "mode" not in row or
10943
            row["mode"] not in ['r', 'w']):
10944
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10945
                                     " parameter", errors.ECODE_INVAL)
10946
      if self.op.hypervisor is None:
10947
        self.op.hypervisor = self.cfg.GetHypervisorType()
10948
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10949
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10950
      self.op.name = fname
10951
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10952
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10953
      if not hasattr(self.op, "evac_nodes"):
10954
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10955
                                   " opcode input", errors.ECODE_INVAL)
10956
    else:
10957
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10958
                                 self.op.mode, errors.ECODE_INVAL)
10959

    
10960
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10961
      if self.op.allocator is None:
10962
        raise errors.OpPrereqError("Missing allocator name",
10963
                                   errors.ECODE_INVAL)
10964
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10965
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10966
                                 self.op.direction, errors.ECODE_INVAL)
10967

    
10968
  def Exec(self, feedback_fn):
10969
    """Run the allocator test.
10970

10971
    """
10972
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10973
      ial = IAllocator(self.cfg, self.rpc,
10974
                       mode=self.op.mode,
10975
                       name=self.op.name,
10976
                       mem_size=self.op.mem_size,
10977
                       disks=self.op.disks,
10978
                       disk_template=self.op.disk_template,
10979
                       os=self.op.os,
10980
                       tags=self.op.tags,
10981
                       nics=self.op.nics,
10982
                       vcpus=self.op.vcpus,
10983
                       hypervisor=self.op.hypervisor,
10984
                       )
10985
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10986
      ial = IAllocator(self.cfg, self.rpc,
10987
                       mode=self.op.mode,
10988
                       name=self.op.name,
10989
                       relocate_from=list(self.relocate_from),
10990
                       )
10991
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10992
      ial = IAllocator(self.cfg, self.rpc,
10993
                       mode=self.op.mode,
10994
                       evac_nodes=self.op.evac_nodes)
10995
    else:
10996
      raise errors.ProgrammerError("Uncatched mode %s in"
10997
                                   " LUTestAllocator.Exec", self.op.mode)
10998

    
10999
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11000
      result = ial.in_text
11001
    else:
11002
      ial.Run(self.op.allocator, validate=False)
11003
      result = ial.out_text
11004
    return result
11005

    
11006

    
11007
#: Query type implementations
11008
_QUERY_IMPL = {
11009
  constants.QR_INSTANCE: _InstanceQuery,
11010
  constants.QR_NODE: _NodeQuery,
11011
  constants.QR_GROUP: _GroupQuery,
11012
  }
11013

    
11014

    
11015
def _GetQueryImplementation(name):
11016
  """Returns the implemtnation for a query type.
11017

11018
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
11019

11020
  """
11021
  try:
11022
    return _QUERY_IMPL[name]
11023
  except KeyError:
11024
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11025
                               errors.ECODE_INVAL)