Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ cafa5b70

History | View | Annotate | Download (427.9 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
64

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

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

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

    
77

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

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

91
  Note that all commands require root permissions.
92

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

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

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

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

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

    
134
    # Tasklets
135
    self.tasklets = None
136

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

    
140
    self.CheckArguments()
141

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

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

    
150
  ssh = property(fget=__GetSSH)
151

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

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

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

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

167
    """
168
    pass
169

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

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

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

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

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

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

195
    Examples::
196

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

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

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

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

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

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

234
    """
235

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

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

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

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

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

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

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

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

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

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

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

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

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

293
    """
294
    raise NotImplementedError
295

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
382
    del self.recalculate_locks[locking.LEVEL_NODE]
383

    
384

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

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

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

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

398
    This just raises an error.
399

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

    
403

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

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

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

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

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

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

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

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

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

436
    """
437
    pass
438

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

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

446
    """
447
    raise NotImplementedError
448

    
449

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

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

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

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

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

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

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

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

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

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

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

    
493
    # Return expanded names
494
    return self.wanted
495

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

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

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

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

508
    See L{LogicalUnit.ExpandNames}.
509

510
    """
511
    raise NotImplementedError()
512

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

516
    See L{LogicalUnit.DeclareLocks}.
517

518
    """
519
    raise NotImplementedError()
520

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

524
    @return: Query data object
525

526
    """
527
    raise NotImplementedError()
528

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

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

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

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

    
541

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

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

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

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

    
559

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

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

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

    
579

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

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

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

    
612

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

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

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

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

    
631

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

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

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

    
646

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

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

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

    
661

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

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

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

    
674

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

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

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

    
687

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

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

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

    
705

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

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

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

    
732

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

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

    
740

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

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

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

    
756

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

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

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

    
773

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

    
778

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

    
783

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

789
  This builds the hook environment from individual variables.
790

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

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

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

    
853
  env["INSTANCE_NIC_COUNT"] = nic_count
854

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

    
863
  env["INSTANCE_DISK_COUNT"] = disk_count
864

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

    
869
  return env
870

    
871

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

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

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

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

    
895

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

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

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

    
933

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

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

    
949

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

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

    
960

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

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

    
974

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

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

    
983

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

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

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

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

    
1003

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

    
1007

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

1011
  """
1012

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

    
1015

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

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

    
1023

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

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

    
1031

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

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

    
1041
  return []
1042

    
1043

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

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

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

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

    
1058
  return faulty
1059

    
1060

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

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

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

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

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

    
1092

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

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

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

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

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

1111
    """
1112
    return True
1113

    
1114

    
1115
class LUClusterDestroy(LogicalUnit):
1116
  """Logical unit for destroying the cluster.
1117

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

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

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

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

1132
    This checks whether the cluster is empty.
1133

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

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

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

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

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

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

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

    
1167
    return master
1168

    
1169

    
1170
def _VerifyCertificate(filename):
1171
  """Verifies a certificate for LUClusterVerify.
1172

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

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

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

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

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

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

    
1202

    
1203
class LUClusterVerify(LogicalUnit):
1204
  """Verifies the cluster status.
1205

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

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

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

    
1242
  ETYPE_FIELD = "code"
1243
  ETYPE_ERROR = "ERROR"
1244
  ETYPE_WARNING = "WARNING"
1245

    
1246
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1247

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

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

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

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

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

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

1311
    This must be called only from Exec and functions called from Exec.
1312

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

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

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

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

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

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

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

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

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

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

    
1385
    # node seems compatible, we can actually try to look into its results
1386

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

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

    
1401
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1402
    if ninfo.vm_capable and isinstance(hvp_result, list):
1403
      for item, hv_name, hv_result in hvp_result:
1404
        _ErrorIf(True, self.ENODEHV, node,
1405
                 "hypervisor %s parameter verify failure (source %s): %s",
1406
                 hv_name, item, hv_result)
1407

    
1408
    test = nresult.get(constants.NV_NODESETUP,
1409
                           ["Missing NODESETUP results"])
1410
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1411
             "; ".join(test))
1412

    
1413
    return True
1414

    
1415
  def _VerifyNodeTime(self, ninfo, nresult,
1416
                      nvinfo_starttime, nvinfo_endtime):
1417
    """Check the node time.
1418

1419
    @type ninfo: L{objects.Node}
1420
    @param ninfo: the node to check
1421
    @param nresult: the remote results for the node
1422
    @param nvinfo_starttime: the start time of the RPC call
1423
    @param nvinfo_endtime: the end time of the RPC call
1424

1425
    """
1426
    node = ninfo.name
1427
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1428

    
1429
    ntime = nresult.get(constants.NV_TIME, None)
1430
    try:
1431
      ntime_merged = utils.MergeTime(ntime)
1432
    except (ValueError, TypeError):
1433
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1434
      return
1435

    
1436
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1437
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1438
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1439
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1440
    else:
1441
      ntime_diff = None
1442

    
1443
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1444
             "Node time diverges by at least %s from master node time",
1445
             ntime_diff)
1446

    
1447
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1448
    """Check the node LVM results.
1449

1450
    @type ninfo: L{objects.Node}
1451
    @param ninfo: the node to check
1452
    @param nresult: the remote results for the node
1453
    @param vg_name: the configured VG name
1454

1455
    """
1456
    if vg_name is None:
1457
      return
1458

    
1459
    node = ninfo.name
1460
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1461

    
1462
    # checks vg existence and size > 20G
1463
    vglist = nresult.get(constants.NV_VGLIST, None)
1464
    test = not vglist
1465
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1466
    if not test:
1467
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1468
                                            constants.MIN_VG_SIZE)
1469
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1470

    
1471
    # check pv names
1472
    pvlist = nresult.get(constants.NV_PVLIST, None)
1473
    test = pvlist is None
1474
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1475
    if not test:
1476
      # check that ':' is not present in PV names, since it's a
1477
      # special character for lvcreate (denotes the range of PEs to
1478
      # use on the PV)
1479
      for _, pvname, owner_vg in pvlist:
1480
        test = ":" in pvname
1481
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1482
                 " '%s' of VG '%s'", pvname, owner_vg)
1483

    
1484
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1485
    """Check the node bridges.
1486

1487
    @type ninfo: L{objects.Node}
1488
    @param ninfo: the node to check
1489
    @param nresult: the remote results for the node
1490
    @param bridges: the expected list of bridges
1491

1492
    """
1493
    if not bridges:
1494
      return
1495

    
1496
    node = ninfo.name
1497
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1498

    
1499
    missing = nresult.get(constants.NV_BRIDGES, None)
1500
    test = not isinstance(missing, list)
1501
    _ErrorIf(test, self.ENODENET, node,
1502
             "did not return valid bridge information")
1503
    if not test:
1504
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1505
               utils.CommaJoin(sorted(missing)))
1506

    
1507
  def _VerifyNodeNetwork(self, ninfo, nresult):
1508
    """Check the node network connectivity results.
1509

1510
    @type ninfo: L{objects.Node}
1511
    @param ninfo: the node to check
1512
    @param nresult: the remote results for the node
1513

1514
    """
1515
    node = ninfo.name
1516
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1517

    
1518
    test = constants.NV_NODELIST not in nresult
1519
    _ErrorIf(test, self.ENODESSH, node,
1520
             "node hasn't returned node ssh connectivity data")
1521
    if not test:
1522
      if nresult[constants.NV_NODELIST]:
1523
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1524
          _ErrorIf(True, self.ENODESSH, node,
1525
                   "ssh communication with node '%s': %s", a_node, a_msg)
1526

    
1527
    test = constants.NV_NODENETTEST not in nresult
1528
    _ErrorIf(test, self.ENODENET, node,
1529
             "node hasn't returned node tcp connectivity data")
1530
    if not test:
1531
      if nresult[constants.NV_NODENETTEST]:
1532
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1533
        for anode in nlist:
1534
          _ErrorIf(True, self.ENODENET, node,
1535
                   "tcp communication with node '%s': %s",
1536
                   anode, nresult[constants.NV_NODENETTEST][anode])
1537

    
1538
    test = constants.NV_MASTERIP not in nresult
1539
    _ErrorIf(test, self.ENODENET, node,
1540
             "node hasn't returned node master IP reachability data")
1541
    if not test:
1542
      if not nresult[constants.NV_MASTERIP]:
1543
        if node == self.master_node:
1544
          msg = "the master node cannot reach the master IP (not configured?)"
1545
        else:
1546
          msg = "cannot reach the master IP"
1547
        _ErrorIf(True, self.ENODENET, node, msg)
1548

    
1549
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1550
                      diskstatus):
1551
    """Verify an instance.
1552

1553
    This function checks to see if the required block devices are
1554
    available on the instance's node.
1555

1556
    """
1557
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1558
    node_current = instanceconfig.primary_node
1559

    
1560
    node_vol_should = {}
1561
    instanceconfig.MapLVsByNode(node_vol_should)
1562

    
1563
    for node in node_vol_should:
1564
      n_img = node_image[node]
1565
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1566
        # ignore missing volumes on offline or broken nodes
1567
        continue
1568
      for volume in node_vol_should[node]:
1569
        test = volume not in n_img.volumes
1570
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1571
                 "volume %s missing on node %s", volume, node)
1572

    
1573
    if instanceconfig.admin_up:
1574
      pri_img = node_image[node_current]
1575
      test = instance not in pri_img.instances and not pri_img.offline
1576
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1577
               "instance not running on its primary node %s",
1578
               node_current)
1579

    
1580
    for node, n_img in node_image.items():
1581
      if node != node_current:
1582
        test = instance in n_img.instances
1583
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1584
                 "instance should not run on node %s", node)
1585

    
1586
    diskdata = [(nname, success, status, idx)
1587
                for (nname, disks) in diskstatus.items()
1588
                for idx, (success, status) in enumerate(disks)]
1589

    
1590
    for nname, success, bdev_status, idx in diskdata:
1591
      # the 'ghost node' construction in Exec() ensures that we have a
1592
      # node here
1593
      snode = node_image[nname]
1594
      bad_snode = snode.ghost or snode.offline
1595
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1596
               self.EINSTANCEFAULTYDISK, instance,
1597
               "couldn't retrieve status for disk/%s on %s: %s",
1598
               idx, nname, bdev_status)
1599
      _ErrorIf((instanceconfig.admin_up and success and
1600
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1601
               self.EINSTANCEFAULTYDISK, instance,
1602
               "disk/%s on %s is faulty", idx, nname)
1603

    
1604
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1605
    """Verify if there are any unknown volumes in the cluster.
1606

1607
    The .os, .swap and backup volumes are ignored. All other volumes are
1608
    reported as unknown.
1609

1610
    @type reserved: L{ganeti.utils.FieldSet}
1611
    @param reserved: a FieldSet of reserved volume names
1612

1613
    """
1614
    for node, n_img in node_image.items():
1615
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1616
        # skip non-healthy nodes
1617
        continue
1618
      for volume in n_img.volumes:
1619
        test = ((node not in node_vol_should or
1620
                volume not in node_vol_should[node]) and
1621
                not reserved.Matches(volume))
1622
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1623
                      "volume %s is unknown", volume)
1624

    
1625
  def _VerifyOrphanInstances(self, instancelist, node_image):
1626
    """Verify the list of running instances.
1627

1628
    This checks what instances are running but unknown to the cluster.
1629

1630
    """
1631
    for node, n_img in node_image.items():
1632
      for o_inst in n_img.instances:
1633
        test = o_inst not in instancelist
1634
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1635
                      "instance %s on node %s should not exist", o_inst, node)
1636

    
1637
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1638
    """Verify N+1 Memory Resilience.
1639

1640
    Check that if one single node dies we can still start all the
1641
    instances it was primary for.
1642

1643
    """
1644
    for node, n_img in node_image.items():
1645
      # This code checks that every node which is now listed as
1646
      # secondary has enough memory to host all instances it is
1647
      # supposed to should a single other node in the cluster fail.
1648
      # FIXME: not ready for failover to an arbitrary node
1649
      # FIXME: does not support file-backed instances
1650
      # WARNING: we currently take into account down instances as well
1651
      # as up ones, considering that even if they're down someone
1652
      # might want to start them even in the event of a node failure.
1653
      if n_img.offline:
1654
        # we're skipping offline nodes from the N+1 warning, since
1655
        # most likely we don't have good memory infromation from them;
1656
        # we already list instances living on such nodes, and that's
1657
        # enough warning
1658
        continue
1659
      for prinode, instances in n_img.sbp.items():
1660
        needed_mem = 0
1661
        for instance in instances:
1662
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1663
          if bep[constants.BE_AUTO_BALANCE]:
1664
            needed_mem += bep[constants.BE_MEMORY]
1665
        test = n_img.mfree < needed_mem
1666
        self._ErrorIf(test, self.ENODEN1, node,
1667
                      "not enough memory to accomodate instance failovers"
1668
                      " should node %s fail (%dMiB needed, %dMiB available)",
1669
                      prinode, needed_mem, n_img.mfree)
1670

    
1671
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1672
                       master_files):
1673
    """Verifies and computes the node required file checksums.
1674

1675
    @type ninfo: L{objects.Node}
1676
    @param ninfo: the node to check
1677
    @param nresult: the remote results for the node
1678
    @param file_list: required list of files
1679
    @param local_cksum: dictionary of local files and their checksums
1680
    @param master_files: list of files that only masters should have
1681

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

    
1686
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1687
    test = not isinstance(remote_cksum, dict)
1688
    _ErrorIf(test, self.ENODEFILECHECK, node,
1689
             "node hasn't returned file checksum data")
1690
    if test:
1691
      return
1692

    
1693
    for file_name in file_list:
1694
      node_is_mc = ninfo.master_candidate
1695
      must_have = (file_name not in master_files) or node_is_mc
1696
      # missing
1697
      test1 = file_name not in remote_cksum
1698
      # invalid checksum
1699
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1700
      # existing and good
1701
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1702
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1703
               "file '%s' missing", file_name)
1704
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1705
               "file '%s' has wrong checksum", file_name)
1706
      # not candidate and this is not a must-have file
1707
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1708
               "file '%s' should not exist on non master"
1709
               " candidates (and the file is outdated)", file_name)
1710
      # all good, except non-master/non-must have combination
1711
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1712
               "file '%s' should not exist"
1713
               " on non master candidates", file_name)
1714

    
1715
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1716
                      drbd_map):
1717
    """Verifies and the node DRBD status.
1718

1719
    @type ninfo: L{objects.Node}
1720
    @param ninfo: the node to check
1721
    @param nresult: the remote results for the node
1722
    @param instanceinfo: the dict of instances
1723
    @param drbd_helper: the configured DRBD usermode helper
1724
    @param drbd_map: the DRBD map as returned by
1725
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1726

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

    
1731
    if drbd_helper:
1732
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1733
      test = (helper_result == None)
1734
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1735
               "no drbd usermode helper returned")
1736
      if helper_result:
1737
        status, payload = helper_result
1738
        test = not status
1739
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1740
                 "drbd usermode helper check unsuccessful: %s", payload)
1741
        test = status and (payload != drbd_helper)
1742
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1743
                 "wrong drbd usermode helper: %s", payload)
1744

    
1745
    # compute the DRBD minors
1746
    node_drbd = {}
1747
    for minor, instance in drbd_map[node].items():
1748
      test = instance not in instanceinfo
1749
      _ErrorIf(test, self.ECLUSTERCFG, None,
1750
               "ghost instance '%s' in temporary DRBD map", instance)
1751
        # ghost instance should not be running, but otherwise we
1752
        # don't give double warnings (both ghost instance and
1753
        # unallocated minor in use)
1754
      if test:
1755
        node_drbd[minor] = (instance, False)
1756
      else:
1757
        instance = instanceinfo[instance]
1758
        node_drbd[minor] = (instance.name, instance.admin_up)
1759

    
1760
    # and now check them
1761
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1762
    test = not isinstance(used_minors, (tuple, list))
1763
    _ErrorIf(test, self.ENODEDRBD, node,
1764
             "cannot parse drbd status file: %s", str(used_minors))
1765
    if test:
1766
      # we cannot check drbd status
1767
      return
1768

    
1769
    for minor, (iname, must_exist) in node_drbd.items():
1770
      test = minor not in used_minors and must_exist
1771
      _ErrorIf(test, self.ENODEDRBD, node,
1772
               "drbd minor %d of instance %s is not active", minor, iname)
1773
    for minor in used_minors:
1774
      test = minor not in node_drbd
1775
      _ErrorIf(test, self.ENODEDRBD, node,
1776
               "unallocated drbd minor %d is in use", minor)
1777

    
1778
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1779
    """Builds the node OS structures.
1780

1781
    @type ninfo: L{objects.Node}
1782
    @param ninfo: the node to check
1783
    @param nresult: the remote results for the node
1784
    @param nimg: the node image object
1785

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

    
1790
    remote_os = nresult.get(constants.NV_OSLIST, None)
1791
    test = (not isinstance(remote_os, list) or
1792
            not compat.all(isinstance(v, list) and len(v) == 7
1793
                           for v in remote_os))
1794

    
1795
    _ErrorIf(test, self.ENODEOS, node,
1796
             "node hasn't returned valid OS data")
1797

    
1798
    nimg.os_fail = test
1799

    
1800
    if test:
1801
      return
1802

    
1803
    os_dict = {}
1804

    
1805
    for (name, os_path, status, diagnose,
1806
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1807

    
1808
      if name not in os_dict:
1809
        os_dict[name] = []
1810

    
1811
      # parameters is a list of lists instead of list of tuples due to
1812
      # JSON lacking a real tuple type, fix it:
1813
      parameters = [tuple(v) for v in parameters]
1814
      os_dict[name].append((os_path, status, diagnose,
1815
                            set(variants), set(parameters), set(api_ver)))
1816

    
1817
    nimg.oslist = os_dict
1818

    
1819
  def _VerifyNodeOS(self, ninfo, nimg, base):
1820
    """Verifies the node OS list.
1821

1822
    @type ninfo: L{objects.Node}
1823
    @param ninfo: the node to check
1824
    @param nimg: the node image object
1825
    @param base: the 'template' node we match against (e.g. from the master)
1826

1827
    """
1828
    node = ninfo.name
1829
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1830

    
1831
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1832

    
1833
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
1834
    for os_name, os_data in nimg.oslist.items():
1835
      assert os_data, "Empty OS status for OS %s?!" % os_name
1836
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1837
      _ErrorIf(not f_status, self.ENODEOS, node,
1838
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1839
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1840
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1841
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1842
      # this will catched in backend too
1843
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1844
               and not f_var, self.ENODEOS, node,
1845
               "OS %s with API at least %d does not declare any variant",
1846
               os_name, constants.OS_API_V15)
1847
      # comparisons with the 'base' image
1848
      test = os_name not in base.oslist
1849
      _ErrorIf(test, self.ENODEOS, node,
1850
               "Extra OS %s not present on reference node (%s)",
1851
               os_name, base.name)
1852
      if test:
1853
        continue
1854
      assert base.oslist[os_name], "Base node has empty OS status?"
1855
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1856
      if not b_status:
1857
        # base OS is invalid, skipping
1858
        continue
1859
      for kind, a, b in [("API version", f_api, b_api),
1860
                         ("variants list", f_var, b_var),
1861
                         ("parameters", beautify_params(f_param),
1862
                          beautify_params(b_param))]:
1863
        _ErrorIf(a != b, self.ENODEOS, node,
1864
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
1865
                 kind, os_name, base.name,
1866
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
1867

    
1868
    # check any missing OSes
1869
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1870
    _ErrorIf(missing, self.ENODEOS, node,
1871
             "OSes present on reference node %s but missing on this node: %s",
1872
             base.name, utils.CommaJoin(missing))
1873

    
1874
  def _VerifyOob(self, ninfo, nresult):
1875
    """Verifies out of band functionality of a node.
1876

1877
    @type ninfo: L{objects.Node}
1878
    @param ninfo: the node to check
1879
    @param nresult: the remote results for the node
1880

1881
    """
1882
    node = ninfo.name
1883
    # We just have to verify the paths on master and/or master candidates
1884
    # as the oob helper is invoked on the master
1885
    if ((ninfo.master_candidate or ninfo.master_capable) and
1886
        constants.NV_OOB_PATHS in nresult):
1887
      for path_result in nresult[constants.NV_OOB_PATHS]:
1888
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
1889

    
1890
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1891
    """Verifies and updates the node volume data.
1892

1893
    This function will update a L{NodeImage}'s internal structures
1894
    with data from the remote call.
1895

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

1902
    """
1903
    node = ninfo.name
1904
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1905

    
1906
    nimg.lvm_fail = True
1907
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1908
    if vg_name is None:
1909
      pass
1910
    elif isinstance(lvdata, basestring):
1911
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1912
               utils.SafeEncode(lvdata))
1913
    elif not isinstance(lvdata, dict):
1914
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1915
    else:
1916
      nimg.volumes = lvdata
1917
      nimg.lvm_fail = False
1918

    
1919
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1920
    """Verifies and updates the node instance list.
1921

1922
    If the listing was successful, then updates this node's instance
1923
    list. Otherwise, it marks the RPC call as failed for the instance
1924
    list key.
1925

1926
    @type ninfo: L{objects.Node}
1927
    @param ninfo: the node to check
1928
    @param nresult: the remote results for the node
1929
    @param nimg: the node image object
1930

1931
    """
1932
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1933
    test = not isinstance(idata, list)
1934
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1935
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1936
    if test:
1937
      nimg.hyp_fail = True
1938
    else:
1939
      nimg.instances = idata
1940

    
1941
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1942
    """Verifies and computes a node information map
1943

1944
    @type ninfo: L{objects.Node}
1945
    @param ninfo: the node to check
1946
    @param nresult: the remote results for the node
1947
    @param nimg: the node image object
1948
    @param vg_name: the configured VG name
1949

1950
    """
1951
    node = ninfo.name
1952
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1953

    
1954
    # try to read free memory (from the hypervisor)
1955
    hv_info = nresult.get(constants.NV_HVINFO, None)
1956
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1957
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1958
    if not test:
1959
      try:
1960
        nimg.mfree = int(hv_info["memory_free"])
1961
      except (ValueError, TypeError):
1962
        _ErrorIf(True, self.ENODERPC, node,
1963
                 "node returned invalid nodeinfo, check hypervisor")
1964

    
1965
    # FIXME: devise a free space model for file based instances as well
1966
    if vg_name is not None:
1967
      test = (constants.NV_VGLIST not in nresult or
1968
              vg_name not in nresult[constants.NV_VGLIST])
1969
      _ErrorIf(test, self.ENODELVM, node,
1970
               "node didn't return data for the volume group '%s'"
1971
               " - it is either missing or broken", vg_name)
1972
      if not test:
1973
        try:
1974
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1975
        except (ValueError, TypeError):
1976
          _ErrorIf(True, self.ENODERPC, node,
1977
                   "node returned invalid LVM info, check LVM status")
1978

    
1979
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1980
    """Gets per-disk status information for all instances.
1981

1982
    @type nodelist: list of strings
1983
    @param nodelist: Node names
1984
    @type node_image: dict of (name, L{objects.Node})
1985
    @param node_image: Node objects
1986
    @type instanceinfo: dict of (name, L{objects.Instance})
1987
    @param instanceinfo: Instance objects
1988
    @rtype: {instance: {node: [(succes, payload)]}}
1989
    @return: a dictionary of per-instance dictionaries with nodes as
1990
        keys and disk information as values; the disk information is a
1991
        list of tuples (success, payload)
1992

1993
    """
1994
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1995

    
1996
    node_disks = {}
1997
    node_disks_devonly = {}
1998
    diskless_instances = set()
1999
    diskless = constants.DT_DISKLESS
2000

    
2001
    for nname in nodelist:
2002
      node_instances = list(itertools.chain(node_image[nname].pinst,
2003
                                            node_image[nname].sinst))
2004
      diskless_instances.update(inst for inst in node_instances
2005
                                if instanceinfo[inst].disk_template == diskless)
2006
      disks = [(inst, disk)
2007
               for inst in node_instances
2008
               for disk in instanceinfo[inst].disks]
2009

    
2010
      if not disks:
2011
        # No need to collect data
2012
        continue
2013

    
2014
      node_disks[nname] = disks
2015

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

    
2020
      for dev in devonly:
2021
        self.cfg.SetDiskID(dev, nname)
2022

    
2023
      node_disks_devonly[nname] = devonly
2024

    
2025
    assert len(node_disks) == len(node_disks_devonly)
2026

    
2027
    # Collect data from all nodes with disks
2028
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2029
                                                          node_disks_devonly)
2030

    
2031
    assert len(result) == len(node_disks)
2032

    
2033
    instdisk = {}
2034

    
2035
    for (nname, nres) in result.items():
2036
      disks = node_disks[nname]
2037

    
2038
      if nres.offline:
2039
        # No data from this node
2040
        data = len(disks) * [(False, "node offline")]
2041
      else:
2042
        msg = nres.fail_msg
2043
        _ErrorIf(msg, self.ENODERPC, nname,
2044
                 "while getting disk information: %s", msg)
2045
        if msg:
2046
          # No data from this node
2047
          data = len(disks) * [(False, msg)]
2048
        else:
2049
          data = []
2050
          for idx, i in enumerate(nres.payload):
2051
            if isinstance(i, (tuple, list)) and len(i) == 2:
2052
              data.append(i)
2053
            else:
2054
              logging.warning("Invalid result from node %s, entry %d: %s",
2055
                              nname, idx, i)
2056
              data.append((False, "Invalid result from the remote node"))
2057

    
2058
      for ((inst, _), status) in zip(disks, data):
2059
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2060

    
2061
    # Add empty entries for diskless instances.
2062
    for inst in diskless_instances:
2063
      assert inst not in instdisk
2064
      instdisk[inst] = {}
2065

    
2066
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2067
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2068
                      compat.all(isinstance(s, (tuple, list)) and
2069
                                 len(s) == 2 for s in statuses)
2070
                      for inst, nnames in instdisk.items()
2071
                      for nname, statuses in nnames.items())
2072
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2073

    
2074
    return instdisk
2075

    
2076
  def _VerifyHVP(self, hvp_data):
2077
    """Verifies locally the syntax of the hypervisor parameters.
2078

2079
    """
2080
    for item, hv_name, hv_params in hvp_data:
2081
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
2082
             (item, hv_name))
2083
      try:
2084
        hv_class = hypervisor.GetHypervisor(hv_name)
2085
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2086
        hv_class.CheckParameterSyntax(hv_params)
2087
      except errors.GenericError, err:
2088
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
2089

    
2090

    
2091
  def BuildHooksEnv(self):
2092
    """Build hooks env.
2093

2094
    Cluster-Verify hooks just ran in the post phase and their failure makes
2095
    the output be logged in the verify output and the verification to fail.
2096

2097
    """
2098
    all_nodes = self.cfg.GetNodeList()
2099
    env = {
2100
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2101
      }
2102
    for node in self.cfg.GetAllNodesInfo().values():
2103
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2104

    
2105
    return env, [], all_nodes
2106

    
2107
  def Exec(self, feedback_fn):
2108
    """Verify integrity of cluster, performing various test on nodes.
2109

2110
    """
2111
    # This method has too many local variables. pylint: disable-msg=R0914
2112
    self.bad = False
2113
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2114
    verbose = self.op.verbose
2115
    self._feedback_fn = feedback_fn
2116
    feedback_fn("* Verifying global settings")
2117
    for msg in self.cfg.VerifyConfig():
2118
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2119

    
2120
    # Check the cluster certificates
2121
    for cert_filename in constants.ALL_CERT_FILES:
2122
      (errcode, msg) = _VerifyCertificate(cert_filename)
2123
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2124

    
2125
    vg_name = self.cfg.GetVGName()
2126
    drbd_helper = self.cfg.GetDRBDHelper()
2127
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2128
    cluster = self.cfg.GetClusterInfo()
2129
    nodeinfo_byname = self.cfg.GetAllNodesInfo()
2130
    nodelist = utils.NiceSort(nodeinfo_byname.keys())
2131
    nodeinfo = [nodeinfo_byname[nname] for nname in nodelist]
2132
    instanceinfo = self.cfg.GetAllInstancesInfo()
2133
    instancelist = utils.NiceSort(instanceinfo.keys())
2134
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2135
    i_non_redundant = [] # Non redundant instances
2136
    i_non_a_balanced = [] # Non auto-balanced instances
2137
    n_offline = 0 # Count of offline nodes
2138
    n_drained = 0 # Count of nodes being drained
2139
    node_vol_should = {}
2140

    
2141
    # FIXME: verify OS list
2142
    # do local checksums
2143
    master_files = [constants.CLUSTER_CONF_FILE]
2144
    master_node = self.master_node = self.cfg.GetMasterNode()
2145
    master_ip = self.cfg.GetMasterIP()
2146

    
2147
    file_names = ssconf.SimpleStore().GetFileList()
2148
    file_names.extend(constants.ALL_CERT_FILES)
2149
    file_names.extend(master_files)
2150
    if cluster.modify_etc_hosts:
2151
      file_names.append(constants.ETC_HOSTS)
2152

    
2153
    local_checksums = utils.FingerprintFiles(file_names)
2154

    
2155
    # Compute the set of hypervisor parameters
2156
    hvp_data = []
2157
    for hv_name in hypervisors:
2158
      hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
2159
    for os_name, os_hvp in cluster.os_hvp.items():
2160
      for hv_name, hv_params in os_hvp.items():
2161
        if not hv_params:
2162
          continue
2163
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
2164
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
2165
    # TODO: collapse identical parameter values in a single one
2166
    for instance in instanceinfo.values():
2167
      if not instance.hvparams:
2168
        continue
2169
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
2170
                       cluster.FillHV(instance)))
2171
    # and verify them locally
2172
    self._VerifyHVP(hvp_data)
2173

    
2174
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2175
    node_verify_param = {
2176
      constants.NV_FILELIST: file_names,
2177
      constants.NV_NODELIST: [node.name for node in nodeinfo
2178
                              if not node.offline],
2179
      constants.NV_HYPERVISOR: hypervisors,
2180
      constants.NV_HVPARAMS: hvp_data,
2181
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2182
                                  node.secondary_ip) for node in nodeinfo
2183
                                 if not node.offline],
2184
      constants.NV_INSTANCELIST: hypervisors,
2185
      constants.NV_VERSION: None,
2186
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2187
      constants.NV_NODESETUP: None,
2188
      constants.NV_TIME: None,
2189
      constants.NV_MASTERIP: (master_node, master_ip),
2190
      constants.NV_OSLIST: None,
2191
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2192
      }
2193

    
2194
    if vg_name is not None:
2195
      node_verify_param[constants.NV_VGLIST] = None
2196
      node_verify_param[constants.NV_LVLIST] = vg_name
2197
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2198
      node_verify_param[constants.NV_DRBDLIST] = None
2199

    
2200
    if drbd_helper:
2201
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2202

    
2203
    # bridge checks
2204
    # FIXME: this needs to be changed per node-group, not cluster-wide
2205
    bridges = set()
2206
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2207
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2208
      bridges.add(default_nicpp[constants.NIC_LINK])
2209
    for instance in instanceinfo.values():
2210
      for nic in instance.nics:
2211
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2212
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2213
          bridges.add(full_nic[constants.NIC_LINK])
2214

    
2215
    if bridges:
2216
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2217

    
2218
    # Build our expected cluster state
2219
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2220
                                                 name=node.name,
2221
                                                 vm_capable=node.vm_capable))
2222
                      for node in nodeinfo)
2223

    
2224
    # Gather OOB paths
2225
    oob_paths = []
2226
    for node in nodeinfo:
2227
      path = _SupportsOob(self.cfg, node)
2228
      if path and path not in oob_paths:
2229
        oob_paths.append(path)
2230

    
2231
    if oob_paths:
2232
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2233

    
2234
    for instance in instancelist:
2235
      inst_config = instanceinfo[instance]
2236

    
2237
      for nname in inst_config.all_nodes:
2238
        if nname not in node_image:
2239
          # ghost node
2240
          gnode = self.NodeImage(name=nname)
2241
          gnode.ghost = True
2242
          node_image[nname] = gnode
2243

    
2244
      inst_config.MapLVsByNode(node_vol_should)
2245

    
2246
      pnode = inst_config.primary_node
2247
      node_image[pnode].pinst.append(instance)
2248

    
2249
      for snode in inst_config.secondary_nodes:
2250
        nimg = node_image[snode]
2251
        nimg.sinst.append(instance)
2252
        if pnode not in nimg.sbp:
2253
          nimg.sbp[pnode] = []
2254
        nimg.sbp[pnode].append(instance)
2255

    
2256
    # At this point, we have the in-memory data structures complete,
2257
    # except for the runtime information, which we'll gather next
2258

    
2259
    # Due to the way our RPC system works, exact response times cannot be
2260
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2261
    # time before and after executing the request, we can at least have a time
2262
    # window.
2263
    nvinfo_starttime = time.time()
2264
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2265
                                           self.cfg.GetClusterName())
2266
    nvinfo_endtime = time.time()
2267

    
2268
    all_drbd_map = self.cfg.ComputeDRBDMap()
2269

    
2270
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2271
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2272

    
2273
    feedback_fn("* Verifying node status")
2274

    
2275
    refos_img = None
2276

    
2277
    for node_i in nodeinfo:
2278
      node = node_i.name
2279
      nimg = node_image[node]
2280

    
2281
      if node_i.offline:
2282
        if verbose:
2283
          feedback_fn("* Skipping offline node %s" % (node,))
2284
        n_offline += 1
2285
        continue
2286

    
2287
      if node == master_node:
2288
        ntype = "master"
2289
      elif node_i.master_candidate:
2290
        ntype = "master candidate"
2291
      elif node_i.drained:
2292
        ntype = "drained"
2293
        n_drained += 1
2294
      else:
2295
        ntype = "regular"
2296
      if verbose:
2297
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2298

    
2299
      msg = all_nvinfo[node].fail_msg
2300
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2301
      if msg:
2302
        nimg.rpc_fail = True
2303
        continue
2304

    
2305
      nresult = all_nvinfo[node].payload
2306

    
2307
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2308
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2309
      self._VerifyNodeNetwork(node_i, nresult)
2310
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2311
                            master_files)
2312

    
2313
      self._VerifyOob(node_i, nresult)
2314

    
2315
      if nimg.vm_capable:
2316
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2317
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2318
                             all_drbd_map)
2319

    
2320
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2321
        self._UpdateNodeInstances(node_i, nresult, nimg)
2322
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2323
        self._UpdateNodeOS(node_i, nresult, nimg)
2324
        if not nimg.os_fail:
2325
          if refos_img is None:
2326
            refos_img = nimg
2327
          self._VerifyNodeOS(node_i, nimg, refos_img)
2328
        self._VerifyNodeBridges(node_i, nresult, bridges)
2329

    
2330
    feedback_fn("* Verifying instance status")
2331
    for instance in instancelist:
2332
      if verbose:
2333
        feedback_fn("* Verifying instance %s" % instance)
2334
      inst_config = instanceinfo[instance]
2335
      self._VerifyInstance(instance, inst_config, node_image,
2336
                           instdisk[instance])
2337
      inst_nodes_offline = []
2338

    
2339
      pnode = inst_config.primary_node
2340
      pnode_img = node_image[pnode]
2341
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2342
               self.ENODERPC, pnode, "instance %s, connection to"
2343
               " primary node failed", instance)
2344

    
2345
      _ErrorIf(pnode_img.offline, self.EINSTANCEBADNODE, instance,
2346
               "instance lives on offline node %s", inst_config.primary_node)
2347

    
2348
      # If the instance is non-redundant we cannot survive losing its primary
2349
      # node, so we are not N+1 compliant. On the other hand we have no disk
2350
      # templates with more than one secondary so that situation is not well
2351
      # supported either.
2352
      # FIXME: does not support file-backed instances
2353
      if not inst_config.secondary_nodes:
2354
        i_non_redundant.append(instance)
2355

    
2356
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2357
               instance, "instance has multiple secondary nodes: %s",
2358
               utils.CommaJoin(inst_config.secondary_nodes),
2359
               code=self.ETYPE_WARNING)
2360

    
2361
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2362
        pnode = inst_config.primary_node
2363
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2364
        instance_groups = {}
2365

    
2366
        for node in instance_nodes:
2367
          instance_groups.setdefault(nodeinfo_byname[node].group,
2368
                                     []).append(node)
2369

    
2370
        pretty_list = [
2371
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2372
          # Sort so that we always list the primary node first.
2373
          for group, nodes in sorted(instance_groups.items(),
2374
                                     key=lambda (_, nodes): pnode in nodes,
2375
                                     reverse=True)]
2376

    
2377
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2378
                      instance, "instance has primary and secondary nodes in"
2379
                      " different groups: %s", utils.CommaJoin(pretty_list),
2380
                      code=self.ETYPE_WARNING)
2381

    
2382
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2383
        i_non_a_balanced.append(instance)
2384

    
2385
      for snode in inst_config.secondary_nodes:
2386
        s_img = node_image[snode]
2387
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2388
                 "instance %s, connection to secondary node failed", instance)
2389

    
2390
        if s_img.offline:
2391
          inst_nodes_offline.append(snode)
2392

    
2393
      # warn that the instance lives on offline nodes
2394
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2395
               "instance has offline secondary node(s) %s",
2396
               utils.CommaJoin(inst_nodes_offline))
2397
      # ... or ghost/non-vm_capable nodes
2398
      for node in inst_config.all_nodes:
2399
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2400
                 "instance lives on ghost node %s", node)
2401
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2402
                 instance, "instance lives on non-vm_capable node %s", node)
2403

    
2404
    feedback_fn("* Verifying orphan volumes")
2405
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2406
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2407

    
2408
    feedback_fn("* Verifying orphan instances")
2409
    self._VerifyOrphanInstances(instancelist, node_image)
2410

    
2411
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2412
      feedback_fn("* Verifying N+1 Memory redundancy")
2413
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2414

    
2415
    feedback_fn("* Other Notes")
2416
    if i_non_redundant:
2417
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2418
                  % len(i_non_redundant))
2419

    
2420
    if i_non_a_balanced:
2421
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2422
                  % len(i_non_a_balanced))
2423

    
2424
    if n_offline:
2425
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2426

    
2427
    if n_drained:
2428
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2429

    
2430
    return not self.bad
2431

    
2432
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2433
    """Analyze the post-hooks' result
2434

2435
    This method analyses the hook result, handles it, and sends some
2436
    nicely-formatted feedback back to the user.
2437

2438
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2439
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2440
    @param hooks_results: the results of the multi-node hooks rpc call
2441
    @param feedback_fn: function used send feedback back to the caller
2442
    @param lu_result: previous Exec result
2443
    @return: the new Exec result, based on the previous result
2444
        and hook results
2445

2446
    """
2447
    # We only really run POST phase hooks, and are only interested in
2448
    # their results
2449
    if phase == constants.HOOKS_PHASE_POST:
2450
      # Used to change hooks' output to proper indentation
2451
      feedback_fn("* Hooks Results")
2452
      assert hooks_results, "invalid result from hooks"
2453

    
2454
      for node_name in hooks_results:
2455
        res = hooks_results[node_name]
2456
        msg = res.fail_msg
2457
        test = msg and not res.offline
2458
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2459
                      "Communication failure in hooks execution: %s", msg)
2460
        if res.offline or msg:
2461
          # No need to investigate payload if node is offline or gave an error.
2462
          # override manually lu_result here as _ErrorIf only
2463
          # overrides self.bad
2464
          lu_result = 1
2465
          continue
2466
        for script, hkr, output in res.payload:
2467
          test = hkr == constants.HKR_FAIL
2468
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2469
                        "Script %s failed, output:", script)
2470
          if test:
2471
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2472
            feedback_fn("%s" % output)
2473
            lu_result = 0
2474

    
2475
      return lu_result
2476

    
2477

    
2478
class LUClusterVerifyDisks(NoHooksLU):
2479
  """Verifies the cluster disks status.
2480

2481
  """
2482
  REQ_BGL = False
2483

    
2484
  def ExpandNames(self):
2485
    self.needed_locks = {
2486
      locking.LEVEL_NODE: locking.ALL_SET,
2487
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2488
    }
2489
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2490

    
2491
  def Exec(self, feedback_fn):
2492
    """Verify integrity of cluster disks.
2493

2494
    @rtype: tuple of three items
2495
    @return: a tuple of (dict of node-to-node_error, list of instances
2496
        which need activate-disks, dict of instance: (node, volume) for
2497
        missing volumes
2498

2499
    """
2500
    result = res_nodes, res_instances, res_missing = {}, [], {}
2501

    
2502
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2503
    instances = self.cfg.GetAllInstancesInfo().values()
2504

    
2505
    nv_dict = {}
2506
    for inst in instances:
2507
      inst_lvs = {}
2508
      if not inst.admin_up:
2509
        continue
2510
      inst.MapLVsByNode(inst_lvs)
2511
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2512
      for node, vol_list in inst_lvs.iteritems():
2513
        for vol in vol_list:
2514
          nv_dict[(node, vol)] = inst
2515

    
2516
    if not nv_dict:
2517
      return result
2518

    
2519
    node_lvs = self.rpc.call_lv_list(nodes, [])
2520
    for node, node_res in node_lvs.items():
2521
      if node_res.offline:
2522
        continue
2523
      msg = node_res.fail_msg
2524
      if msg:
2525
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2526
        res_nodes[node] = msg
2527
        continue
2528

    
2529
      lvs = node_res.payload
2530
      for lv_name, (_, _, lv_online) in lvs.items():
2531
        inst = nv_dict.pop((node, lv_name), None)
2532
        if (not lv_online and inst is not None
2533
            and inst.name not in res_instances):
2534
          res_instances.append(inst.name)
2535

    
2536
    # any leftover items in nv_dict are missing LVs, let's arrange the
2537
    # data better
2538
    for key, inst in nv_dict.iteritems():
2539
      if inst.name not in res_missing:
2540
        res_missing[inst.name] = []
2541
      res_missing[inst.name].append(key)
2542

    
2543
    return result
2544

    
2545

    
2546
class LUClusterRepairDiskSizes(NoHooksLU):
2547
  """Verifies the cluster disks sizes.
2548

2549
  """
2550
  REQ_BGL = False
2551

    
2552
  def ExpandNames(self):
2553
    if self.op.instances:
2554
      self.wanted_names = []
2555
      for name in self.op.instances:
2556
        full_name = _ExpandInstanceName(self.cfg, name)
2557
        self.wanted_names.append(full_name)
2558
      self.needed_locks = {
2559
        locking.LEVEL_NODE: [],
2560
        locking.LEVEL_INSTANCE: self.wanted_names,
2561
        }
2562
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2563
    else:
2564
      self.wanted_names = None
2565
      self.needed_locks = {
2566
        locking.LEVEL_NODE: locking.ALL_SET,
2567
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2568
        }
2569
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2570

    
2571
  def DeclareLocks(self, level):
2572
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2573
      self._LockInstancesNodes(primary_only=True)
2574

    
2575
  def CheckPrereq(self):
2576
    """Check prerequisites.
2577

2578
    This only checks the optional instance list against the existing names.
2579

2580
    """
2581
    if self.wanted_names is None:
2582
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2583

    
2584
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2585
                             in self.wanted_names]
2586

    
2587
  def _EnsureChildSizes(self, disk):
2588
    """Ensure children of the disk have the needed disk size.
2589

2590
    This is valid mainly for DRBD8 and fixes an issue where the
2591
    children have smaller disk size.
2592

2593
    @param disk: an L{ganeti.objects.Disk} object
2594

2595
    """
2596
    if disk.dev_type == constants.LD_DRBD8:
2597
      assert disk.children, "Empty children for DRBD8?"
2598
      fchild = disk.children[0]
2599
      mismatch = fchild.size < disk.size
2600
      if mismatch:
2601
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2602
                     fchild.size, disk.size)
2603
        fchild.size = disk.size
2604

    
2605
      # and we recurse on this child only, not on the metadev
2606
      return self._EnsureChildSizes(fchild) or mismatch
2607
    else:
2608
      return False
2609

    
2610
  def Exec(self, feedback_fn):
2611
    """Verify the size of cluster disks.
2612

2613
    """
2614
    # TODO: check child disks too
2615
    # TODO: check differences in size between primary/secondary nodes
2616
    per_node_disks = {}
2617
    for instance in self.wanted_instances:
2618
      pnode = instance.primary_node
2619
      if pnode not in per_node_disks:
2620
        per_node_disks[pnode] = []
2621
      for idx, disk in enumerate(instance.disks):
2622
        per_node_disks[pnode].append((instance, idx, disk))
2623

    
2624
    changed = []
2625
    for node, dskl in per_node_disks.items():
2626
      newl = [v[2].Copy() for v in dskl]
2627
      for dsk in newl:
2628
        self.cfg.SetDiskID(dsk, node)
2629
      result = self.rpc.call_blockdev_getsize(node, newl)
2630
      if result.fail_msg:
2631
        self.LogWarning("Failure in blockdev_getsize call to node"
2632
                        " %s, ignoring", node)
2633
        continue
2634
      if len(result.payload) != len(dskl):
2635
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2636
                        " result.payload=%s", node, len(dskl), result.payload)
2637
        self.LogWarning("Invalid result from node %s, ignoring node results",
2638
                        node)
2639
        continue
2640
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2641
        if size is None:
2642
          self.LogWarning("Disk %d of instance %s did not return size"
2643
                          " information, ignoring", idx, instance.name)
2644
          continue
2645
        if not isinstance(size, (int, long)):
2646
          self.LogWarning("Disk %d of instance %s did not return valid"
2647
                          " size information, ignoring", idx, instance.name)
2648
          continue
2649
        size = size >> 20
2650
        if size != disk.size:
2651
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2652
                       " correcting: recorded %d, actual %d", idx,
2653
                       instance.name, disk.size, size)
2654
          disk.size = size
2655
          self.cfg.Update(instance, feedback_fn)
2656
          changed.append((instance.name, idx, size))
2657
        if self._EnsureChildSizes(disk):
2658
          self.cfg.Update(instance, feedback_fn)
2659
          changed.append((instance.name, idx, disk.size))
2660
    return changed
2661

    
2662

    
2663
class LUClusterRename(LogicalUnit):
2664
  """Rename the cluster.
2665

2666
  """
2667
  HPATH = "cluster-rename"
2668
  HTYPE = constants.HTYPE_CLUSTER
2669

    
2670
  def BuildHooksEnv(self):
2671
    """Build hooks env.
2672

2673
    """
2674
    env = {
2675
      "OP_TARGET": self.cfg.GetClusterName(),
2676
      "NEW_NAME": self.op.name,
2677
      }
2678
    mn = self.cfg.GetMasterNode()
2679
    all_nodes = self.cfg.GetNodeList()
2680
    return env, [mn], all_nodes
2681

    
2682
  def CheckPrereq(self):
2683
    """Verify that the passed name is a valid one.
2684

2685
    """
2686
    hostname = netutils.GetHostname(name=self.op.name,
2687
                                    family=self.cfg.GetPrimaryIPFamily())
2688

    
2689
    new_name = hostname.name
2690
    self.ip = new_ip = hostname.ip
2691
    old_name = self.cfg.GetClusterName()
2692
    old_ip = self.cfg.GetMasterIP()
2693
    if new_name == old_name and new_ip == old_ip:
2694
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2695
                                 " cluster has changed",
2696
                                 errors.ECODE_INVAL)
2697
    if new_ip != old_ip:
2698
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2699
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2700
                                   " reachable on the network" %
2701
                                   new_ip, errors.ECODE_NOTUNIQUE)
2702

    
2703
    self.op.name = new_name
2704

    
2705
  def Exec(self, feedback_fn):
2706
    """Rename the cluster.
2707

2708
    """
2709
    clustername = self.op.name
2710
    ip = self.ip
2711

    
2712
    # shutdown the master IP
2713
    master = self.cfg.GetMasterNode()
2714
    result = self.rpc.call_node_stop_master(master, False)
2715
    result.Raise("Could not disable the master role")
2716

    
2717
    try:
2718
      cluster = self.cfg.GetClusterInfo()
2719
      cluster.cluster_name = clustername
2720
      cluster.master_ip = ip
2721
      self.cfg.Update(cluster, feedback_fn)
2722

    
2723
      # update the known hosts file
2724
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2725
      node_list = self.cfg.GetOnlineNodeList()
2726
      try:
2727
        node_list.remove(master)
2728
      except ValueError:
2729
        pass
2730
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2731
    finally:
2732
      result = self.rpc.call_node_start_master(master, False, False)
2733
      msg = result.fail_msg
2734
      if msg:
2735
        self.LogWarning("Could not re-enable the master role on"
2736
                        " the master, please restart manually: %s", msg)
2737

    
2738
    return clustername
2739

    
2740

    
2741
class LUClusterSetParams(LogicalUnit):
2742
  """Change the parameters of the cluster.
2743

2744
  """
2745
  HPATH = "cluster-modify"
2746
  HTYPE = constants.HTYPE_CLUSTER
2747
  REQ_BGL = False
2748

    
2749
  def CheckArguments(self):
2750
    """Check parameters
2751

2752
    """
2753
    if self.op.uid_pool:
2754
      uidpool.CheckUidPool(self.op.uid_pool)
2755

    
2756
    if self.op.add_uids:
2757
      uidpool.CheckUidPool(self.op.add_uids)
2758

    
2759
    if self.op.remove_uids:
2760
      uidpool.CheckUidPool(self.op.remove_uids)
2761

    
2762
  def ExpandNames(self):
2763
    # FIXME: in the future maybe other cluster params won't require checking on
2764
    # all nodes to be modified.
2765
    self.needed_locks = {
2766
      locking.LEVEL_NODE: locking.ALL_SET,
2767
    }
2768
    self.share_locks[locking.LEVEL_NODE] = 1
2769

    
2770
  def BuildHooksEnv(self):
2771
    """Build hooks env.
2772

2773
    """
2774
    env = {
2775
      "OP_TARGET": self.cfg.GetClusterName(),
2776
      "NEW_VG_NAME": self.op.vg_name,
2777
      }
2778
    mn = self.cfg.GetMasterNode()
2779
    return env, [mn], [mn]
2780

    
2781
  def CheckPrereq(self):
2782
    """Check prerequisites.
2783

2784
    This checks whether the given params don't conflict and
2785
    if the given volume group is valid.
2786

2787
    """
2788
    if self.op.vg_name is not None and not self.op.vg_name:
2789
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2790
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2791
                                   " instances exist", errors.ECODE_INVAL)
2792

    
2793
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2794
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2795
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2796
                                   " drbd-based instances exist",
2797
                                   errors.ECODE_INVAL)
2798

    
2799
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2800

    
2801
    # if vg_name not None, checks given volume group on all nodes
2802
    if self.op.vg_name:
2803
      vglist = self.rpc.call_vg_list(node_list)
2804
      for node in node_list:
2805
        msg = vglist[node].fail_msg
2806
        if msg:
2807
          # ignoring down node
2808
          self.LogWarning("Error while gathering data on node %s"
2809
                          " (ignoring node): %s", node, msg)
2810
          continue
2811
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2812
                                              self.op.vg_name,
2813
                                              constants.MIN_VG_SIZE)
2814
        if vgstatus:
2815
          raise errors.OpPrereqError("Error on node '%s': %s" %
2816
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2817

    
2818
    if self.op.drbd_helper:
2819
      # checks given drbd helper on all nodes
2820
      helpers = self.rpc.call_drbd_helper(node_list)
2821
      for node in node_list:
2822
        ninfo = self.cfg.GetNodeInfo(node)
2823
        if ninfo.offline:
2824
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2825
          continue
2826
        msg = helpers[node].fail_msg
2827
        if msg:
2828
          raise errors.OpPrereqError("Error checking drbd helper on node"
2829
                                     " '%s': %s" % (node, msg),
2830
                                     errors.ECODE_ENVIRON)
2831
        node_helper = helpers[node].payload
2832
        if node_helper != self.op.drbd_helper:
2833
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2834
                                     (node, node_helper), errors.ECODE_ENVIRON)
2835

    
2836
    self.cluster = cluster = self.cfg.GetClusterInfo()
2837
    # validate params changes
2838
    if self.op.beparams:
2839
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2840
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2841

    
2842
    if self.op.ndparams:
2843
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2844
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2845

    
2846
      # TODO: we need a more general way to handle resetting
2847
      # cluster-level parameters to default values
2848
      if self.new_ndparams["oob_program"] == "":
2849
        self.new_ndparams["oob_program"] = \
2850
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
2851

    
2852
    if self.op.nicparams:
2853
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2854
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2855
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2856
      nic_errors = []
2857

    
2858
      # check all instances for consistency
2859
      for instance in self.cfg.GetAllInstancesInfo().values():
2860
        for nic_idx, nic in enumerate(instance.nics):
2861
          params_copy = copy.deepcopy(nic.nicparams)
2862
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2863

    
2864
          # check parameter syntax
2865
          try:
2866
            objects.NIC.CheckParameterSyntax(params_filled)
2867
          except errors.ConfigurationError, err:
2868
            nic_errors.append("Instance %s, nic/%d: %s" %
2869
                              (instance.name, nic_idx, err))
2870

    
2871
          # if we're moving instances to routed, check that they have an ip
2872
          target_mode = params_filled[constants.NIC_MODE]
2873
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2874
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
2875
                              " address" % (instance.name, nic_idx))
2876
      if nic_errors:
2877
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2878
                                   "\n".join(nic_errors))
2879

    
2880
    # hypervisor list/parameters
2881
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2882
    if self.op.hvparams:
2883
      for hv_name, hv_dict in self.op.hvparams.items():
2884
        if hv_name not in self.new_hvparams:
2885
          self.new_hvparams[hv_name] = hv_dict
2886
        else:
2887
          self.new_hvparams[hv_name].update(hv_dict)
2888

    
2889
    # os hypervisor parameters
2890
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2891
    if self.op.os_hvp:
2892
      for os_name, hvs in self.op.os_hvp.items():
2893
        if os_name not in self.new_os_hvp:
2894
          self.new_os_hvp[os_name] = hvs
2895
        else:
2896
          for hv_name, hv_dict in hvs.items():
2897
            if hv_name not in self.new_os_hvp[os_name]:
2898
              self.new_os_hvp[os_name][hv_name] = hv_dict
2899
            else:
2900
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2901

    
2902
    # os parameters
2903
    self.new_osp = objects.FillDict(cluster.osparams, {})
2904
    if self.op.osparams:
2905
      for os_name, osp in self.op.osparams.items():
2906
        if os_name not in self.new_osp:
2907
          self.new_osp[os_name] = {}
2908

    
2909
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2910
                                                  use_none=True)
2911

    
2912
        if not self.new_osp[os_name]:
2913
          # we removed all parameters
2914
          del self.new_osp[os_name]
2915
        else:
2916
          # check the parameter validity (remote check)
2917
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2918
                         os_name, self.new_osp[os_name])
2919

    
2920
    # changes to the hypervisor list
2921
    if self.op.enabled_hypervisors is not None:
2922
      self.hv_list = self.op.enabled_hypervisors
2923
      for hv in self.hv_list:
2924
        # if the hypervisor doesn't already exist in the cluster
2925
        # hvparams, we initialize it to empty, and then (in both
2926
        # cases) we make sure to fill the defaults, as we might not
2927
        # have a complete defaults list if the hypervisor wasn't
2928
        # enabled before
2929
        if hv not in new_hvp:
2930
          new_hvp[hv] = {}
2931
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2932
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2933
    else:
2934
      self.hv_list = cluster.enabled_hypervisors
2935

    
2936
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2937
      # either the enabled list has changed, or the parameters have, validate
2938
      for hv_name, hv_params in self.new_hvparams.items():
2939
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2940
            (self.op.enabled_hypervisors and
2941
             hv_name in self.op.enabled_hypervisors)):
2942
          # either this is a new hypervisor, or its parameters have changed
2943
          hv_class = hypervisor.GetHypervisor(hv_name)
2944
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2945
          hv_class.CheckParameterSyntax(hv_params)
2946
          _CheckHVParams(self, node_list, hv_name, hv_params)
2947

    
2948
    if self.op.os_hvp:
2949
      # no need to check any newly-enabled hypervisors, since the
2950
      # defaults have already been checked in the above code-block
2951
      for os_name, os_hvp in self.new_os_hvp.items():
2952
        for hv_name, hv_params in os_hvp.items():
2953
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2954
          # we need to fill in the new os_hvp on top of the actual hv_p
2955
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2956
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2957
          hv_class = hypervisor.GetHypervisor(hv_name)
2958
          hv_class.CheckParameterSyntax(new_osp)
2959
          _CheckHVParams(self, node_list, hv_name, new_osp)
2960

    
2961
    if self.op.default_iallocator:
2962
      alloc_script = utils.FindFile(self.op.default_iallocator,
2963
                                    constants.IALLOCATOR_SEARCH_PATH,
2964
                                    os.path.isfile)
2965
      if alloc_script is None:
2966
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2967
                                   " specified" % self.op.default_iallocator,
2968
                                   errors.ECODE_INVAL)
2969

    
2970
  def Exec(self, feedback_fn):
2971
    """Change the parameters of the cluster.
2972

2973
    """
2974
    if self.op.vg_name is not None:
2975
      new_volume = self.op.vg_name
2976
      if not new_volume:
2977
        new_volume = None
2978
      if new_volume != self.cfg.GetVGName():
2979
        self.cfg.SetVGName(new_volume)
2980
      else:
2981
        feedback_fn("Cluster LVM configuration already in desired"
2982
                    " state, not changing")
2983
    if self.op.drbd_helper is not None:
2984
      new_helper = self.op.drbd_helper
2985
      if not new_helper:
2986
        new_helper = None
2987
      if new_helper != self.cfg.GetDRBDHelper():
2988
        self.cfg.SetDRBDHelper(new_helper)
2989
      else:
2990
        feedback_fn("Cluster DRBD helper already in desired state,"
2991
                    " not changing")
2992
    if self.op.hvparams:
2993
      self.cluster.hvparams = self.new_hvparams
2994
    if self.op.os_hvp:
2995
      self.cluster.os_hvp = self.new_os_hvp
2996
    if self.op.enabled_hypervisors is not None:
2997
      self.cluster.hvparams = self.new_hvparams
2998
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2999
    if self.op.beparams:
3000
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3001
    if self.op.nicparams:
3002
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3003
    if self.op.osparams:
3004
      self.cluster.osparams = self.new_osp
3005
    if self.op.ndparams:
3006
      self.cluster.ndparams = self.new_ndparams
3007

    
3008
    if self.op.candidate_pool_size is not None:
3009
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3010
      # we need to update the pool size here, otherwise the save will fail
3011
      _AdjustCandidatePool(self, [])
3012

    
3013
    if self.op.maintain_node_health is not None:
3014
      self.cluster.maintain_node_health = self.op.maintain_node_health
3015

    
3016
    if self.op.prealloc_wipe_disks is not None:
3017
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3018

    
3019
    if self.op.add_uids is not None:
3020
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3021

    
3022
    if self.op.remove_uids is not None:
3023
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3024

    
3025
    if self.op.uid_pool is not None:
3026
      self.cluster.uid_pool = self.op.uid_pool
3027

    
3028
    if self.op.default_iallocator is not None:
3029
      self.cluster.default_iallocator = self.op.default_iallocator
3030

    
3031
    if self.op.reserved_lvs is not None:
3032
      self.cluster.reserved_lvs = self.op.reserved_lvs
3033

    
3034
    def helper_os(aname, mods, desc):
3035
      desc += " OS list"
3036
      lst = getattr(self.cluster, aname)
3037
      for key, val in mods:
3038
        if key == constants.DDM_ADD:
3039
          if val in lst:
3040
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3041
          else:
3042
            lst.append(val)
3043
        elif key == constants.DDM_REMOVE:
3044
          if val in lst:
3045
            lst.remove(val)
3046
          else:
3047
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3048
        else:
3049
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3050

    
3051
    if self.op.hidden_os:
3052
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3053

    
3054
    if self.op.blacklisted_os:
3055
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3056

    
3057
    if self.op.master_netdev:
3058
      master = self.cfg.GetMasterNode()
3059
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3060
                  self.cluster.master_netdev)
3061
      result = self.rpc.call_node_stop_master(master, False)
3062
      result.Raise("Could not disable the master ip")
3063
      feedback_fn("Changing master_netdev from %s to %s" %
3064
                  (self.cluster.master_netdev, self.op.master_netdev))
3065
      self.cluster.master_netdev = self.op.master_netdev
3066

    
3067
    self.cfg.Update(self.cluster, feedback_fn)
3068

    
3069
    if self.op.master_netdev:
3070
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3071
                  self.op.master_netdev)
3072
      result = self.rpc.call_node_start_master(master, False, False)
3073
      if result.fail_msg:
3074
        self.LogWarning("Could not re-enable the master ip on"
3075
                        " the master, please restart manually: %s",
3076
                        result.fail_msg)
3077

    
3078

    
3079
def _UploadHelper(lu, nodes, fname):
3080
  """Helper for uploading a file and showing warnings.
3081

3082
  """
3083
  if os.path.exists(fname):
3084
    result = lu.rpc.call_upload_file(nodes, fname)
3085
    for to_node, to_result in result.items():
3086
      msg = to_result.fail_msg
3087
      if msg:
3088
        msg = ("Copy of file %s to node %s failed: %s" %
3089
               (fname, to_node, msg))
3090
        lu.proc.LogWarning(msg)
3091

    
3092

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

3096
  ConfigWriter takes care of distributing the config and ssconf files, but
3097
  there are more files which should be distributed to all nodes. This function
3098
  makes sure those are copied.
3099

3100
  @param lu: calling logical unit
3101
  @param additional_nodes: list of nodes not in the config to distribute to
3102
  @type additional_vm: boolean
3103
  @param additional_vm: whether the additional nodes are vm-capable or not
3104

3105
  """
3106
  # 1. Gather target nodes
3107
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3108
  dist_nodes = lu.cfg.GetOnlineNodeList()
3109
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
3110
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
3111
  if additional_nodes is not None:
3112
    dist_nodes.extend(additional_nodes)
3113
    if additional_vm:
3114
      vm_nodes.extend(additional_nodes)
3115
  if myself.name in dist_nodes:
3116
    dist_nodes.remove(myself.name)
3117
  if myself.name in vm_nodes:
3118
    vm_nodes.remove(myself.name)
3119

    
3120
  # 2. Gather files to distribute
3121
  dist_files = set([constants.ETC_HOSTS,
3122
                    constants.SSH_KNOWN_HOSTS_FILE,
3123
                    constants.RAPI_CERT_FILE,
3124
                    constants.RAPI_USERS_FILE,
3125
                    constants.CONFD_HMAC_KEY,
3126
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3127
                   ])
3128

    
3129
  vm_files = set()
3130
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3131
  for hv_name in enabled_hypervisors:
3132
    hv_class = hypervisor.GetHypervisor(hv_name)
3133
    vm_files.update(hv_class.GetAncillaryFiles())
3134

    
3135
  # 3. Perform the files upload
3136
  for fname in dist_files:
3137
    _UploadHelper(lu, dist_nodes, fname)
3138
  for fname in vm_files:
3139
    _UploadHelper(lu, vm_nodes, fname)
3140

    
3141

    
3142
class LUClusterRedistConf(NoHooksLU):
3143
  """Force the redistribution of cluster configuration.
3144

3145
  This is a very simple LU.
3146

3147
  """
3148
  REQ_BGL = False
3149

    
3150
  def ExpandNames(self):
3151
    self.needed_locks = {
3152
      locking.LEVEL_NODE: locking.ALL_SET,
3153
    }
3154
    self.share_locks[locking.LEVEL_NODE] = 1
3155

    
3156
  def Exec(self, feedback_fn):
3157
    """Redistribute the configuration.
3158

3159
    """
3160
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3161
    _RedistributeAncillaryFiles(self)
3162

    
3163

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

3167
  """
3168
  if not instance.disks or disks is not None and not disks:
3169
    return True
3170

    
3171
  disks = _ExpandCheckDisks(instance, disks)
3172

    
3173
  if not oneshot:
3174
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3175

    
3176
  node = instance.primary_node
3177

    
3178
  for dev in disks:
3179
    lu.cfg.SetDiskID(dev, node)
3180

    
3181
  # TODO: Convert to utils.Retry
3182

    
3183
  retries = 0
3184
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3185
  while True:
3186
    max_time = 0
3187
    done = True
3188
    cumul_degraded = False
3189
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3190
    msg = rstats.fail_msg
3191
    if msg:
3192
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3193
      retries += 1
3194
      if retries >= 10:
3195
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3196
                                 " aborting." % node)
3197
      time.sleep(6)
3198
      continue
3199
    rstats = rstats.payload
3200
    retries = 0
3201
    for i, mstat in enumerate(rstats):
3202
      if mstat is None:
3203
        lu.LogWarning("Can't compute data for node %s/%s",
3204
                           node, disks[i].iv_name)
3205
        continue
3206

    
3207
      cumul_degraded = (cumul_degraded or
3208
                        (mstat.is_degraded and mstat.sync_percent is None))
3209
      if mstat.sync_percent is not None:
3210
        done = False
3211
        if mstat.estimated_time is not None:
3212
          rem_time = ("%s remaining (estimated)" %
3213
                      utils.FormatSeconds(mstat.estimated_time))
3214
          max_time = mstat.estimated_time
3215
        else:
3216
          rem_time = "no time estimate"
3217
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3218
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3219

    
3220
    # if we're done but degraded, let's do a few small retries, to
3221
    # make sure we see a stable and not transient situation; therefore
3222
    # we force restart of the loop
3223
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3224
      logging.info("Degraded disks found, %d retries left", degr_retries)
3225
      degr_retries -= 1
3226
      time.sleep(1)
3227
      continue
3228

    
3229
    if done or oneshot:
3230
      break
3231

    
3232
    time.sleep(min(60, max_time))
3233

    
3234
  if done:
3235
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3236
  return not cumul_degraded
3237

    
3238

    
3239
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3240
  """Check that mirrors are not degraded.
3241

3242
  The ldisk parameter, if True, will change the test from the
3243
  is_degraded attribute (which represents overall non-ok status for
3244
  the device(s)) to the ldisk (representing the local storage status).
3245

3246
  """
3247
  lu.cfg.SetDiskID(dev, node)
3248

    
3249
  result = True
3250

    
3251
  if on_primary or dev.AssembleOnSecondary():
3252
    rstats = lu.rpc.call_blockdev_find(node, dev)
3253
    msg = rstats.fail_msg
3254
    if msg:
3255
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3256
      result = False
3257
    elif not rstats.payload:
3258
      lu.LogWarning("Can't find disk on node %s", node)
3259
      result = False
3260
    else:
3261
      if ldisk:
3262
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3263
      else:
3264
        result = result and not rstats.payload.is_degraded
3265

    
3266
  if dev.children:
3267
    for child in dev.children:
3268
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3269

    
3270
  return result
3271

    
3272

    
3273
class LUOobCommand(NoHooksLU):
3274
  """Logical unit for OOB handling.
3275

3276
  """
3277
  REG_BGL = False
3278

    
3279
  def CheckPrereq(self):
3280
    """Check prerequisites.
3281

3282
    This checks:
3283
     - the node exists in the configuration
3284
     - OOB is supported
3285

3286
    Any errors are signaled by raising errors.OpPrereqError.
3287

3288
    """
3289
    self.nodes = []
3290
    for node_name in self.op.node_names:
3291
      node = self.cfg.GetNodeInfo(node_name)
3292

    
3293
      if node is None:
3294
        raise errors.OpPrereqError("Node %s not found" % node_name,
3295
                                   errors.ECODE_NOENT)
3296
      else:
3297
        self.nodes.append(node)
3298

    
3299
      if (self.op.command == constants.OOB_POWER_OFF and not node.offline):
3300
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3301
                                    " not marked offline") % node_name,
3302
                                   errors.ECODE_STATE)
3303

    
3304
  def ExpandNames(self):
3305
    """Gather locks we need.
3306

3307
    """
3308
    if self.op.node_names:
3309
      self.op.node_names = [_ExpandNodeName(self.cfg, name)
3310
                            for name in self.op.node_names]
3311
    else:
3312
      self.op.node_names = self.cfg.GetNodeList()
3313

    
3314
    self.needed_locks = {
3315
      locking.LEVEL_NODE: self.op.node_names,
3316
      }
3317

    
3318
  def Exec(self, feedback_fn):
3319
    """Execute OOB and return result if we expect any.
3320

3321
    """
3322
    master_node = self.cfg.GetMasterNode()
3323
    ret = []
3324

    
3325
    for node in self.nodes:
3326
      node_entry = [(constants.RS_NORMAL, node.name)]
3327
      ret.append(node_entry)
3328

    
3329
      oob_program = _SupportsOob(self.cfg, node)
3330

    
3331
      if not oob_program:
3332
        node_entry.append((constants.RS_UNAVAIL, None))
3333
        continue
3334

    
3335
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3336
                   self.op.command, oob_program, node.name)
3337
      result = self.rpc.call_run_oob(master_node, oob_program,
3338
                                     self.op.command, node.name,
3339
                                     self.op.timeout)
3340

    
3341
      if result.fail_msg:
3342
        self.LogWarning("On node '%s' out-of-band RPC failed with: %s",
3343
                        node.name, result.fail_msg)
3344
        node_entry.append((constants.RS_NODATA, None))
3345
      else:
3346
        try:
3347
          self._CheckPayload(result)
3348
        except errors.OpExecError, err:
3349
          self.LogWarning("The payload returned by '%s' is not valid: %s",
3350
                          node.name, err)
3351
          node_entry.append((constants.RS_NODATA, None))
3352
        else:
3353
          if self.op.command == constants.OOB_HEALTH:
3354
            # For health we should log important events
3355
            for item, status in result.payload:
3356
              if status in [constants.OOB_STATUS_WARNING,
3357
                            constants.OOB_STATUS_CRITICAL]:
3358
                self.LogWarning("On node '%s' item '%s' has status '%s'",
3359
                                node.name, item, status)
3360

    
3361
          if self.op.command == constants.OOB_POWER_ON:
3362
            node.powered = True
3363
          elif self.op.command == constants.OOB_POWER_OFF:
3364
            node.powered = False
3365
          elif self.op.command == constants.OOB_POWER_STATUS:
3366
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3367
            if powered != node.powered:
3368
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3369
                               " match actual power state (%s)"), node.powered,
3370
                              node.name, powered)
3371

    
3372
          # For configuration changing commands we should update the node
3373
          if self.op.command in (constants.OOB_POWER_ON,
3374
                                 constants.OOB_POWER_OFF):
3375
            self.cfg.Update(node, feedback_fn)
3376

    
3377
          node_entry.append((constants.RS_NORMAL, result.payload))
3378

    
3379
    return ret
3380

    
3381
  def _CheckPayload(self, result):
3382
    """Checks if the payload is valid.
3383

3384
    @param result: RPC result
3385
    @raises errors.OpExecError: If payload is not valid
3386

3387
    """
3388
    errs = []
3389
    if self.op.command == constants.OOB_HEALTH:
3390
      if not isinstance(result.payload, list):
3391
        errs.append("command 'health' is expected to return a list but got %s" %
3392
                    type(result.payload))
3393
      else:
3394
        for item, status in result.payload:
3395
          if status not in constants.OOB_STATUSES:
3396
            errs.append("health item '%s' has invalid status '%s'" %
3397
                        (item, status))
3398

    
3399
    if self.op.command == constants.OOB_POWER_STATUS:
3400
      if not isinstance(result.payload, dict):
3401
        errs.append("power-status is expected to return a dict but got %s" %
3402
                    type(result.payload))
3403

    
3404
    if self.op.command in [
3405
        constants.OOB_POWER_ON,
3406
        constants.OOB_POWER_OFF,
3407
        constants.OOB_POWER_CYCLE,
3408
        ]:
3409
      if result.payload is not None:
3410
        errs.append("%s is expected to not return payload but got '%s'" %
3411
                    (self.op.command, result.payload))
3412

    
3413
    if errs:
3414
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3415
                               utils.CommaJoin(errs))
3416

    
3417

    
3418

    
3419
class LUOsDiagnose(NoHooksLU):
3420
  """Logical unit for OS diagnose/query.
3421

3422
  """
3423
  REQ_BGL = False
3424
  _HID = "hidden"
3425
  _BLK = "blacklisted"
3426
  _VLD = "valid"
3427
  _FIELDS_STATIC = utils.FieldSet()
3428
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3429
                                   "parameters", "api_versions", _HID, _BLK)
3430

    
3431
  def CheckArguments(self):
3432
    if self.op.names:
3433
      raise errors.OpPrereqError("Selective OS query not supported",
3434
                                 errors.ECODE_INVAL)
3435

    
3436
    _CheckOutputFields(static=self._FIELDS_STATIC,
3437
                       dynamic=self._FIELDS_DYNAMIC,
3438
                       selected=self.op.output_fields)
3439

    
3440
  def ExpandNames(self):
3441
    # Lock all nodes, in shared mode
3442
    # Temporary removal of locks, should be reverted later
3443
    # TODO: reintroduce locks when they are lighter-weight
3444
    self.needed_locks = {}
3445
    #self.share_locks[locking.LEVEL_NODE] = 1
3446
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3447

    
3448
  @staticmethod
3449
  def _DiagnoseByOS(rlist):
3450
    """Remaps a per-node return list into an a per-os per-node dictionary
3451

3452
    @param rlist: a map with node names as keys and OS objects as values
3453

3454
    @rtype: dict
3455
    @return: a dictionary with osnames as keys and as value another
3456
        map, with nodes as keys and tuples of (path, status, diagnose,
3457
        variants, parameters, api_versions) as values, eg::
3458

3459
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3460
                                     (/srv/..., False, "invalid api")],
3461
                           "node2": [(/srv/..., True, "", [], [])]}
3462
          }
3463

3464
    """
3465
    all_os = {}
3466
    # we build here the list of nodes that didn't fail the RPC (at RPC
3467
    # level), so that nodes with a non-responding node daemon don't
3468
    # make all OSes invalid
3469
    good_nodes = [node_name for node_name in rlist
3470
                  if not rlist[node_name].fail_msg]
3471
    for node_name, nr in rlist.items():
3472
      if nr.fail_msg or not nr.payload:
3473
        continue
3474
      for (name, path, status, diagnose, variants,
3475
           params, api_versions) in nr.payload:
3476
        if name not in all_os:
3477
          # build a list of nodes for this os containing empty lists
3478
          # for each node in node_list
3479
          all_os[name] = {}
3480
          for nname in good_nodes:
3481
            all_os[name][nname] = []
3482
        # convert params from [name, help] to (name, help)
3483
        params = [tuple(v) for v in params]
3484
        all_os[name][node_name].append((path, status, diagnose,
3485
                                        variants, params, api_versions))
3486
    return all_os
3487

    
3488
  def Exec(self, feedback_fn):
3489
    """Compute the list of OSes.
3490

3491
    """
3492
    valid_nodes = [node.name
3493
                   for node in self.cfg.GetAllNodesInfo().values()
3494
                   if not node.offline and node.vm_capable]
3495
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3496
    pol = self._DiagnoseByOS(node_data)
3497
    output = []
3498
    cluster = self.cfg.GetClusterInfo()
3499

    
3500
    for os_name in utils.NiceSort(pol.keys()):
3501
      os_data = pol[os_name]
3502
      row = []
3503
      valid = True
3504
      (variants, params, api_versions) = null_state = (set(), set(), set())
3505
      for idx, osl in enumerate(os_data.values()):
3506
        valid = bool(valid and osl and osl[0][1])
3507
        if not valid:
3508
          (variants, params, api_versions) = null_state
3509
          break
3510
        node_variants, node_params, node_api = osl[0][3:6]
3511
        if idx == 0: # first entry
3512
          variants = set(node_variants)
3513
          params = set(node_params)
3514
          api_versions = set(node_api)
3515
        else: # keep consistency
3516
          variants.intersection_update(node_variants)
3517
          params.intersection_update(node_params)
3518
          api_versions.intersection_update(node_api)
3519

    
3520
      is_hid = os_name in cluster.hidden_os
3521
      is_blk = os_name in cluster.blacklisted_os
3522
      if ((self._HID not in self.op.output_fields and is_hid) or
3523
          (self._BLK not in self.op.output_fields and is_blk) or
3524
          (self._VLD not in self.op.output_fields and not valid)):
3525
        continue
3526

    
3527
      for field in self.op.output_fields:
3528
        if field == "name":
3529
          val = os_name
3530
        elif field == self._VLD:
3531
          val = valid
3532
        elif field == "node_status":
3533
          # this is just a copy of the dict
3534
          val = {}
3535
          for node_name, nos_list in os_data.items():
3536
            val[node_name] = nos_list
3537
        elif field == "variants":
3538
          val = utils.NiceSort(list(variants))
3539
        elif field == "parameters":
3540
          val = list(params)
3541
        elif field == "api_versions":
3542
          val = list(api_versions)
3543
        elif field == self._HID:
3544
          val = is_hid
3545
        elif field == self._BLK:
3546
          val = is_blk
3547
        else:
3548
          raise errors.ParameterError(field)
3549
        row.append(val)
3550
      output.append(row)
3551

    
3552
    return output
3553

    
3554

    
3555
class LUNodeRemove(LogicalUnit):
3556
  """Logical unit for removing a node.
3557

3558
  """
3559
  HPATH = "node-remove"
3560
  HTYPE = constants.HTYPE_NODE
3561

    
3562
  def BuildHooksEnv(self):
3563
    """Build hooks env.
3564

3565
    This doesn't run on the target node in the pre phase as a failed
3566
    node would then be impossible to remove.
3567

3568
    """
3569
    env = {
3570
      "OP_TARGET": self.op.node_name,
3571
      "NODE_NAME": self.op.node_name,
3572
      }
3573
    all_nodes = self.cfg.GetNodeList()
3574
    try:
3575
      all_nodes.remove(self.op.node_name)
3576
    except ValueError:
3577
      logging.warning("Node %s which is about to be removed not found"
3578
                      " in the all nodes list", self.op.node_name)
3579
    return env, all_nodes, all_nodes
3580

    
3581
  def CheckPrereq(self):
3582
    """Check prerequisites.
3583

3584
    This checks:
3585
     - the node exists in the configuration
3586
     - it does not have primary or secondary instances
3587
     - it's not the master
3588

3589
    Any errors are signaled by raising errors.OpPrereqError.
3590

3591
    """
3592
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3593
    node = self.cfg.GetNodeInfo(self.op.node_name)
3594
    assert node is not None
3595

    
3596
    instance_list = self.cfg.GetInstanceList()
3597

    
3598
    masternode = self.cfg.GetMasterNode()
3599
    if node.name == masternode:
3600
      raise errors.OpPrereqError("Node is the master node,"
3601
                                 " you need to failover first.",
3602
                                 errors.ECODE_INVAL)
3603

    
3604
    for instance_name in instance_list:
3605
      instance = self.cfg.GetInstanceInfo(instance_name)
3606
      if node.name in instance.all_nodes:
3607
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3608
                                   " please remove first." % instance_name,
3609
                                   errors.ECODE_INVAL)
3610
    self.op.node_name = node.name
3611
    self.node = node
3612

    
3613
  def Exec(self, feedback_fn):
3614
    """Removes the node from the cluster.
3615

3616
    """
3617
    node = self.node
3618
    logging.info("Stopping the node daemon and removing configs from node %s",
3619
                 node.name)
3620

    
3621
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3622

    
3623
    # Promote nodes to master candidate as needed
3624
    _AdjustCandidatePool(self, exceptions=[node.name])
3625
    self.context.RemoveNode(node.name)
3626

    
3627
    # Run post hooks on the node before it's removed
3628
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3629
    try:
3630
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3631
    except:
3632
      # pylint: disable-msg=W0702
3633
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3634

    
3635
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3636
    msg = result.fail_msg
3637
    if msg:
3638
      self.LogWarning("Errors encountered on the remote node while leaving"
3639
                      " the cluster: %s", msg)
3640

    
3641
    # Remove node from our /etc/hosts
3642
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3643
      master_node = self.cfg.GetMasterNode()
3644
      result = self.rpc.call_etc_hosts_modify(master_node,
3645
                                              constants.ETC_HOSTS_REMOVE,
3646
                                              node.name, None)
3647
      result.Raise("Can't update hosts file with new host data")
3648
      _RedistributeAncillaryFiles(self)
3649

    
3650

    
3651
class _NodeQuery(_QueryBase):
3652
  FIELDS = query.NODE_FIELDS
3653

    
3654
  def ExpandNames(self, lu):
3655
    lu.needed_locks = {}
3656
    lu.share_locks[locking.LEVEL_NODE] = 1
3657

    
3658
    if self.names:
3659
      self.wanted = _GetWantedNodes(lu, self.names)
3660
    else:
3661
      self.wanted = locking.ALL_SET
3662

    
3663
    self.do_locking = (self.use_locking and
3664
                       query.NQ_LIVE in self.requested_data)
3665

    
3666
    if self.do_locking:
3667
      # if we don't request only static fields, we need to lock the nodes
3668
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3669

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

    
3673
  def _GetQueryData(self, lu):
3674
    """Computes the list of nodes and their attributes.
3675

3676
    """
3677
    all_info = lu.cfg.GetAllNodesInfo()
3678

    
3679
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3680

    
3681
    # Gather data as requested
3682
    if query.NQ_LIVE in self.requested_data:
3683
      # filter out non-vm_capable nodes
3684
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3685

    
3686
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3687
                                        lu.cfg.GetHypervisorType())
3688
      live_data = dict((name, nresult.payload)
3689
                       for (name, nresult) in node_data.items()
3690
                       if not nresult.fail_msg and nresult.payload)
3691
    else:
3692
      live_data = None
3693

    
3694
    if query.NQ_INST in self.requested_data:
3695
      node_to_primary = dict([(name, set()) for name in nodenames])
3696
      node_to_secondary = dict([(name, set()) for name in nodenames])
3697

    
3698
      inst_data = lu.cfg.GetAllInstancesInfo()
3699

    
3700
      for inst in inst_data.values():
3701
        if inst.primary_node in node_to_primary:
3702
          node_to_primary[inst.primary_node].add(inst.name)
3703
        for secnode in inst.secondary_nodes:
3704
          if secnode in node_to_secondary:
3705
            node_to_secondary[secnode].add(inst.name)
3706
    else:
3707
      node_to_primary = None
3708
      node_to_secondary = None
3709

    
3710
    if query.NQ_OOB in self.requested_data:
3711
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3712
                         for name, node in all_info.iteritems())
3713
    else:
3714
      oob_support = None
3715

    
3716
    if query.NQ_GROUP in self.requested_data:
3717
      groups = lu.cfg.GetAllNodeGroupsInfo()
3718
    else:
3719
      groups = {}
3720

    
3721
    return query.NodeQueryData([all_info[name] for name in nodenames],
3722
                               live_data, lu.cfg.GetMasterNode(),
3723
                               node_to_primary, node_to_secondary, groups,
3724
                               oob_support, lu.cfg.GetClusterInfo())
3725

    
3726

    
3727
class LUNodeQuery(NoHooksLU):
3728
  """Logical unit for querying nodes.
3729

3730
  """
3731
  # pylint: disable-msg=W0142
3732
  REQ_BGL = False
3733

    
3734
  def CheckArguments(self):
3735
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3736
                         self.op.use_locking)
3737

    
3738
  def ExpandNames(self):
3739
    self.nq.ExpandNames(self)
3740

    
3741
  def Exec(self, feedback_fn):
3742
    return self.nq.OldStyleQuery(self)
3743

    
3744

    
3745
class LUNodeQueryvols(NoHooksLU):
3746
  """Logical unit for getting volumes on node(s).
3747

3748
  """
3749
  REQ_BGL = False
3750
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3751
  _FIELDS_STATIC = utils.FieldSet("node")
3752

    
3753
  def CheckArguments(self):
3754
    _CheckOutputFields(static=self._FIELDS_STATIC,
3755
                       dynamic=self._FIELDS_DYNAMIC,
3756
                       selected=self.op.output_fields)
3757

    
3758
  def ExpandNames(self):
3759
    self.needed_locks = {}
3760
    self.share_locks[locking.LEVEL_NODE] = 1
3761
    if not self.op.nodes:
3762
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3763
    else:
3764
      self.needed_locks[locking.LEVEL_NODE] = \
3765
        _GetWantedNodes(self, self.op.nodes)
3766

    
3767
  def Exec(self, feedback_fn):
3768
    """Computes the list of nodes and their attributes.
3769

3770
    """
3771
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3772
    volumes = self.rpc.call_node_volumes(nodenames)
3773

    
3774
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3775
             in self.cfg.GetInstanceList()]
3776

    
3777
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3778

    
3779
    output = []
3780
    for node in nodenames:
3781
      nresult = volumes[node]
3782
      if nresult.offline:
3783
        continue
3784
      msg = nresult.fail_msg
3785
      if msg:
3786
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3787
        continue
3788

    
3789
      node_vols = nresult.payload[:]
3790
      node_vols.sort(key=lambda vol: vol['dev'])
3791

    
3792
      for vol in node_vols:
3793
        node_output = []
3794
        for field in self.op.output_fields:
3795
          if field == "node":
3796
            val = node
3797
          elif field == "phys":
3798
            val = vol['dev']
3799
          elif field == "vg":
3800
            val = vol['vg']
3801
          elif field == "name":
3802
            val = vol['name']
3803
          elif field == "size":
3804
            val = int(float(vol['size']))
3805
          elif field == "instance":
3806
            for inst in ilist:
3807
              if node not in lv_by_node[inst]:
3808
                continue
3809
              if vol['name'] in lv_by_node[inst][node]:
3810
                val = inst.name
3811
                break
3812
            else:
3813
              val = '-'
3814
          else:
3815
            raise errors.ParameterError(field)
3816
          node_output.append(str(val))
3817

    
3818
        output.append(node_output)
3819

    
3820
    return output
3821

    
3822

    
3823
class LUNodeQueryStorage(NoHooksLU):
3824
  """Logical unit for getting information on storage units on node(s).
3825

3826
  """
3827
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3828
  REQ_BGL = False
3829

    
3830
  def CheckArguments(self):
3831
    _CheckOutputFields(static=self._FIELDS_STATIC,
3832
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3833
                       selected=self.op.output_fields)
3834

    
3835
  def ExpandNames(self):
3836
    self.needed_locks = {}
3837
    self.share_locks[locking.LEVEL_NODE] = 1
3838

    
3839
    if self.op.nodes:
3840
      self.needed_locks[locking.LEVEL_NODE] = \
3841
        _GetWantedNodes(self, self.op.nodes)
3842
    else:
3843
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3844

    
3845
  def Exec(self, feedback_fn):
3846
    """Computes the list of nodes and their attributes.
3847

3848
    """
3849
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3850

    
3851
    # Always get name to sort by
3852
    if constants.SF_NAME in self.op.output_fields:
3853
      fields = self.op.output_fields[:]
3854
    else:
3855
      fields = [constants.SF_NAME] + self.op.output_fields
3856

    
3857
    # Never ask for node or type as it's only known to the LU
3858
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3859
      while extra in fields:
3860
        fields.remove(extra)
3861

    
3862
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3863
    name_idx = field_idx[constants.SF_NAME]
3864

    
3865
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3866
    data = self.rpc.call_storage_list(self.nodes,
3867
                                      self.op.storage_type, st_args,
3868
                                      self.op.name, fields)
3869

    
3870
    result = []
3871

    
3872
    for node in utils.NiceSort(self.nodes):
3873
      nresult = data[node]
3874
      if nresult.offline:
3875
        continue
3876

    
3877
      msg = nresult.fail_msg
3878
      if msg:
3879
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3880
        continue
3881

    
3882
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3883

    
3884
      for name in utils.NiceSort(rows.keys()):
3885
        row = rows[name]
3886

    
3887
        out = []
3888

    
3889
        for field in self.op.output_fields:
3890
          if field == constants.SF_NODE:
3891
            val = node
3892
          elif field == constants.SF_TYPE:
3893
            val = self.op.storage_type
3894
          elif field in field_idx:
3895
            val = row[field_idx[field]]
3896
          else:
3897
            raise errors.ParameterError(field)
3898

    
3899
          out.append(val)
3900

    
3901
        result.append(out)
3902

    
3903
    return result
3904

    
3905

    
3906
class _InstanceQuery(_QueryBase):
3907
  FIELDS = query.INSTANCE_FIELDS
3908

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

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

    
3919
    self.do_locking = (self.use_locking and
3920
                       query.IQ_LIVE in self.requested_data)
3921
    if self.do_locking:
3922
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3923
      lu.needed_locks[locking.LEVEL_NODE] = []
3924
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3925

    
3926
  def DeclareLocks(self, lu, level):
3927
    if level == locking.LEVEL_NODE and self.do_locking:
3928
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3929

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

3933
    """
3934
    cluster = lu.cfg.GetClusterInfo()
3935
    all_info = lu.cfg.GetAllInstancesInfo()
3936

    
3937
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3938

    
3939
    instance_list = [all_info[name] for name in instance_names]
3940
    nodes = frozenset(itertools.chain(*(inst.all_nodes
3941
                                        for inst in instance_list)))
3942
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3943
    bad_nodes = []
3944
    offline_nodes = []
3945
    wrongnode_inst = set()
3946

    
3947
    # Gather data as requested
3948
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
3949
      live_data = {}
3950
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
3951
      for name in nodes:
3952
        result = node_data[name]
3953
        if result.offline:
3954
          # offline nodes will be in both lists
3955
          assert result.fail_msg
3956
          offline_nodes.append(name)
3957
        if result.fail_msg:
3958
          bad_nodes.append(name)
3959
        elif result.payload:
3960
          for inst in result.payload:
3961
            if inst in all_info:
3962
              if all_info[inst].primary_node == name:
3963
                live_data.update(result.payload)
3964
              else:
3965
                wrongnode_inst.add(inst)
3966
            else:
3967
              # orphan instance; we don't list it here as we don't
3968
              # handle this case yet in the output of instance listing
3969
              logging.warning("Orphan instance '%s' found on node %s",
3970
                              inst, name)
3971
        # else no instance is alive
3972
    else:
3973
      live_data = {}
3974

    
3975
    if query.IQ_DISKUSAGE in self.requested_data:
3976
      disk_usage = dict((inst.name,
3977
                         _ComputeDiskSize(inst.disk_template,
3978
                                          [{"size": disk.size}
3979
                                           for disk in inst.disks]))
3980
                        for inst in instance_list)
3981
    else:
3982
      disk_usage = None
3983

    
3984
    if query.IQ_CONSOLE in self.requested_data:
3985
      consinfo = {}
3986
      for inst in instance_list:
3987
        if inst.name in live_data:
3988
          # Instance is running
3989
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
3990
        else:
3991
          consinfo[inst.name] = None
3992
      assert set(consinfo.keys()) == set(instance_names)
3993
    else:
3994
      consinfo = None
3995

    
3996
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
3997
                                   disk_usage, offline_nodes, bad_nodes,
3998
                                   live_data, wrongnode_inst, consinfo)
3999

    
4000

    
4001
class LUQuery(NoHooksLU):
4002
  """Query for resources/items of a certain kind.
4003

4004
  """
4005
  # pylint: disable-msg=W0142
4006
  REQ_BGL = False
4007

    
4008
  def CheckArguments(self):
4009
    qcls = _GetQueryImplementation(self.op.what)
4010
    names = qlang.ReadSimpleFilter("name", self.op.filter)
4011

    
4012
    self.impl = qcls(names, self.op.fields, False)
4013

    
4014
  def ExpandNames(self):
4015
    self.impl.ExpandNames(self)
4016

    
4017
  def DeclareLocks(self, level):
4018
    self.impl.DeclareLocks(self, level)
4019

    
4020
  def Exec(self, feedback_fn):
4021
    return self.impl.NewStyleQuery(self)
4022

    
4023

    
4024
class LUQueryFields(NoHooksLU):
4025
  """Query for resources/items of a certain kind.
4026

4027
  """
4028
  # pylint: disable-msg=W0142
4029
  REQ_BGL = False
4030

    
4031
  def CheckArguments(self):
4032
    self.qcls = _GetQueryImplementation(self.op.what)
4033

    
4034
  def ExpandNames(self):
4035
    self.needed_locks = {}
4036

    
4037
  def Exec(self, feedback_fn):
4038
    return self.qcls.FieldsQuery(self.op.fields)
4039

    
4040

    
4041
class LUNodeModifyStorage(NoHooksLU):
4042
  """Logical unit for modifying a storage volume on a node.
4043

4044
  """
4045
  REQ_BGL = False
4046

    
4047
  def CheckArguments(self):
4048
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4049

    
4050
    storage_type = self.op.storage_type
4051

    
4052
    try:
4053
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4054
    except KeyError:
4055
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4056
                                 " modified" % storage_type,
4057
                                 errors.ECODE_INVAL)
4058

    
4059
    diff = set(self.op.changes.keys()) - modifiable
4060
    if diff:
4061
      raise errors.OpPrereqError("The following fields can not be modified for"
4062
                                 " storage units of type '%s': %r" %
4063
                                 (storage_type, list(diff)),
4064
                                 errors.ECODE_INVAL)
4065

    
4066
  def ExpandNames(self):
4067
    self.needed_locks = {
4068
      locking.LEVEL_NODE: self.op.node_name,
4069
      }
4070

    
4071
  def Exec(self, feedback_fn):
4072
    """Computes the list of nodes and their attributes.
4073

4074
    """
4075
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4076
    result = self.rpc.call_storage_modify(self.op.node_name,
4077
                                          self.op.storage_type, st_args,
4078
                                          self.op.name, self.op.changes)
4079
    result.Raise("Failed to modify storage unit '%s' on %s" %
4080
                 (self.op.name, self.op.node_name))
4081

    
4082

    
4083
class LUNodeAdd(LogicalUnit):
4084
  """Logical unit for adding node to the cluster.
4085

4086
  """
4087
  HPATH = "node-add"
4088
  HTYPE = constants.HTYPE_NODE
4089
  _NFLAGS = ["master_capable", "vm_capable"]
4090

    
4091
  def CheckArguments(self):
4092
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4093
    # validate/normalize the node name
4094
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4095
                                         family=self.primary_ip_family)
4096
    self.op.node_name = self.hostname.name
4097

    
4098
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4099
      raise errors.OpPrereqError("Cannot readd the master node",
4100
                                 errors.ECODE_STATE)
4101

    
4102
    if self.op.readd and self.op.group:
4103
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4104
                                 " being readded", errors.ECODE_INVAL)
4105

    
4106
  def BuildHooksEnv(self):
4107
    """Build hooks env.
4108

4109
    This will run on all nodes before, and on all nodes + the new node after.
4110

4111
    """
4112
    env = {
4113
      "OP_TARGET": self.op.node_name,
4114
      "NODE_NAME": self.op.node_name,
4115
      "NODE_PIP": self.op.primary_ip,
4116
      "NODE_SIP": self.op.secondary_ip,
4117
      "MASTER_CAPABLE": str(self.op.master_capable),
4118
      "VM_CAPABLE": str(self.op.vm_capable),
4119
      }
4120
    nodes_0 = self.cfg.GetNodeList()
4121
    nodes_1 = nodes_0 + [self.op.node_name, ]
4122
    return env, nodes_0, nodes_1
4123

    
4124
  def CheckPrereq(self):
4125
    """Check prerequisites.
4126

4127
    This checks:
4128
     - the new node is not already in the config
4129
     - it is resolvable
4130
     - its parameters (single/dual homed) matches the cluster
4131

4132
    Any errors are signaled by raising errors.OpPrereqError.
4133

4134
    """
4135
    cfg = self.cfg
4136
    hostname = self.hostname
4137
    node = hostname.name
4138
    primary_ip = self.op.primary_ip = hostname.ip
4139
    if self.op.secondary_ip is None:
4140
      if self.primary_ip_family == netutils.IP6Address.family:
4141
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4142
                                   " IPv4 address must be given as secondary",
4143
                                   errors.ECODE_INVAL)
4144
      self.op.secondary_ip = primary_ip
4145

    
4146
    secondary_ip = self.op.secondary_ip
4147
    if not netutils.IP4Address.IsValid(secondary_ip):
4148
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4149
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4150

    
4151
    node_list = cfg.GetNodeList()
4152
    if not self.op.readd and node in node_list:
4153
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4154
                                 node, errors.ECODE_EXISTS)
4155
    elif self.op.readd and node not in node_list:
4156
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4157
                                 errors.ECODE_NOENT)
4158

    
4159
    self.changed_primary_ip = False
4160

    
4161
    for existing_node_name in node_list:
4162
      existing_node = cfg.GetNodeInfo(existing_node_name)
4163

    
4164
      if self.op.readd and node == existing_node_name:
4165
        if existing_node.secondary_ip != secondary_ip:
4166
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4167
                                     " address configuration as before",
4168
                                     errors.ECODE_INVAL)
4169
        if existing_node.primary_ip != primary_ip:
4170
          self.changed_primary_ip = True
4171

    
4172
        continue
4173

    
4174
      if (existing_node.primary_ip == primary_ip or
4175
          existing_node.secondary_ip == primary_ip or
4176
          existing_node.primary_ip == secondary_ip or
4177
          existing_node.secondary_ip == secondary_ip):
4178
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4179
                                   " existing node %s" % existing_node.name,
4180
                                   errors.ECODE_NOTUNIQUE)
4181

    
4182
    # After this 'if' block, None is no longer a valid value for the
4183
    # _capable op attributes
4184
    if self.op.readd:
4185
      old_node = self.cfg.GetNodeInfo(node)
4186
      assert old_node is not None, "Can't retrieve locked node %s" % node
4187
      for attr in self._NFLAGS:
4188
        if getattr(self.op, attr) is None:
4189
          setattr(self.op, attr, getattr(old_node, attr))
4190
    else:
4191
      for attr in self._NFLAGS:
4192
        if getattr(self.op, attr) is None:
4193
          setattr(self.op, attr, True)
4194

    
4195
    if self.op.readd and not self.op.vm_capable:
4196
      pri, sec = cfg.GetNodeInstances(node)
4197
      if pri or sec:
4198
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4199
                                   " flag set to false, but it already holds"
4200
                                   " instances" % node,
4201
                                   errors.ECODE_STATE)
4202

    
4203
    # check that the type of the node (single versus dual homed) is the
4204
    # same as for the master
4205
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4206
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4207
    newbie_singlehomed = secondary_ip == primary_ip
4208
    if master_singlehomed != newbie_singlehomed:
4209
      if master_singlehomed:
4210
        raise errors.OpPrereqError("The master has no secondary ip but the"
4211
                                   " new node has one",
4212
                                   errors.ECODE_INVAL)
4213
      else:
4214
        raise errors.OpPrereqError("The master has a secondary ip but the"
4215
                                   " new node doesn't have one",
4216
                                   errors.ECODE_INVAL)
4217

    
4218
    # checks reachability
4219
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4220
      raise errors.OpPrereqError("Node not reachable by ping",
4221
                                 errors.ECODE_ENVIRON)
4222

    
4223
    if not newbie_singlehomed:
4224
      # check reachability from my secondary ip to newbie's secondary ip
4225
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4226
                           source=myself.secondary_ip):
4227
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4228
                                   " based ping to node daemon port",
4229
                                   errors.ECODE_ENVIRON)
4230

    
4231
    if self.op.readd:
4232
      exceptions = [node]
4233
    else:
4234
      exceptions = []
4235

    
4236
    if self.op.master_capable:
4237
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4238
    else:
4239
      self.master_candidate = False
4240

    
4241
    if self.op.readd:
4242
      self.new_node = old_node
4243
    else:
4244
      node_group = cfg.LookupNodeGroup(self.op.group)
4245
      self.new_node = objects.Node(name=node,
4246
                                   primary_ip=primary_ip,
4247
                                   secondary_ip=secondary_ip,
4248
                                   master_candidate=self.master_candidate,
4249
                                   offline=False, drained=False,
4250
                                   group=node_group)
4251

    
4252
    if self.op.ndparams:
4253
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4254

    
4255
  def Exec(self, feedback_fn):
4256
    """Adds the new node to the cluster.
4257

4258
    """
4259
    new_node = self.new_node
4260
    node = new_node.name
4261

    
4262
    # We adding a new node so we assume it's powered
4263
    new_node.powered = True
4264

    
4265
    # for re-adds, reset the offline/drained/master-candidate flags;
4266
    # we need to reset here, otherwise offline would prevent RPC calls
4267
    # later in the procedure; this also means that if the re-add
4268
    # fails, we are left with a non-offlined, broken node
4269
    if self.op.readd:
4270
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4271
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4272
      # if we demote the node, we do cleanup later in the procedure
4273
      new_node.master_candidate = self.master_candidate
4274
      if self.changed_primary_ip:
4275
        new_node.primary_ip = self.op.primary_ip
4276

    
4277
    # copy the master/vm_capable flags
4278
    for attr in self._NFLAGS:
4279
      setattr(new_node, attr, getattr(self.op, attr))
4280

    
4281
    # notify the user about any possible mc promotion
4282
    if new_node.master_candidate:
4283
      self.LogInfo("Node will be a master candidate")
4284

    
4285
    if self.op.ndparams:
4286
      new_node.ndparams = self.op.ndparams
4287
    else:
4288
      new_node.ndparams = {}
4289

    
4290
    # check connectivity
4291
    result = self.rpc.call_version([node])[node]
4292
    result.Raise("Can't get version information from node %s" % node)
4293
    if constants.PROTOCOL_VERSION == result.payload:
4294
      logging.info("Communication to node %s fine, sw version %s match",
4295
                   node, result.payload)
4296
    else:
4297
      raise errors.OpExecError("Version mismatch master version %s,"
4298
                               " node version %s" %
4299
                               (constants.PROTOCOL_VERSION, result.payload))
4300

    
4301
    # Add node to our /etc/hosts, and add key to known_hosts
4302
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4303
      master_node = self.cfg.GetMasterNode()
4304
      result = self.rpc.call_etc_hosts_modify(master_node,
4305
                                              constants.ETC_HOSTS_ADD,
4306
                                              self.hostname.name,
4307
                                              self.hostname.ip)
4308
      result.Raise("Can't update hosts file with new host data")
4309

    
4310
    if new_node.secondary_ip != new_node.primary_ip:
4311
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4312
                               False)
4313

    
4314
    node_verify_list = [self.cfg.GetMasterNode()]
4315
    node_verify_param = {
4316
      constants.NV_NODELIST: [node],
4317
      # TODO: do a node-net-test as well?
4318
    }
4319

    
4320
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4321
                                       self.cfg.GetClusterName())
4322
    for verifier in node_verify_list:
4323
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4324
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4325
      if nl_payload:
4326
        for failed in nl_payload:
4327
          feedback_fn("ssh/hostname verification failed"
4328
                      " (checking from %s): %s" %
4329
                      (verifier, nl_payload[failed]))
4330
        raise errors.OpExecError("ssh/hostname verification failed")
4331

    
4332
    if self.op.readd:
4333
      _RedistributeAncillaryFiles(self)
4334
      self.context.ReaddNode(new_node)
4335
      # make sure we redistribute the config
4336
      self.cfg.Update(new_node, feedback_fn)
4337
      # and make sure the new node will not have old files around
4338
      if not new_node.master_candidate:
4339
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4340
        msg = result.fail_msg
4341
        if msg:
4342
          self.LogWarning("Node failed to demote itself from master"
4343
                          " candidate status: %s" % msg)
4344
    else:
4345
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4346
                                  additional_vm=self.op.vm_capable)
4347
      self.context.AddNode(new_node, self.proc.GetECId())
4348

    
4349

    
4350
class LUNodeSetParams(LogicalUnit):
4351
  """Modifies the parameters of a node.
4352

4353
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4354
      to the node role (as _ROLE_*)
4355
  @cvar _R2F: a dictionary from node role to tuples of flags
4356
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4357

4358
  """
4359
  HPATH = "node-modify"
4360
  HTYPE = constants.HTYPE_NODE
4361
  REQ_BGL = False
4362
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4363
  _F2R = {
4364
    (True, False, False): _ROLE_CANDIDATE,
4365
    (False, True, False): _ROLE_DRAINED,
4366
    (False, False, True): _ROLE_OFFLINE,
4367
    (False, False, False): _ROLE_REGULAR,
4368
    }
4369
  _R2F = dict((v, k) for k, v in _F2R.items())
4370
  _FLAGS = ["master_candidate", "drained", "offline"]
4371

    
4372
  def CheckArguments(self):
4373
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4374
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4375
                self.op.master_capable, self.op.vm_capable,
4376
                self.op.secondary_ip, self.op.ndparams]
4377
    if all_mods.count(None) == len(all_mods):
4378
      raise errors.OpPrereqError("Please pass at least one modification",
4379
                                 errors.ECODE_INVAL)
4380
    if all_mods.count(True) > 1:
4381
      raise errors.OpPrereqError("Can't set the node into more than one"
4382
                                 " state at the same time",
4383
                                 errors.ECODE_INVAL)
4384

    
4385
    # Boolean value that tells us whether we might be demoting from MC
4386
    self.might_demote = (self.op.master_candidate == False or
4387
                         self.op.offline == True or
4388
                         self.op.drained == True or
4389
                         self.op.master_capable == False)
4390

    
4391
    if self.op.secondary_ip:
4392
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4393
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4394
                                   " address" % self.op.secondary_ip,
4395
                                   errors.ECODE_INVAL)
4396

    
4397
    self.lock_all = self.op.auto_promote and self.might_demote
4398
    self.lock_instances = self.op.secondary_ip is not None
4399

    
4400
  def ExpandNames(self):
4401
    if self.lock_all:
4402
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4403
    else:
4404
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4405

    
4406
    if self.lock_instances:
4407
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4408

    
4409
  def DeclareLocks(self, level):
4410
    # If we have locked all instances, before waiting to lock nodes, release
4411
    # all the ones living on nodes unrelated to the current operation.
4412
    if level == locking.LEVEL_NODE and self.lock_instances:
4413
      instances_release = []
4414
      instances_keep = []
4415
      self.affected_instances = []
4416
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4417
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4418
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4419
          i_mirrored = instance.disk_template in constants.DTS_INT_MIRROR
4420
          if i_mirrored and self.op.node_name in instance.all_nodes:
4421
            instances_keep.append(instance_name)
4422
            self.affected_instances.append(instance)
4423
          else:
4424
            instances_release.append(instance_name)
4425
        if instances_release:
4426
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4427
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4428

    
4429
  def BuildHooksEnv(self):
4430
    """Build hooks env.
4431

4432
    This runs on the master node.
4433

4434
    """
4435
    env = {
4436
      "OP_TARGET": self.op.node_name,
4437
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4438
      "OFFLINE": str(self.op.offline),
4439
      "DRAINED": str(self.op.drained),
4440
      "MASTER_CAPABLE": str(self.op.master_capable),
4441
      "VM_CAPABLE": str(self.op.vm_capable),
4442
      }
4443
    nl = [self.cfg.GetMasterNode(),
4444
          self.op.node_name]
4445
    return env, nl, nl
4446

    
4447
  def CheckPrereq(self):
4448
    """Check prerequisites.
4449

4450
    This only checks the instance list against the existing names.
4451

4452
    """
4453
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4454

    
4455
    if (self.op.master_candidate is not None or
4456
        self.op.drained is not None or
4457
        self.op.offline is not None):
4458
      # we can't change the master's node flags
4459
      if self.op.node_name == self.cfg.GetMasterNode():
4460
        raise errors.OpPrereqError("The master role can be changed"
4461
                                   " only via master-failover",
4462
                                   errors.ECODE_INVAL)
4463

    
4464
    if self.op.master_candidate and not node.master_capable:
4465
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4466
                                 " it a master candidate" % node.name,
4467
                                 errors.ECODE_STATE)
4468

    
4469
    if self.op.vm_capable == False:
4470
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4471
      if ipri or isec:
4472
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4473
                                   " the vm_capable flag" % node.name,
4474
                                   errors.ECODE_STATE)
4475

    
4476
    if node.master_candidate and self.might_demote and not self.lock_all:
4477
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4478
      # check if after removing the current node, we're missing master
4479
      # candidates
4480
      (mc_remaining, mc_should, _) = \
4481
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4482
      if mc_remaining < mc_should:
4483
        raise errors.OpPrereqError("Not enough master candidates, please"
4484
                                   " pass auto promote option to allow"
4485
                                   " promotion", errors.ECODE_STATE)
4486

    
4487
    self.old_flags = old_flags = (node.master_candidate,
4488
                                  node.drained, node.offline)
4489
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4490
    self.old_role = old_role = self._F2R[old_flags]
4491

    
4492
    # Check for ineffective changes
4493
    for attr in self._FLAGS:
4494
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4495
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4496
        setattr(self.op, attr, None)
4497

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

    
4501
    # TODO: We might query the real power state if it supports OOB
4502
    if _SupportsOob(self.cfg, node):
4503
      if self.op.offline is False and not (node.powered or
4504
                                           self.op.powered == True):
4505
        raise errors.OpPrereqError(("Please power on node %s first before you"
4506
                                    " can reset offline state") %
4507
                                   self.op.node_name)
4508
    elif self.op.powered is not None:
4509
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4510
                                  " which does not support out-of-band"
4511
                                  " handling") % self.op.node_name)
4512

    
4513
    # If we're being deofflined/drained, we'll MC ourself if needed
4514
    if (self.op.drained == False or self.op.offline == False or
4515
        (self.op.master_capable and not node.master_capable)):
4516
      if _DecideSelfPromotion(self):
4517
        self.op.master_candidate = True
4518
        self.LogInfo("Auto-promoting node to master candidate")
4519

    
4520
    # If we're no longer master capable, we'll demote ourselves from MC
4521
    if self.op.master_capable == False and node.master_candidate:
4522
      self.LogInfo("Demoting from master candidate")
4523
      self.op.master_candidate = False
4524

    
4525
    # Compute new role
4526
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4527
    if self.op.master_candidate:
4528
      new_role = self._ROLE_CANDIDATE
4529
    elif self.op.drained:
4530
      new_role = self._ROLE_DRAINED
4531
    elif self.op.offline:
4532
      new_role = self._ROLE_OFFLINE
4533
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4534
      # False is still in new flags, which means we're un-setting (the
4535
      # only) True flag
4536
      new_role = self._ROLE_REGULAR
4537
    else: # no new flags, nothing, keep old role
4538
      new_role = old_role
4539

    
4540
    self.new_role = new_role
4541

    
4542
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4543
      # Trying to transition out of offline status
4544
      result = self.rpc.call_version([node.name])[node.name]
4545
      if result.fail_msg:
4546
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4547
                                   " to report its version: %s" %
4548
                                   (node.name, result.fail_msg),
4549
                                   errors.ECODE_STATE)
4550
      else:
4551
        self.LogWarning("Transitioning node from offline to online state"
4552
                        " without using re-add. Please make sure the node"
4553
                        " is healthy!")
4554

    
4555
    if self.op.secondary_ip:
4556
      # Ok even without locking, because this can't be changed by any LU
4557
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4558
      master_singlehomed = master.secondary_ip == master.primary_ip
4559
      if master_singlehomed and self.op.secondary_ip:
4560
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4561
                                   " homed cluster", errors.ECODE_INVAL)
4562

    
4563
      if node.offline:
4564
        if self.affected_instances:
4565
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4566
                                     " node has instances (%s) configured"
4567
                                     " to use it" % self.affected_instances)
4568
      else:
4569
        # On online nodes, check that no instances are running, and that
4570
        # the node has the new ip and we can reach it.
4571
        for instance in self.affected_instances:
4572
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4573

    
4574
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4575
        if master.name != node.name:
4576
          # check reachability from master secondary ip to new secondary ip
4577
          if not netutils.TcpPing(self.op.secondary_ip,
4578
                                  constants.DEFAULT_NODED_PORT,
4579
                                  source=master.secondary_ip):
4580
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4581
                                       " based ping to node daemon port",
4582
                                       errors.ECODE_ENVIRON)
4583

    
4584
    if self.op.ndparams:
4585
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4586
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4587
      self.new_ndparams = new_ndparams
4588

    
4589
  def Exec(self, feedback_fn):
4590
    """Modifies a node.
4591

4592
    """
4593
    node = self.node
4594
    old_role = self.old_role
4595
    new_role = self.new_role
4596

    
4597
    result = []
4598

    
4599
    if self.op.ndparams:
4600
      node.ndparams = self.new_ndparams
4601

    
4602
    if self.op.powered is not None:
4603
      node.powered = self.op.powered
4604

    
4605
    for attr in ["master_capable", "vm_capable"]:
4606
      val = getattr(self.op, attr)
4607
      if val is not None:
4608
        setattr(node, attr, val)
4609
        result.append((attr, str(val)))
4610

    
4611
    if new_role != old_role:
4612
      # Tell the node to demote itself, if no longer MC and not offline
4613
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4614
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4615
        if msg:
4616
          self.LogWarning("Node failed to demote itself: %s", msg)
4617

    
4618
      new_flags = self._R2F[new_role]
4619
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4620
        if of != nf:
4621
          result.append((desc, str(nf)))
4622
      (node.master_candidate, node.drained, node.offline) = new_flags
4623

    
4624
      # we locked all nodes, we adjust the CP before updating this node
4625
      if self.lock_all:
4626
        _AdjustCandidatePool(self, [node.name])
4627

    
4628
    if self.op.secondary_ip:
4629
      node.secondary_ip = self.op.secondary_ip
4630
      result.append(("secondary_ip", self.op.secondary_ip))
4631

    
4632
    # this will trigger configuration file update, if needed
4633
    self.cfg.Update(node, feedback_fn)
4634

    
4635
    # this will trigger job queue propagation or cleanup if the mc
4636
    # flag changed
4637
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4638
      self.context.ReaddNode(node)
4639

    
4640
    return result
4641

    
4642

    
4643
class LUNodePowercycle(NoHooksLU):
4644
  """Powercycles a node.
4645

4646
  """
4647
  REQ_BGL = False
4648

    
4649
  def CheckArguments(self):
4650
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4651
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4652
      raise errors.OpPrereqError("The node is the master and the force"
4653
                                 " parameter was not set",
4654
                                 errors.ECODE_INVAL)
4655

    
4656
  def ExpandNames(self):
4657
    """Locking for PowercycleNode.
4658

4659
    This is a last-resort option and shouldn't block on other
4660
    jobs. Therefore, we grab no locks.
4661

4662
    """
4663
    self.needed_locks = {}
4664

    
4665
  def Exec(self, feedback_fn):
4666
    """Reboots a node.
4667

4668
    """
4669
    result = self.rpc.call_node_powercycle(self.op.node_name,
4670
                                           self.cfg.GetHypervisorType())
4671
    result.Raise("Failed to schedule the reboot")
4672
    return result.payload
4673

    
4674

    
4675
class LUClusterQuery(NoHooksLU):
4676
  """Query cluster configuration.
4677

4678
  """
4679
  REQ_BGL = False
4680

    
4681
  def ExpandNames(self):
4682
    self.needed_locks = {}
4683

    
4684
  def Exec(self, feedback_fn):
4685
    """Return cluster config.
4686

4687
    """
4688
    cluster = self.cfg.GetClusterInfo()
4689
    os_hvp = {}
4690

    
4691
    # Filter just for enabled hypervisors
4692
    for os_name, hv_dict in cluster.os_hvp.items():
4693
      os_hvp[os_name] = {}
4694
      for hv_name, hv_params in hv_dict.items():
4695
        if hv_name in cluster.enabled_hypervisors:
4696
          os_hvp[os_name][hv_name] = hv_params
4697

    
4698
    # Convert ip_family to ip_version
4699
    primary_ip_version = constants.IP4_VERSION
4700
    if cluster.primary_ip_family == netutils.IP6Address.family:
4701
      primary_ip_version = constants.IP6_VERSION
4702

    
4703
    result = {
4704
      "software_version": constants.RELEASE_VERSION,
4705
      "protocol_version": constants.PROTOCOL_VERSION,
4706
      "config_version": constants.CONFIG_VERSION,
4707
      "os_api_version": max(constants.OS_API_VERSIONS),
4708
      "export_version": constants.EXPORT_VERSION,
4709
      "architecture": (platform.architecture()[0], platform.machine()),
4710
      "name": cluster.cluster_name,
4711
      "master": cluster.master_node,
4712
      "default_hypervisor": cluster.enabled_hypervisors[0],
4713
      "enabled_hypervisors": cluster.enabled_hypervisors,
4714
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4715
                        for hypervisor_name in cluster.enabled_hypervisors]),
4716
      "os_hvp": os_hvp,
4717
      "beparams": cluster.beparams,
4718
      "osparams": cluster.osparams,
4719
      "nicparams": cluster.nicparams,
4720
      "ndparams": cluster.ndparams,
4721
      "candidate_pool_size": cluster.candidate_pool_size,
4722
      "master_netdev": cluster.master_netdev,
4723
      "volume_group_name": cluster.volume_group_name,
4724
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4725
      "file_storage_dir": cluster.file_storage_dir,
4726
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
4727
      "maintain_node_health": cluster.maintain_node_health,
4728
      "ctime": cluster.ctime,
4729
      "mtime": cluster.mtime,
4730
      "uuid": cluster.uuid,
4731
      "tags": list(cluster.GetTags()),
4732
      "uid_pool": cluster.uid_pool,
4733
      "default_iallocator": cluster.default_iallocator,
4734
      "reserved_lvs": cluster.reserved_lvs,
4735
      "primary_ip_version": primary_ip_version,
4736
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4737
      "hidden_os": cluster.hidden_os,
4738
      "blacklisted_os": cluster.blacklisted_os,
4739
      }
4740

    
4741
    return result
4742

    
4743

    
4744
class LUClusterConfigQuery(NoHooksLU):
4745
  """Return configuration values.
4746

4747
  """
4748
  REQ_BGL = False
4749
  _FIELDS_DYNAMIC = utils.FieldSet()
4750
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4751
                                  "watcher_pause", "volume_group_name")
4752

    
4753
  def CheckArguments(self):
4754
    _CheckOutputFields(static=self._FIELDS_STATIC,
4755
                       dynamic=self._FIELDS_DYNAMIC,
4756
                       selected=self.op.output_fields)
4757

    
4758
  def ExpandNames(self):
4759
    self.needed_locks = {}
4760

    
4761
  def Exec(self, feedback_fn):
4762
    """Dump a representation of the cluster config to the standard output.
4763

4764
    """
4765
    values = []
4766
    for field in self.op.output_fields:
4767
      if field == "cluster_name":
4768
        entry = self.cfg.GetClusterName()
4769
      elif field == "master_node":
4770
        entry = self.cfg.GetMasterNode()
4771
      elif field == "drain_flag":
4772
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4773
      elif field == "watcher_pause":
4774
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4775
      elif field == "volume_group_name":
4776
        entry = self.cfg.GetVGName()
4777
      else:
4778
        raise errors.ParameterError(field)
4779
      values.append(entry)
4780
    return values
4781

    
4782

    
4783
class LUInstanceActivateDisks(NoHooksLU):
4784
  """Bring up an instance's disks.
4785

4786
  """
4787
  REQ_BGL = False
4788

    
4789
  def ExpandNames(self):
4790
    self._ExpandAndLockInstance()
4791
    self.needed_locks[locking.LEVEL_NODE] = []
4792
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4793

    
4794
  def DeclareLocks(self, level):
4795
    if level == locking.LEVEL_NODE:
4796
      self._LockInstancesNodes()
4797

    
4798
  def CheckPrereq(self):
4799
    """Check prerequisites.
4800

4801
    This checks that the instance is in the cluster.
4802

4803
    """
4804
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4805
    assert self.instance is not None, \
4806
      "Cannot retrieve locked instance %s" % self.op.instance_name
4807
    _CheckNodeOnline(self, self.instance.primary_node)
4808

    
4809
  def Exec(self, feedback_fn):
4810
    """Activate the disks.
4811

4812
    """
4813
    disks_ok, disks_info = \
4814
              _AssembleInstanceDisks(self, self.instance,
4815
                                     ignore_size=self.op.ignore_size)
4816
    if not disks_ok:
4817
      raise errors.OpExecError("Cannot activate block devices")
4818

    
4819
    return disks_info
4820

    
4821

    
4822
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4823
                           ignore_size=False):
4824
  """Prepare the block devices for an instance.
4825

4826
  This sets up the block devices on all nodes.
4827

4828
  @type lu: L{LogicalUnit}
4829
  @param lu: the logical unit on whose behalf we execute
4830
  @type instance: L{objects.Instance}
4831
  @param instance: the instance for whose disks we assemble
4832
  @type disks: list of L{objects.Disk} or None
4833
  @param disks: which disks to assemble (or all, if None)
4834
  @type ignore_secondaries: boolean
4835
  @param ignore_secondaries: if true, errors on secondary nodes
4836
      won't result in an error return from the function
4837
  @type ignore_size: boolean
4838
  @param ignore_size: if true, the current known size of the disk
4839
      will not be used during the disk activation, useful for cases
4840
      when the size is wrong
4841
  @return: False if the operation failed, otherwise a list of
4842
      (host, instance_visible_name, node_visible_name)
4843
      with the mapping from node devices to instance devices
4844

4845
  """
4846
  device_info = []
4847
  disks_ok = True
4848
  iname = instance.name
4849
  disks = _ExpandCheckDisks(instance, disks)
4850

    
4851
  # With the two passes mechanism we try to reduce the window of
4852
  # opportunity for the race condition of switching DRBD to primary
4853
  # before handshaking occured, but we do not eliminate it
4854

    
4855
  # The proper fix would be to wait (with some limits) until the
4856
  # connection has been made and drbd transitions from WFConnection
4857
  # into any other network-connected state (Connected, SyncTarget,
4858
  # SyncSource, etc.)
4859

    
4860
  # 1st pass, assemble on all nodes in secondary mode
4861
  for idx, inst_disk in enumerate(disks):
4862
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4863
      if ignore_size:
4864
        node_disk = node_disk.Copy()
4865
        node_disk.UnsetSize()
4866
      lu.cfg.SetDiskID(node_disk, node)
4867
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
4868
      msg = result.fail_msg
4869
      if msg:
4870
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4871
                           " (is_primary=False, pass=1): %s",
4872
                           inst_disk.iv_name, node, msg)
4873
        if not ignore_secondaries:
4874
          disks_ok = False
4875

    
4876
  # FIXME: race condition on drbd migration to primary
4877

    
4878
  # 2nd pass, do only the primary node
4879
  for idx, inst_disk in enumerate(disks):
4880
    dev_path = None
4881

    
4882
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4883
      if node != instance.primary_node:
4884
        continue
4885
      if ignore_size:
4886
        node_disk = node_disk.Copy()
4887
        node_disk.UnsetSize()
4888
      lu.cfg.SetDiskID(node_disk, node)
4889
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
4890
      msg = result.fail_msg
4891
      if msg:
4892
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4893
                           " (is_primary=True, pass=2): %s",
4894
                           inst_disk.iv_name, node, msg)
4895
        disks_ok = False
4896
      else:
4897
        dev_path = result.payload
4898

    
4899
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4900

    
4901
  # leave the disks configured for the primary node
4902
  # this is a workaround that would be fixed better by
4903
  # improving the logical/physical id handling
4904
  for disk in disks:
4905
    lu.cfg.SetDiskID(disk, instance.primary_node)
4906

    
4907
  return disks_ok, device_info
4908

    
4909

    
4910
def _StartInstanceDisks(lu, instance, force):
4911
  """Start the disks of an instance.
4912

4913
  """
4914
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4915
                                           ignore_secondaries=force)
4916
  if not disks_ok:
4917
    _ShutdownInstanceDisks(lu, instance)
4918
    if force is not None and not force:
4919
      lu.proc.LogWarning("", hint="If the message above refers to a"
4920
                         " secondary node,"
4921
                         " you can retry the operation using '--force'.")
4922
    raise errors.OpExecError("Disk consistency error")
4923

    
4924

    
4925
class LUInstanceDeactivateDisks(NoHooksLU):
4926
  """Shutdown an instance's disks.
4927

4928
  """
4929
  REQ_BGL = False
4930

    
4931
  def ExpandNames(self):
4932
    self._ExpandAndLockInstance()
4933
    self.needed_locks[locking.LEVEL_NODE] = []
4934
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4935

    
4936
  def DeclareLocks(self, level):
4937
    if level == locking.LEVEL_NODE:
4938
      self._LockInstancesNodes()
4939

    
4940
  def CheckPrereq(self):
4941
    """Check prerequisites.
4942

4943
    This checks that the instance is in the cluster.
4944

4945
    """
4946
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4947
    assert self.instance is not None, \
4948
      "Cannot retrieve locked instance %s" % self.op.instance_name
4949

    
4950
  def Exec(self, feedback_fn):
4951
    """Deactivate the disks
4952

4953
    """
4954
    instance = self.instance
4955
    if self.op.force:
4956
      _ShutdownInstanceDisks(self, instance)
4957
    else:
4958
      _SafeShutdownInstanceDisks(self, instance)
4959

    
4960

    
4961
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4962
  """Shutdown block devices of an instance.
4963

4964
  This function checks if an instance is running, before calling
4965
  _ShutdownInstanceDisks.
4966

4967
  """
4968
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4969
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4970

    
4971

    
4972
def _ExpandCheckDisks(instance, disks):
4973
  """Return the instance disks selected by the disks list
4974

4975
  @type disks: list of L{objects.Disk} or None
4976
  @param disks: selected disks
4977
  @rtype: list of L{objects.Disk}
4978
  @return: selected instance disks to act on
4979

4980
  """
4981
  if disks is None:
4982
    return instance.disks
4983
  else:
4984
    if not set(disks).issubset(instance.disks):
4985
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4986
                                   " target instance")
4987
    return disks
4988

    
4989

    
4990
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4991
  """Shutdown block devices of an instance.
4992

4993
  This does the shutdown on all nodes of the instance.
4994

4995
  If the ignore_primary is false, errors on the primary node are
4996
  ignored.
4997

4998
  """
4999
  all_result = True
5000
  disks = _ExpandCheckDisks(instance, disks)
5001

    
5002
  for disk in disks:
5003
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5004
      lu.cfg.SetDiskID(top_disk, node)
5005
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5006
      msg = result.fail_msg
5007
      if msg:
5008
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5009
                      disk.iv_name, node, msg)
5010
        if ((node == instance.primary_node and not ignore_primary) or
5011
            (node != instance.primary_node and not result.offline)):
5012
          all_result = False
5013
  return all_result
5014

    
5015

    
5016
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5017
  """Checks if a node has enough free memory.
5018

5019
  This function check if a given node has the needed amount of free
5020
  memory. In case the node has less memory or we cannot get the
5021
  information from the node, this function raise an OpPrereqError
5022
  exception.
5023

5024
  @type lu: C{LogicalUnit}
5025
  @param lu: a logical unit from which we get configuration data
5026
  @type node: C{str}
5027
  @param node: the node to check
5028
  @type reason: C{str}
5029
  @param reason: string to use in the error message
5030
  @type requested: C{int}
5031
  @param requested: the amount of memory in MiB to check for
5032
  @type hypervisor_name: C{str}
5033
  @param hypervisor_name: the hypervisor to ask for memory stats
5034
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5035
      we cannot check the node
5036

5037
  """
5038
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5039
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5040
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5041
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5042
  if not isinstance(free_mem, int):
5043
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5044
                               " was '%s'" % (node, free_mem),
5045
                               errors.ECODE_ENVIRON)
5046
  if requested > free_mem:
5047
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5048
                               " needed %s MiB, available %s MiB" %
5049
                               (node, reason, requested, free_mem),
5050
                               errors.ECODE_NORES)
5051

    
5052

    
5053
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5054
  """Checks if nodes have enough free disk space in the all VGs.
5055

5056
  This function check if all given nodes have the needed amount of
5057
  free disk. In case any node has less disk or we cannot get the
5058
  information from the node, this function raise an OpPrereqError
5059
  exception.
5060

5061
  @type lu: C{LogicalUnit}
5062
  @param lu: a logical unit from which we get configuration data
5063
  @type nodenames: C{list}
5064
  @param nodenames: the list of node names to check
5065
  @type req_sizes: C{dict}
5066
  @param req_sizes: the hash of vg and corresponding amount of disk in
5067
      MiB to check for
5068
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5069
      or we cannot check the node
5070

5071
  """
5072
  for vg, req_size in req_sizes.items():
5073
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5074

    
5075

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

5079
  This function check if all given nodes have the needed amount of
5080
  free disk. In case any node has less disk or we cannot get the
5081
  information from the node, this function raise an OpPrereqError
5082
  exception.
5083

5084
  @type lu: C{LogicalUnit}
5085
  @param lu: a logical unit from which we get configuration data
5086
  @type nodenames: C{list}
5087
  @param nodenames: the list of node names to check
5088
  @type vg: C{str}
5089
  @param vg: the volume group to check
5090
  @type requested: C{int}
5091
  @param requested: the amount of disk in MiB to check for
5092
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5093
      or we cannot check the node
5094

5095
  """
5096
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5097
  for node in nodenames:
5098
    info = nodeinfo[node]
5099
    info.Raise("Cannot get current information from node %s" % node,
5100
               prereq=True, ecode=errors.ECODE_ENVIRON)
5101
    vg_free = info.payload.get("vg_free", None)
5102
    if not isinstance(vg_free, int):
5103
      raise errors.OpPrereqError("Can't compute free disk space on node"
5104
                                 " %s for vg %s, result was '%s'" %
5105
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5106
    if requested > vg_free:
5107
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5108
                                 " vg %s: required %d MiB, available %d MiB" %
5109
                                 (node, vg, requested, vg_free),
5110
                                 errors.ECODE_NORES)
5111

    
5112

    
5113
class LUInstanceStartup(LogicalUnit):
5114
  """Starts an instance.
5115

5116
  """
5117
  HPATH = "instance-start"
5118
  HTYPE = constants.HTYPE_INSTANCE
5119
  REQ_BGL = False
5120

    
5121
  def CheckArguments(self):
5122
    # extra beparams
5123
    if self.op.beparams:
5124
      # fill the beparams dict
5125
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5126

    
5127
  def ExpandNames(self):
5128
    self._ExpandAndLockInstance()
5129

    
5130
  def BuildHooksEnv(self):
5131
    """Build hooks env.
5132

5133
    This runs on master, primary and secondary nodes of the instance.
5134

5135
    """
5136
    env = {
5137
      "FORCE": self.op.force,
5138
      }
5139
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5140
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5141
    return env, nl, nl
5142

    
5143
  def CheckPrereq(self):
5144
    """Check prerequisites.
5145

5146
    This checks that the instance is in the cluster.
5147

5148
    """
5149
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5150
    assert self.instance is not None, \
5151
      "Cannot retrieve locked instance %s" % self.op.instance_name
5152

    
5153
    # extra hvparams
5154
    if self.op.hvparams:
5155
      # check hypervisor parameter syntax (locally)
5156
      cluster = self.cfg.GetClusterInfo()
5157
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5158
      filled_hvp = cluster.FillHV(instance)
5159
      filled_hvp.update(self.op.hvparams)
5160
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5161
      hv_type.CheckParameterSyntax(filled_hvp)
5162
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5163

    
5164
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5165

    
5166
    if self.primary_offline and self.op.ignore_offline_nodes:
5167
      self.proc.LogWarning("Ignoring offline primary node")
5168

    
5169
      if self.op.hvparams or self.op.beparams:
5170
        self.proc.LogWarning("Overridden parameters are ignored")
5171
    else:
5172
      _CheckNodeOnline(self, instance.primary_node)
5173

    
5174
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5175

    
5176
      # check bridges existence
5177
      _CheckInstanceBridgesExist(self, instance)
5178

    
5179
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5180
                                                instance.name,
5181
                                                instance.hypervisor)
5182
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5183
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5184
      if not remote_info.payload: # not running already
5185
        _CheckNodeFreeMemory(self, instance.primary_node,
5186
                             "starting instance %s" % instance.name,
5187
                             bep[constants.BE_MEMORY], instance.hypervisor)
5188

    
5189
  def Exec(self, feedback_fn):
5190
    """Start the instance.
5191

5192
    """
5193
    instance = self.instance
5194
    force = self.op.force
5195

    
5196
    self.cfg.MarkInstanceUp(instance.name)
5197

    
5198
    if self.primary_offline:
5199
      assert self.op.ignore_offline_nodes
5200
      self.proc.LogInfo("Primary node offline, marked instance as started")
5201
    else:
5202
      node_current = instance.primary_node
5203

    
5204
      _StartInstanceDisks(self, instance, force)
5205

    
5206
      result = self.rpc.call_instance_start(node_current, instance,
5207
                                            self.op.hvparams, self.op.beparams)
5208
      msg = result.fail_msg
5209
      if msg:
5210
        _ShutdownInstanceDisks(self, instance)
5211
        raise errors.OpExecError("Could not start instance: %s" % msg)
5212

    
5213

    
5214
class LUInstanceReboot(LogicalUnit):
5215
  """Reboot an instance.
5216

5217
  """
5218
  HPATH = "instance-reboot"
5219
  HTYPE = constants.HTYPE_INSTANCE
5220
  REQ_BGL = False
5221

    
5222
  def ExpandNames(self):
5223
    self._ExpandAndLockInstance()
5224

    
5225
  def BuildHooksEnv(self):
5226
    """Build hooks env.
5227

5228
    This runs on master, primary and secondary nodes of the instance.
5229

5230
    """
5231
    env = {
5232
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5233
      "REBOOT_TYPE": self.op.reboot_type,
5234
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5235
      }
5236
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5237
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5238
    return env, nl, nl
5239

    
5240
  def CheckPrereq(self):
5241
    """Check prerequisites.
5242

5243
    This checks that the instance is in the cluster.
5244

5245
    """
5246
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5247
    assert self.instance is not None, \
5248
      "Cannot retrieve locked instance %s" % self.op.instance_name
5249

    
5250
    _CheckNodeOnline(self, instance.primary_node)
5251

    
5252
    # check bridges existence
5253
    _CheckInstanceBridgesExist(self, instance)
5254

    
5255
  def Exec(self, feedback_fn):
5256
    """Reboot the instance.
5257

5258
    """
5259
    instance = self.instance
5260
    ignore_secondaries = self.op.ignore_secondaries
5261
    reboot_type = self.op.reboot_type
5262

    
5263
    node_current = instance.primary_node
5264

    
5265
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5266
                       constants.INSTANCE_REBOOT_HARD]:
5267
      for disk in instance.disks:
5268
        self.cfg.SetDiskID(disk, node_current)
5269
      result = self.rpc.call_instance_reboot(node_current, instance,
5270
                                             reboot_type,
5271
                                             self.op.shutdown_timeout)
5272
      result.Raise("Could not reboot instance")
5273
    else:
5274
      result = self.rpc.call_instance_shutdown(node_current, instance,
5275
                                               self.op.shutdown_timeout)
5276
      result.Raise("Could not shutdown instance for full reboot")
5277
      _ShutdownInstanceDisks(self, instance)
5278
      _StartInstanceDisks(self, instance, ignore_secondaries)
5279
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5280
      msg = result.fail_msg
5281
      if msg:
5282
        _ShutdownInstanceDisks(self, instance)
5283
        raise errors.OpExecError("Could not start instance for"
5284
                                 " full reboot: %s" % msg)
5285

    
5286
    self.cfg.MarkInstanceUp(instance.name)
5287

    
5288

    
5289
class LUInstanceShutdown(LogicalUnit):
5290
  """Shutdown an instance.
5291

5292
  """
5293
  HPATH = "instance-stop"
5294
  HTYPE = constants.HTYPE_INSTANCE
5295
  REQ_BGL = False
5296

    
5297
  def ExpandNames(self):
5298
    self._ExpandAndLockInstance()
5299

    
5300
  def BuildHooksEnv(self):
5301
    """Build hooks env.
5302

5303
    This runs on master, primary and secondary nodes of the instance.
5304

5305
    """
5306
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5307
    env["TIMEOUT"] = self.op.timeout
5308
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5309
    return env, nl, nl
5310

    
5311
  def CheckPrereq(self):
5312
    """Check prerequisites.
5313

5314
    This checks that the instance is in the cluster.
5315

5316
    """
5317
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5318
    assert self.instance is not None, \
5319
      "Cannot retrieve locked instance %s" % self.op.instance_name
5320

    
5321
    self.primary_offline = \
5322
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5323

    
5324
    if self.primary_offline and self.op.ignore_offline_nodes:
5325
      self.proc.LogWarning("Ignoring offline primary node")
5326
    else:
5327
      _CheckNodeOnline(self, self.instance.primary_node)
5328

    
5329
  def Exec(self, feedback_fn):
5330
    """Shutdown the instance.
5331

5332
    """
5333
    instance = self.instance
5334
    node_current = instance.primary_node
5335
    timeout = self.op.timeout
5336

    
5337
    self.cfg.MarkInstanceDown(instance.name)
5338

    
5339
    if self.primary_offline:
5340
      assert self.op.ignore_offline_nodes
5341
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5342
    else:
5343
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5344
      msg = result.fail_msg
5345
      if msg:
5346
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5347

    
5348
      _ShutdownInstanceDisks(self, instance)
5349

    
5350

    
5351
class LUInstanceReinstall(LogicalUnit):
5352
  """Reinstall an instance.
5353

5354
  """
5355
  HPATH = "instance-reinstall"
5356
  HTYPE = constants.HTYPE_INSTANCE
5357
  REQ_BGL = False
5358

    
5359
  def ExpandNames(self):
5360
    self._ExpandAndLockInstance()
5361

    
5362
  def BuildHooksEnv(self):
5363
    """Build hooks env.
5364

5365
    This runs on master, primary and secondary nodes of the instance.
5366

5367
    """
5368
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5369
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5370
    return env, nl, nl
5371

    
5372
  def CheckPrereq(self):
5373
    """Check prerequisites.
5374

5375
    This checks that the instance is in the cluster and is not running.
5376

5377
    """
5378
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5379
    assert instance is not None, \
5380
      "Cannot retrieve locked instance %s" % self.op.instance_name
5381
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5382
                     " offline, cannot reinstall")
5383
    for node in instance.secondary_nodes:
5384
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5385
                       " cannot reinstall")
5386

    
5387
    if instance.disk_template == constants.DT_DISKLESS:
5388
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5389
                                 self.op.instance_name,
5390
                                 errors.ECODE_INVAL)
5391
    _CheckInstanceDown(self, instance, "cannot reinstall")
5392

    
5393
    if self.op.os_type is not None:
5394
      # OS verification
5395
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5396
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5397
      instance_os = self.op.os_type
5398
    else:
5399
      instance_os = instance.os
5400

    
5401
    nodelist = list(instance.all_nodes)
5402

    
5403
    if self.op.osparams:
5404
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5405
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5406
      self.os_inst = i_osdict # the new dict (without defaults)
5407
    else:
5408
      self.os_inst = None
5409

    
5410
    self.instance = instance
5411

    
5412
  def Exec(self, feedback_fn):
5413
    """Reinstall the instance.
5414

5415
    """
5416
    inst = self.instance
5417

    
5418
    if self.op.os_type is not None:
5419
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5420
      inst.os = self.op.os_type
5421
      # Write to configuration
5422
      self.cfg.Update(inst, feedback_fn)
5423

    
5424
    _StartInstanceDisks(self, inst, None)
5425
    try:
5426
      feedback_fn("Running the instance OS create scripts...")
5427
      # FIXME: pass debug option from opcode to backend
5428
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5429
                                             self.op.debug_level,
5430
                                             osparams=self.os_inst)
5431
      result.Raise("Could not install OS for instance %s on node %s" %
5432
                   (inst.name, inst.primary_node))
5433
    finally:
5434
      _ShutdownInstanceDisks(self, inst)
5435

    
5436

    
5437
class LUInstanceRecreateDisks(LogicalUnit):
5438
  """Recreate an instance's missing disks.
5439

5440
  """
5441
  HPATH = "instance-recreate-disks"
5442
  HTYPE = constants.HTYPE_INSTANCE
5443
  REQ_BGL = False
5444

    
5445
  def CheckArguments(self):
5446
    # normalise the disk list
5447
    self.op.disks = sorted(frozenset(self.op.disks))
5448

    
5449
  def ExpandNames(self):
5450
    self._ExpandAndLockInstance()
5451
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5452
    if self.op.nodes:
5453
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5454
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5455
    else:
5456
      self.needed_locks[locking.LEVEL_NODE] = []
5457

    
5458
  def DeclareLocks(self, level):
5459
    if level == locking.LEVEL_NODE:
5460
      # if we replace the nodes, we only need to lock the old primary,
5461
      # otherwise we need to lock all nodes for disk re-creation
5462
      primary_only = bool(self.op.nodes)
5463
      self._LockInstancesNodes(primary_only=primary_only)
5464

    
5465
  def BuildHooksEnv(self):
5466
    """Build hooks env.
5467

5468
    This runs on master, primary and secondary nodes of the instance.
5469

5470
    """
5471
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5472
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5473
    return env, nl, nl
5474

    
5475
  def CheckPrereq(self):
5476
    """Check prerequisites.
5477

5478
    This checks that the instance is in the cluster and is not running.
5479

5480
    """
5481
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5482
    assert instance is not None, \
5483
      "Cannot retrieve locked instance %s" % self.op.instance_name
5484
    if self.op.nodes:
5485
      if len(self.op.nodes) != len(instance.all_nodes):
5486
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
5487
                                   " %d replacement nodes were specified" %
5488
                                   (instance.name, len(instance.all_nodes),
5489
                                    len(self.op.nodes)),
5490
                                   errors.ECODE_INVAL)
5491
      assert instance.disk_template != constants.DT_DRBD8 or \
5492
          len(self.op.nodes) == 2
5493
      assert instance.disk_template != constants.DT_PLAIN or \
5494
          len(self.op.nodes) == 1
5495
      primary_node = self.op.nodes[0]
5496
    else:
5497
      primary_node = instance.primary_node
5498
    _CheckNodeOnline(self, primary_node)
5499

    
5500
    if instance.disk_template == constants.DT_DISKLESS:
5501
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5502
                                 self.op.instance_name, errors.ECODE_INVAL)
5503
    # if we replace nodes *and* the old primary is offline, we don't
5504
    # check
5505
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
5506
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
5507
    if not (self.op.nodes and old_pnode.offline):
5508
      _CheckInstanceDown(self, instance, "cannot recreate disks")
5509

    
5510
    if not self.op.disks:
5511
      self.op.disks = range(len(instance.disks))
5512
    else:
5513
      for idx in self.op.disks:
5514
        if idx >= len(instance.disks):
5515
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5516
                                     errors.ECODE_INVAL)
5517
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
5518
      raise errors.OpPrereqError("Can't recreate disks partially and"
5519
                                 " change the nodes at the same time",
5520
                                 errors.ECODE_INVAL)
5521
    self.instance = instance
5522

    
5523
  def Exec(self, feedback_fn):
5524
    """Recreate the disks.
5525

5526
    """
5527
    # change primary node, if needed
5528
    if self.op.nodes:
5529
      self.instance.primary_node = self.op.nodes[0]
5530
      self.LogWarning("Changing the instance's nodes, you will have to"
5531
                      " remove any disks left on the older nodes manually")
5532

    
5533
    to_skip = []
5534
    for idx, disk in enumerate(self.instance.disks):
5535
      if idx not in self.op.disks: # disk idx has not been passed in
5536
        to_skip.append(idx)
5537
        continue
5538
      # update secondaries for disks, if needed
5539
      if self.op.nodes:
5540
        if disk.dev_type == constants.LD_DRBD8:
5541
          # need to update the nodes
5542
          assert len(self.op.nodes) == 2
5543
          logical_id = list(disk.logical_id)
5544
          logical_id[0] = self.op.nodes[0]
5545
          logical_id[1] = self.op.nodes[1]
5546
          disk.logical_id = tuple(logical_id)
5547

    
5548
    if self.op.nodes:
5549
      self.cfg.Update(self.instance, feedback_fn)
5550

    
5551
    _CreateDisks(self, self.instance, to_skip=to_skip)
5552

    
5553

    
5554
class LUInstanceRename(LogicalUnit):
5555
  """Rename an instance.
5556

5557
  """
5558
  HPATH = "instance-rename"
5559
  HTYPE = constants.HTYPE_INSTANCE
5560

    
5561
  def CheckArguments(self):
5562
    """Check arguments.
5563

5564
    """
5565
    if self.op.ip_check and not self.op.name_check:
5566
      # TODO: make the ip check more flexible and not depend on the name check
5567
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5568
                                 errors.ECODE_INVAL)
5569

    
5570
  def BuildHooksEnv(self):
5571
    """Build hooks env.
5572

5573
    This runs on master, primary and secondary nodes of the instance.
5574

5575
    """
5576
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5577
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5578
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5579
    return env, nl, nl
5580

    
5581
  def CheckPrereq(self):
5582
    """Check prerequisites.
5583

5584
    This checks that the instance is in the cluster and is not running.
5585

5586
    """
5587
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5588
                                                self.op.instance_name)
5589
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5590
    assert instance is not None
5591
    _CheckNodeOnline(self, instance.primary_node)
5592
    _CheckInstanceDown(self, instance, "cannot rename")
5593
    self.instance = instance
5594

    
5595
    new_name = self.op.new_name
5596
    if self.op.name_check:
5597
      hostname = netutils.GetHostname(name=new_name)
5598
      if hostname != new_name:
5599
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5600
                     hostname.name)
5601
      new_name = self.op.new_name = hostname.name
5602
      if (self.op.ip_check and
5603
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5604
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5605
                                   (hostname.ip, new_name),
5606
                                   errors.ECODE_NOTUNIQUE)
5607

    
5608
    instance_list = self.cfg.GetInstanceList()
5609
    if new_name in instance_list and new_name != instance.name:
5610
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5611
                                 new_name, errors.ECODE_EXISTS)
5612

    
5613
  def Exec(self, feedback_fn):
5614
    """Rename the instance.
5615

5616
    """
5617
    inst = self.instance
5618
    old_name = inst.name
5619

    
5620
    rename_file_storage = False
5621
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
5622
        self.op.new_name != inst.name):
5623
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5624
      rename_file_storage = True
5625

    
5626
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5627
    # Change the instance lock. This is definitely safe while we hold the BGL
5628
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5629
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5630

    
5631
    # re-read the instance from the configuration after rename
5632
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5633

    
5634
    if rename_file_storage:
5635
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5636
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5637
                                                     old_file_storage_dir,
5638
                                                     new_file_storage_dir)
5639
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5640
                   " (but the instance has been renamed in Ganeti)" %
5641
                   (inst.primary_node, old_file_storage_dir,
5642
                    new_file_storage_dir))
5643

    
5644
    _StartInstanceDisks(self, inst, None)
5645
    try:
5646
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5647
                                                 old_name, self.op.debug_level)
5648
      msg = result.fail_msg
5649
      if msg:
5650
        msg = ("Could not run OS rename script for instance %s on node %s"
5651
               " (but the instance has been renamed in Ganeti): %s" %
5652
               (inst.name, inst.primary_node, msg))
5653
        self.proc.LogWarning(msg)
5654
    finally:
5655
      _ShutdownInstanceDisks(self, inst)
5656

    
5657
    return inst.name
5658

    
5659

    
5660
class LUInstanceRemove(LogicalUnit):
5661
  """Remove an instance.
5662

5663
  """
5664
  HPATH = "instance-remove"
5665
  HTYPE = constants.HTYPE_INSTANCE
5666
  REQ_BGL = False
5667

    
5668
  def ExpandNames(self):
5669
    self._ExpandAndLockInstance()
5670
    self.needed_locks[locking.LEVEL_NODE] = []
5671
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5672

    
5673
  def DeclareLocks(self, level):
5674
    if level == locking.LEVEL_NODE:
5675
      self._LockInstancesNodes()
5676

    
5677
  def BuildHooksEnv(self):
5678
    """Build hooks env.
5679

5680
    This runs on master, primary and secondary nodes of the instance.
5681

5682
    """
5683
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5684
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5685
    nl = [self.cfg.GetMasterNode()]
5686
    nl_post = list(self.instance.all_nodes) + nl
5687
    return env, nl, nl_post
5688

    
5689
  def CheckPrereq(self):
5690
    """Check prerequisites.
5691

5692
    This checks that the instance is in the cluster.
5693

5694
    """
5695
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5696
    assert self.instance is not None, \
5697
      "Cannot retrieve locked instance %s" % self.op.instance_name
5698

    
5699
  def Exec(self, feedback_fn):
5700
    """Remove the instance.
5701

5702
    """
5703
    instance = self.instance
5704
    logging.info("Shutting down instance %s on node %s",
5705
                 instance.name, instance.primary_node)
5706

    
5707
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5708
                                             self.op.shutdown_timeout)
5709
    msg = result.fail_msg
5710
    if msg:
5711
      if self.op.ignore_failures:
5712
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5713
      else:
5714
        raise errors.OpExecError("Could not shutdown instance %s on"
5715
                                 " node %s: %s" %
5716
                                 (instance.name, instance.primary_node, msg))
5717

    
5718
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5719

    
5720

    
5721
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5722
  """Utility function to remove an instance.
5723

5724
  """
5725
  logging.info("Removing block devices for instance %s", instance.name)
5726

    
5727
  if not _RemoveDisks(lu, instance):
5728
    if not ignore_failures:
5729
      raise errors.OpExecError("Can't remove instance's disks")
5730
    feedback_fn("Warning: can't remove instance's disks")
5731

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

    
5734
  lu.cfg.RemoveInstance(instance.name)
5735

    
5736
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5737
    "Instance lock removal conflict"
5738

    
5739
  # Remove lock for the instance
5740
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5741

    
5742

    
5743
class LUInstanceQuery(NoHooksLU):
5744
  """Logical unit for querying instances.
5745

5746
  """
5747
  # pylint: disable-msg=W0142
5748
  REQ_BGL = False
5749

    
5750
  def CheckArguments(self):
5751
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5752
                             self.op.use_locking)
5753

    
5754
  def ExpandNames(self):
5755
    self.iq.ExpandNames(self)
5756

    
5757
  def DeclareLocks(self, level):
5758
    self.iq.DeclareLocks(self, level)
5759

    
5760
  def Exec(self, feedback_fn):
5761
    return self.iq.OldStyleQuery(self)
5762

    
5763

    
5764
class LUInstanceFailover(LogicalUnit):
5765
  """Failover an instance.
5766

5767
  """
5768
  HPATH = "instance-failover"
5769
  HTYPE = constants.HTYPE_INSTANCE
5770
  REQ_BGL = False
5771

    
5772
  def CheckArguments(self):
5773
    """Check the arguments.
5774

5775
    """
5776
    self.iallocator = getattr(self.op, "iallocator", None)
5777
    self.target_node = getattr(self.op, "target_node", None)
5778

    
5779
  def ExpandNames(self):
5780
    self._ExpandAndLockInstance()
5781

    
5782
    if self.op.target_node is not None:
5783
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5784

    
5785
    self.needed_locks[locking.LEVEL_NODE] = []
5786
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5787

    
5788
  def DeclareLocks(self, level):
5789
    if level == locking.LEVEL_NODE:
5790
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
5791
      if instance.disk_template in constants.DTS_EXT_MIRROR:
5792
        if self.op.target_node is None:
5793
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5794
        else:
5795
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
5796
                                                   self.op.target_node]
5797
        del self.recalculate_locks[locking.LEVEL_NODE]
5798
      else:
5799
        self._LockInstancesNodes()
5800

    
5801
  def BuildHooksEnv(self):
5802
    """Build hooks env.
5803

5804
    This runs on master, primary and secondary nodes of the instance.
5805

5806
    """
5807
    instance = self.instance
5808
    source_node = instance.primary_node
5809
    env = {
5810
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5811
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5812
      "OLD_PRIMARY": source_node,
5813
      "NEW_PRIMARY": self.op.target_node,
5814
      }
5815

    
5816
    if instance.disk_template in constants.DTS_INT_MIRROR:
5817
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
5818
      env["NEW_SECONDARY"] = source_node
5819
    else:
5820
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
5821

    
5822
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5823
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5824
    nl_post = list(nl)
5825
    nl_post.append(source_node)
5826
    return env, nl, nl_post
5827

    
5828
  def CheckPrereq(self):
5829
    """Check prerequisites.
5830

5831
    This checks that the instance is in the cluster.
5832

5833
    """
5834
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5835
    assert self.instance is not None, \
5836
      "Cannot retrieve locked instance %s" % self.op.instance_name
5837

    
5838
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5839
    if instance.disk_template not in constants.DTS_MIRRORED:
5840
      raise errors.OpPrereqError("Instance's disk layout is not"
5841
                                 " mirrored, cannot failover.",
5842
                                 errors.ECODE_STATE)
5843

    
5844
    if instance.disk_template in constants.DTS_EXT_MIRROR:
5845
      _CheckIAllocatorOrNode(self, "iallocator", "target_node")
5846
      if self.op.iallocator:
5847
        self._RunAllocator()
5848
        # Release all unnecessary node locks
5849
        nodes_keep = [instance.primary_node, self.op.target_node]
5850
        nodes_rel = [node for node in self.acquired_locks[locking.LEVEL_NODE]
5851
                     if node not in nodes_keep]
5852
        self.context.glm.release(locking.LEVEL_NODE, nodes_rel)
5853
        self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
5854

    
5855
      # self.op.target_node is already populated, either directly or by the
5856
      # iallocator run
5857
      target_node = self.op.target_node
5858

    
5859
    else:
5860
      secondary_nodes = instance.secondary_nodes
5861
      if not secondary_nodes:
5862
        raise errors.ConfigurationError("No secondary node but using"
5863
                                        " %s disk template" %
5864
                                        instance.disk_template)
5865
      target_node = secondary_nodes[0]
5866

    
5867
      if self.op.iallocator or (self.op.target_node and
5868
                                self.op.target_node != target_node):
5869
        raise errors.OpPrereqError("Instances with disk template %s cannot"
5870
                                   " be failed over to arbitrary nodes"
5871
                                   " (neither an iallocator nor a target"
5872
                                   " node can be passed)" %
5873
                                   instance.disk_template, errors.ECODE_INVAL)
5874
    _CheckNodeOnline(self, target_node)
5875
    _CheckNodeNotDrained(self, target_node)
5876

    
5877
    # Save target_node so that we can use it in BuildHooksEnv
5878
    self.op.target_node = target_node
5879

    
5880
    if instance.admin_up:
5881
      # check memory requirements on the secondary node
5882
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5883
                           instance.name, bep[constants.BE_MEMORY],
5884
                           instance.hypervisor)
5885
    else:
5886
      self.LogInfo("Not checking memory on the secondary node as"
5887
                   " instance will not be started")
5888

    
5889
    # check bridge existance
5890
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5891

    
5892
  def Exec(self, feedback_fn):
5893
    """Failover an instance.
5894

5895
    The failover is done by shutting it down on its present node and
5896
    starting it on the secondary.
5897

5898
    """
5899
    instance = self.instance
5900
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5901

    
5902
    source_node = instance.primary_node
5903
    target_node = self.op.target_node
5904

    
5905
    if instance.admin_up:
5906
      feedback_fn("* checking disk consistency between source and target")
5907
      for dev in instance.disks:
5908
        # for drbd, these are drbd over lvm
5909
        if not _CheckDiskConsistency(self, dev, target_node, False):
5910
          if not self.op.ignore_consistency:
5911
            raise errors.OpExecError("Disk %s is degraded on target node,"
5912
                                     " aborting failover." % dev.iv_name)
5913
    else:
5914
      feedback_fn("* not checking disk consistency as instance is not running")
5915

    
5916
    feedback_fn("* shutting down instance on source node")
5917
    logging.info("Shutting down instance %s on node %s",
5918
                 instance.name, source_node)
5919

    
5920
    result = self.rpc.call_instance_shutdown(source_node, instance,
5921
                                             self.op.shutdown_timeout)
5922
    msg = result.fail_msg
5923
    if msg:
5924
      if self.op.ignore_consistency or primary_node.offline:
5925
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5926
                             " Proceeding anyway. Please make sure node"
5927
                             " %s is down. Error details: %s",
5928
                             instance.name, source_node, source_node, msg)
5929
      else:
5930
        raise errors.OpExecError("Could not shutdown instance %s on"
5931
                                 " node %s: %s" %
5932
                                 (instance.name, source_node, msg))
5933

    
5934
    feedback_fn("* deactivating the instance's disks on source node")
5935
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5936
      raise errors.OpExecError("Can't shut down the instance's disks.")
5937

    
5938
    instance.primary_node = target_node
5939
    # distribute new instance config to the other nodes
5940
    self.cfg.Update(instance, feedback_fn)
5941

    
5942
    # Only start the instance if it's marked as up
5943
    if instance.admin_up:
5944
      feedback_fn("* activating the instance's disks on target node")
5945
      logging.info("Starting instance %s on node %s",
5946
                   instance.name, target_node)
5947

    
5948
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5949
                                           ignore_secondaries=True)
5950
      if not disks_ok:
5951
        _ShutdownInstanceDisks(self, instance)
5952
        raise errors.OpExecError("Can't activate the instance's disks")
5953

    
5954
      feedback_fn("* starting the instance on the target node")
5955
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5956
      msg = result.fail_msg
5957
      if msg:
5958
        _ShutdownInstanceDisks(self, instance)
5959
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5960
                                 (instance.name, target_node, msg))
5961

    
5962
  def _RunAllocator(self):
5963
    """Run the allocator based on input opcode.
5964

5965
    """
5966
    ial = IAllocator(self.cfg, self.rpc,
5967
                     mode=constants.IALLOCATOR_MODE_RELOC,
5968
                     name=self.instance.name,
5969
                     # TODO See why hail breaks with a single node below
5970
                     relocate_from=[self.instance.primary_node,
5971
                                    self.instance.primary_node],
5972
                     )
5973

    
5974
    ial.Run(self.op.iallocator)
5975

    
5976
    if not ial.success:
5977
      raise errors.OpPrereqError("Can't compute nodes using"
5978
                                 " iallocator '%s': %s" %
5979
                                 (self.op.iallocator, ial.info),
5980
                                 errors.ECODE_NORES)
5981
    if len(ial.result) != ial.required_nodes:
5982
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5983
                                 " of nodes (%s), required %s" %
5984
                                 (self.op.iallocator, len(ial.result),
5985
                                  ial.required_nodes), errors.ECODE_FAULT)
5986
    self.op.target_node = ial.result[0]
5987
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5988
                 self.instance.name, self.op.iallocator,
5989
                 utils.CommaJoin(ial.result))
5990

    
5991

    
5992
class LUInstanceMigrate(LogicalUnit):
5993
  """Migrate an instance.
5994

5995
  This is migration without shutting down, compared to the failover,
5996
  which is done with shutdown.
5997

5998
  """
5999
  HPATH = "instance-migrate"
6000
  HTYPE = constants.HTYPE_INSTANCE
6001
  REQ_BGL = False
6002

    
6003
  def ExpandNames(self):
6004
    self._ExpandAndLockInstance()
6005

    
6006
    if self.op.target_node is not None:
6007
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6008

    
6009
    self.needed_locks[locking.LEVEL_NODE] = []
6010
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6011

    
6012
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6013
                                       self.op.cleanup)
6014
    self.tasklets = [self._migrater]
6015

    
6016
  def DeclareLocks(self, level):
6017
    if level == locking.LEVEL_NODE:
6018
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6019
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6020
        if self.op.target_node is None:
6021
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6022
        else:
6023
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6024
                                                   self.op.target_node]
6025
        del self.recalculate_locks[locking.LEVEL_NODE]
6026
      else:
6027
        self._LockInstancesNodes()
6028

    
6029
  def BuildHooksEnv(self):
6030
    """Build hooks env.
6031

6032
    This runs on master, primary and secondary nodes of the instance.
6033

6034
    """
6035
    instance = self._migrater.instance
6036
    source_node = instance.primary_node
6037
    target_node = self.op.target_node
6038
    env = _BuildInstanceHookEnvByObject(self, instance)
6039
    env["MIGRATE_LIVE"] = self._migrater.live
6040
    env["MIGRATE_CLEANUP"] = self.op.cleanup
6041
    env.update({
6042
        "OLD_PRIMARY": source_node,
6043
        "NEW_PRIMARY": target_node,
6044
        })
6045

    
6046
    if instance.disk_template in constants.DTS_INT_MIRROR:
6047
      env["OLD_SECONDARY"] = target_node
6048
      env["NEW_SECONDARY"] = source_node
6049
    else:
6050
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6051

    
6052
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6053
    nl_post = list(nl)
6054
    nl_post.append(source_node)
6055
    return env, nl, nl_post
6056

    
6057

    
6058
class LUInstanceMove(LogicalUnit):
6059
  """Move an instance by data-copying.
6060

6061
  """
6062
  HPATH = "instance-move"
6063
  HTYPE = constants.HTYPE_INSTANCE
6064
  REQ_BGL = False
6065

    
6066
  def ExpandNames(self):
6067
    self._ExpandAndLockInstance()
6068
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6069
    self.op.target_node = target_node
6070
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6071
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6072

    
6073
  def DeclareLocks(self, level):
6074
    if level == locking.LEVEL_NODE:
6075
      self._LockInstancesNodes(primary_only=True)
6076

    
6077
  def BuildHooksEnv(self):
6078
    """Build hooks env.
6079

6080
    This runs on master, primary and secondary nodes of the instance.
6081

6082
    """
6083
    env = {
6084
      "TARGET_NODE": self.op.target_node,
6085
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6086
      }
6087
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6088
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
6089
                                       self.op.target_node]
6090
    return env, nl, nl
6091

    
6092
  def CheckPrereq(self):
6093
    """Check prerequisites.
6094

6095
    This checks that the instance is in the cluster.
6096

6097
    """
6098
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6099
    assert self.instance is not None, \
6100
      "Cannot retrieve locked instance %s" % self.op.instance_name
6101

    
6102
    node = self.cfg.GetNodeInfo(self.op.target_node)
6103
    assert node is not None, \
6104
      "Cannot retrieve locked node %s" % self.op.target_node
6105

    
6106
    self.target_node = target_node = node.name
6107

    
6108
    if target_node == instance.primary_node:
6109
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6110
                                 (instance.name, target_node),
6111
                                 errors.ECODE_STATE)
6112

    
6113
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6114

    
6115
    for idx, dsk in enumerate(instance.disks):
6116
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6117
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6118
                                   " cannot copy" % idx, errors.ECODE_STATE)
6119

    
6120
    _CheckNodeOnline(self, target_node)
6121
    _CheckNodeNotDrained(self, target_node)
6122
    _CheckNodeVmCapable(self, target_node)
6123

    
6124
    if instance.admin_up:
6125
      # check memory requirements on the secondary node
6126
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6127
                           instance.name, bep[constants.BE_MEMORY],
6128
                           instance.hypervisor)
6129
    else:
6130
      self.LogInfo("Not checking memory on the secondary node as"
6131
                   " instance will not be started")
6132

    
6133
    # check bridge existance
6134
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6135

    
6136
  def Exec(self, feedback_fn):
6137
    """Move an instance.
6138

6139
    The move is done by shutting it down on its present node, copying
6140
    the data over (slow) and starting it on the new node.
6141

6142
    """
6143
    instance = self.instance
6144

    
6145
    source_node = instance.primary_node
6146
    target_node = self.target_node
6147

    
6148
    self.LogInfo("Shutting down instance %s on source node %s",
6149
                 instance.name, source_node)
6150

    
6151
    result = self.rpc.call_instance_shutdown(source_node, instance,
6152
                                             self.op.shutdown_timeout)
6153
    msg = result.fail_msg
6154
    if msg:
6155
      if self.op.ignore_consistency:
6156
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6157
                             " Proceeding anyway. Please make sure node"
6158
                             " %s is down. Error details: %s",
6159
                             instance.name, source_node, source_node, msg)
6160
      else:
6161
        raise errors.OpExecError("Could not shutdown instance %s on"
6162
                                 " node %s: %s" %
6163
                                 (instance.name, source_node, msg))
6164

    
6165
    # create the target disks
6166
    try:
6167
      _CreateDisks(self, instance, target_node=target_node)
6168
    except errors.OpExecError:
6169
      self.LogWarning("Device creation failed, reverting...")
6170
      try:
6171
        _RemoveDisks(self, instance, target_node=target_node)
6172
      finally:
6173
        self.cfg.ReleaseDRBDMinors(instance.name)
6174
        raise
6175

    
6176
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6177

    
6178
    errs = []
6179
    # activate, get path, copy the data over
6180
    for idx, disk in enumerate(instance.disks):
6181
      self.LogInfo("Copying data for disk %d", idx)
6182
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6183
                                               instance.name, True, idx)
6184
      if result.fail_msg:
6185
        self.LogWarning("Can't assemble newly created disk %d: %s",
6186
                        idx, result.fail_msg)
6187
        errs.append(result.fail_msg)
6188
        break
6189
      dev_path = result.payload
6190
      result = self.rpc.call_blockdev_export(source_node, disk,
6191
                                             target_node, dev_path,
6192
                                             cluster_name)
6193
      if result.fail_msg:
6194
        self.LogWarning("Can't copy data over for disk %d: %s",
6195
                        idx, result.fail_msg)
6196
        errs.append(result.fail_msg)
6197
        break
6198

    
6199
    if errs:
6200
      self.LogWarning("Some disks failed to copy, aborting")
6201
      try:
6202
        _RemoveDisks(self, instance, target_node=target_node)
6203
      finally:
6204
        self.cfg.ReleaseDRBDMinors(instance.name)
6205
        raise errors.OpExecError("Errors during disk copy: %s" %
6206
                                 (",".join(errs),))
6207

    
6208
    instance.primary_node = target_node
6209
    self.cfg.Update(instance, feedback_fn)
6210

    
6211
    self.LogInfo("Removing the disks on the original node")
6212
    _RemoveDisks(self, instance, target_node=source_node)
6213

    
6214
    # Only start the instance if it's marked as up
6215
    if instance.admin_up:
6216
      self.LogInfo("Starting instance %s on node %s",
6217
                   instance.name, target_node)
6218

    
6219
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6220
                                           ignore_secondaries=True)
6221
      if not disks_ok:
6222
        _ShutdownInstanceDisks(self, instance)
6223
        raise errors.OpExecError("Can't activate the instance's disks")
6224

    
6225
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6226
      msg = result.fail_msg
6227
      if msg:
6228
        _ShutdownInstanceDisks(self, instance)
6229
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6230
                                 (instance.name, target_node, msg))
6231

    
6232

    
6233
class LUNodeMigrate(LogicalUnit):
6234
  """Migrate all instances from a node.
6235

6236
  """
6237
  HPATH = "node-migrate"
6238
  HTYPE = constants.HTYPE_NODE
6239
  REQ_BGL = False
6240

    
6241
  def CheckArguments(self):
6242
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6243

    
6244
  def ExpandNames(self):
6245
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6246

    
6247
    self.needed_locks = {}
6248

    
6249
    # Create tasklets for migrating instances for all instances on this node
6250
    names = []
6251
    tasklets = []
6252

    
6253
    self.lock_all_nodes = False
6254

    
6255
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6256
      logging.debug("Migrating instance %s", inst.name)
6257
      names.append(inst.name)
6258

    
6259
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6260

    
6261
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6262
        # We need to lock all nodes, as the iallocator will choose the
6263
        # destination nodes afterwards
6264
        self.lock_all_nodes = True
6265

    
6266
    self.tasklets = tasklets
6267

    
6268
    # Declare node locks
6269
    if self.lock_all_nodes:
6270
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6271
    else:
6272
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6273
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6274

    
6275
    # Declare instance locks
6276
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6277

    
6278
  def DeclareLocks(self, level):
6279
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6280
      self._LockInstancesNodes()
6281

    
6282
  def BuildHooksEnv(self):
6283
    """Build hooks env.
6284

6285
    This runs on the master, the primary and all the secondaries.
6286

6287
    """
6288
    env = {
6289
      "NODE_NAME": self.op.node_name,
6290
      }
6291

    
6292
    nl = [self.cfg.GetMasterNode()]
6293

    
6294
    return (env, nl, nl)
6295

    
6296

    
6297
class TLMigrateInstance(Tasklet):
6298
  """Tasklet class for instance migration.
6299

6300
  @type live: boolean
6301
  @ivar live: whether the migration will be done live or non-live;
6302
      this variable is initalized only after CheckPrereq has run
6303

6304
  """
6305
  def __init__(self, lu, instance_name, cleanup):
6306
    """Initializes this class.
6307

6308
    """
6309
    Tasklet.__init__(self, lu)
6310

    
6311
    # Parameters
6312
    self.instance_name = instance_name
6313
    self.cleanup = cleanup
6314
    self.live = False # will be overridden later
6315

    
6316
  def CheckPrereq(self):
6317
    """Check prerequisites.
6318

6319
    This checks that the instance is in the cluster.
6320

6321
    """
6322
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6323
    instance = self.cfg.GetInstanceInfo(instance_name)
6324
    assert instance is not None
6325
    self.instance = instance
6326

    
6327
    if instance.disk_template not in constants.DTS_MIRRORED:
6328
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6329
                                 " migrations" % instance.disk_template,
6330
                                 errors.ECODE_STATE)
6331

    
6332
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6333
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6334

    
6335
      if self.lu.op.iallocator:
6336
        self._RunAllocator()
6337
      else:
6338
        # We set set self.target_node as it is required by
6339
        # BuildHooksEnv
6340
        self.target_node = self.lu.op.target_node
6341

    
6342
      target_node = self.target_node
6343
      if self.target_node == instance.primary_node:
6344
        raise errors.OpPrereqError("Cannot migrate instance %s"
6345
                                   " to its primary (%s)" %
6346
                                   (instance.name, instance.primary_node))
6347

    
6348
      if len(self.lu.tasklets) == 1:
6349
        # It is safe to remove locks only when we're the only tasklet in the LU
6350
        nodes_keep = [instance.primary_node, target_node]
6351
        nodes_rel = [node for node in self.lu.acquired_locks[locking.LEVEL_NODE]
6352
                     if node not in nodes_keep]
6353
        self.lu.context.glm.release(locking.LEVEL_NODE, nodes_rel)
6354
        self.lu.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6355

    
6356
    else:
6357
      secondary_nodes = instance.secondary_nodes
6358
      if not secondary_nodes:
6359
        raise errors.ConfigurationError("No secondary node but using"
6360
                                        " %s disk template" %
6361
                                        instance.disk_template)
6362
      target_node = secondary_nodes[0]
6363
      if self.lu.op.iallocator or (self.lu.op.target_node and
6364
                                   self.lu.op.target_node != target_node):
6365
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6366
                                   " be migrated over to arbitrary nodes"
6367
                                   " (neither an iallocator nor a target"
6368
                                   " node can be passed)" %
6369
                                   instance.disk_template, errors.ECODE_INVAL)
6370

    
6371
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6372

    
6373
    # check memory requirements on the secondary node
6374
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6375
                         instance.name, i_be[constants.BE_MEMORY],
6376
                         instance.hypervisor)
6377

    
6378
    # check bridge existance
6379
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6380

    
6381
    if not self.cleanup:
6382
      _CheckNodeNotDrained(self.lu, target_node)
6383
      result = self.rpc.call_instance_migratable(instance.primary_node,
6384
                                                 instance)
6385
      result.Raise("Can't migrate, please use failover",
6386
                   prereq=True, ecode=errors.ECODE_STATE)
6387

    
6388

    
6389
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6390
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6391
                                 " parameters are accepted",
6392
                                 errors.ECODE_INVAL)
6393
    if self.lu.op.live is not None:
6394
      if self.lu.op.live:
6395
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6396
      else:
6397
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6398
      # reset the 'live' parameter to None so that repeated
6399
      # invocations of CheckPrereq do not raise an exception
6400
      self.lu.op.live = None
6401
    elif self.lu.op.mode is None:
6402
      # read the default value from the hypervisor
6403
      i_hv = self.cfg.GetClusterInfo().FillHV(self.instance, skip_globals=False)
6404
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6405

    
6406
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6407

    
6408
  def _RunAllocator(self):
6409
    """Run the allocator based on input opcode.
6410

6411
    """
6412
    ial = IAllocator(self.cfg, self.rpc,
6413
                     mode=constants.IALLOCATOR_MODE_RELOC,
6414
                     name=self.instance_name,
6415
                     # TODO See why hail breaks with a single node below
6416
                     relocate_from=[self.instance.primary_node,
6417
                                    self.instance.primary_node],
6418
                     )
6419

    
6420
    ial.Run(self.lu.op.iallocator)
6421

    
6422
    if not ial.success:
6423
      raise errors.OpPrereqError("Can't compute nodes using"
6424
                                 " iallocator '%s': %s" %
6425
                                 (self.lu.op.iallocator, ial.info),
6426
                                 errors.ECODE_NORES)
6427
    if len(ial.result) != ial.required_nodes:
6428
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6429
                                 " of nodes (%s), required %s" %
6430
                                 (self.lu.op.iallocator, len(ial.result),
6431
                                  ial.required_nodes), errors.ECODE_FAULT)
6432
    self.target_node = ial.result[0]
6433
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6434
                 self.instance_name, self.lu.op.iallocator,
6435
                 utils.CommaJoin(ial.result))
6436

    
6437
  def _WaitUntilSync(self):
6438
    """Poll with custom rpc for disk sync.
6439

6440
    This uses our own step-based rpc call.
6441

6442
    """
6443
    self.feedback_fn("* wait until resync is done")
6444
    all_done = False
6445
    while not all_done:
6446
      all_done = True
6447
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6448
                                            self.nodes_ip,
6449
                                            self.instance.disks)
6450
      min_percent = 100
6451
      for node, nres in result.items():
6452
        nres.Raise("Cannot resync disks on node %s" % node)
6453
        node_done, node_percent = nres.payload
6454
        all_done = all_done and node_done
6455
        if node_percent is not None:
6456
          min_percent = min(min_percent, node_percent)
6457
      if not all_done:
6458
        if min_percent < 100:
6459
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6460
        time.sleep(2)
6461

    
6462
  def _EnsureSecondary(self, node):
6463
    """Demote a node to secondary.
6464

6465
    """
6466
    self.feedback_fn("* switching node %s to secondary mode" % node)
6467

    
6468
    for dev in self.instance.disks:
6469
      self.cfg.SetDiskID(dev, node)
6470

    
6471
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6472
                                          self.instance.disks)
6473
    result.Raise("Cannot change disk to secondary on node %s" % node)
6474

    
6475
  def _GoStandalone(self):
6476
    """Disconnect from the network.
6477

6478
    """
6479
    self.feedback_fn("* changing into standalone mode")
6480
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6481
                                               self.instance.disks)
6482
    for node, nres in result.items():
6483
      nres.Raise("Cannot disconnect disks node %s" % node)
6484

    
6485
  def _GoReconnect(self, multimaster):
6486
    """Reconnect to the network.
6487

6488
    """
6489
    if multimaster:
6490
      msg = "dual-master"
6491
    else:
6492
      msg = "single-master"
6493
    self.feedback_fn("* changing disks into %s mode" % msg)
6494
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6495
                                           self.instance.disks,
6496
                                           self.instance.name, multimaster)
6497
    for node, nres in result.items():
6498
      nres.Raise("Cannot change disks config on node %s" % node)
6499

    
6500
  def _ExecCleanup(self):
6501
    """Try to cleanup after a failed migration.
6502

6503
    The cleanup is done by:
6504
      - check that the instance is running only on one node
6505
        (and update the config if needed)
6506
      - change disks on its secondary node to secondary
6507
      - wait until disks are fully synchronized
6508
      - disconnect from the network
6509
      - change disks into single-master mode
6510
      - wait again until disks are fully synchronized
6511

6512
    """
6513
    instance = self.instance
6514
    target_node = self.target_node
6515
    source_node = self.source_node
6516

    
6517
    # check running on only one node
6518
    self.feedback_fn("* checking where the instance actually runs"
6519
                     " (if this hangs, the hypervisor might be in"
6520
                     " a bad state)")
6521
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6522
    for node, result in ins_l.items():
6523
      result.Raise("Can't contact node %s" % node)
6524

    
6525
    runningon_source = instance.name in ins_l[source_node].payload
6526
    runningon_target = instance.name in ins_l[target_node].payload
6527

    
6528
    if runningon_source and runningon_target:
6529
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6530
                               " or the hypervisor is confused. You will have"
6531
                               " to ensure manually that it runs only on one"
6532
                               " and restart this operation.")
6533

    
6534
    if not (runningon_source or runningon_target):
6535
      raise errors.OpExecError("Instance does not seem to be running at all."
6536
                               " In this case, it's safer to repair by"
6537
                               " running 'gnt-instance stop' to ensure disk"
6538
                               " shutdown, and then restarting it.")
6539

    
6540
    if runningon_target:
6541
      # the migration has actually succeeded, we need to update the config
6542
      self.feedback_fn("* instance running on secondary node (%s),"
6543
                       " updating config" % target_node)
6544
      instance.primary_node = target_node
6545
      self.cfg.Update(instance, self.feedback_fn)
6546
      demoted_node = source_node
6547
    else:
6548
      self.feedback_fn("* instance confirmed to be running on its"
6549
                       " primary node (%s)" % source_node)
6550
      demoted_node = target_node
6551

    
6552
    if instance.disk_template in constants.DTS_INT_MIRROR:
6553
      self._EnsureSecondary(demoted_node)
6554
      try:
6555
        self._WaitUntilSync()
6556
      except errors.OpExecError:
6557
        # we ignore here errors, since if the device is standalone, it
6558
        # won't be able to sync
6559
        pass
6560
      self._GoStandalone()
6561
      self._GoReconnect(False)
6562
      self._WaitUntilSync()
6563

    
6564
    self.feedback_fn("* done")
6565

    
6566
  def _RevertDiskStatus(self):
6567
    """Try to revert the disk status after a failed migration.
6568

6569
    """
6570
    target_node = self.target_node
6571
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
6572
      return
6573

    
6574
    try:
6575
      self._EnsureSecondary(target_node)
6576
      self._GoStandalone()
6577
      self._GoReconnect(False)
6578
      self._WaitUntilSync()
6579
    except errors.OpExecError, err:
6580
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6581
                         " drives: error '%s'\n"
6582
                         "Please look and recover the instance status" %
6583
                         str(err))
6584

    
6585
  def _AbortMigration(self):
6586
    """Call the hypervisor code to abort a started migration.
6587

6588
    """
6589
    instance = self.instance
6590
    target_node = self.target_node
6591
    migration_info = self.migration_info
6592

    
6593
    abort_result = self.rpc.call_finalize_migration(target_node,
6594
                                                    instance,
6595
                                                    migration_info,
6596
                                                    False)
6597
    abort_msg = abort_result.fail_msg
6598
    if abort_msg:
6599
      logging.error("Aborting migration failed on target node %s: %s",
6600
                    target_node, abort_msg)
6601
      # Don't raise an exception here, as we stil have to try to revert the
6602
      # disk status, even if this step failed.
6603

    
6604
  def _ExecMigration(self):
6605
    """Migrate an instance.
6606

6607
    The migrate is done by:
6608
      - change the disks into dual-master mode
6609
      - wait until disks are fully synchronized again
6610
      - migrate the instance
6611
      - change disks on the new secondary node (the old primary) to secondary
6612
      - wait until disks are fully synchronized
6613
      - change disks into single-master mode
6614

6615
    """
6616
    instance = self.instance
6617
    target_node = self.target_node
6618
    source_node = self.source_node
6619

    
6620
    self.feedback_fn("* checking disk consistency between source and target")
6621
    for dev in instance.disks:
6622
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6623
        raise errors.OpExecError("Disk %s is degraded or not fully"
6624
                                 " synchronized on target node,"
6625
                                 " aborting migrate." % dev.iv_name)
6626

    
6627
    # First get the migration information from the remote node
6628
    result = self.rpc.call_migration_info(source_node, instance)
6629
    msg = result.fail_msg
6630
    if msg:
6631
      log_err = ("Failed fetching source migration information from %s: %s" %
6632
                 (source_node, msg))
6633
      logging.error(log_err)
6634
      raise errors.OpExecError(log_err)
6635

    
6636
    self.migration_info = migration_info = result.payload
6637

    
6638
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6639
      # Then switch the disks to master/master mode
6640
      self._EnsureSecondary(target_node)
6641
      self._GoStandalone()
6642
      self._GoReconnect(True)
6643
      self._WaitUntilSync()
6644

    
6645
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6646
    result = self.rpc.call_accept_instance(target_node,
6647
                                           instance,
6648
                                           migration_info,
6649
                                           self.nodes_ip[target_node])
6650

    
6651
    msg = result.fail_msg
6652
    if msg:
6653
      logging.error("Instance pre-migration failed, trying to revert"
6654
                    " disk status: %s", msg)
6655
      self.feedback_fn("Pre-migration failed, aborting")
6656
      self._AbortMigration()
6657
      self._RevertDiskStatus()
6658
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6659
                               (instance.name, msg))
6660

    
6661
    self.feedback_fn("* migrating instance to %s" % target_node)
6662
    result = self.rpc.call_instance_migrate(source_node, instance,
6663
                                            self.nodes_ip[target_node],
6664
                                            self.live)
6665
    msg = result.fail_msg
6666
    if msg:
6667
      logging.error("Instance migration failed, trying to revert"
6668
                    " disk status: %s", msg)
6669
      self.feedback_fn("Migration failed, aborting")
6670
      self._AbortMigration()
6671
      self._RevertDiskStatus()
6672
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6673
                               (instance.name, msg))
6674

    
6675
    instance.primary_node = target_node
6676
    # distribute new instance config to the other nodes
6677
    self.cfg.Update(instance, self.feedback_fn)
6678

    
6679
    result = self.rpc.call_finalize_migration(target_node,
6680
                                              instance,
6681
                                              migration_info,
6682
                                              True)
6683
    msg = result.fail_msg
6684
    if msg:
6685
      logging.error("Instance migration succeeded, but finalization failed:"
6686
                    " %s", msg)
6687
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6688
                               msg)
6689

    
6690
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6691
      self._EnsureSecondary(source_node)
6692
      self._WaitUntilSync()
6693
      self._GoStandalone()
6694
      self._GoReconnect(False)
6695
      self._WaitUntilSync()
6696

    
6697
    self.feedback_fn("* done")
6698

    
6699
  def Exec(self, feedback_fn):
6700
    """Perform the migration.
6701

6702
    """
6703
    feedback_fn("Migrating instance %s" % self.instance.name)
6704

    
6705
    self.feedback_fn = feedback_fn
6706

    
6707
    self.source_node = self.instance.primary_node
6708

    
6709
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
6710
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
6711
      self.target_node = self.instance.secondary_nodes[0]
6712
      # Otherwise self.target_node has been populated either
6713
      # directly, or through an iallocator.
6714

    
6715
    self.all_nodes = [self.source_node, self.target_node]
6716
    self.nodes_ip = {
6717
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6718
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6719
      }
6720

    
6721
    if self.cleanup:
6722
      return self._ExecCleanup()
6723
    else:
6724
      return self._ExecMigration()
6725

    
6726

    
6727
def _CreateBlockDev(lu, node, instance, device, force_create,
6728
                    info, force_open):
6729
  """Create a tree of block devices on a given node.
6730

6731
  If this device type has to be created on secondaries, create it and
6732
  all its children.
6733

6734
  If not, just recurse to children keeping the same 'force' value.
6735

6736
  @param lu: the lu on whose behalf we execute
6737
  @param node: the node on which to create the device
6738
  @type instance: L{objects.Instance}
6739
  @param instance: the instance which owns the device
6740
  @type device: L{objects.Disk}
6741
  @param device: the device to create
6742
  @type force_create: boolean
6743
  @param force_create: whether to force creation of this device; this
6744
      will be change to True whenever we find a device which has
6745
      CreateOnSecondary() attribute
6746
  @param info: the extra 'metadata' we should attach to the device
6747
      (this will be represented as a LVM tag)
6748
  @type force_open: boolean
6749
  @param force_open: this parameter will be passes to the
6750
      L{backend.BlockdevCreate} function where it specifies
6751
      whether we run on primary or not, and it affects both
6752
      the child assembly and the device own Open() execution
6753

6754
  """
6755
  if device.CreateOnSecondary():
6756
    force_create = True
6757

    
6758
  if device.children:
6759
    for child in device.children:
6760
      _CreateBlockDev(lu, node, instance, child, force_create,
6761
                      info, force_open)
6762

    
6763
  if not force_create:
6764
    return
6765

    
6766
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6767

    
6768

    
6769
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6770
  """Create a single block device on a given node.
6771

6772
  This will not recurse over children of the device, so they must be
6773
  created in advance.
6774

6775
  @param lu: the lu on whose behalf we execute
6776
  @param node: the node on which to create the device
6777
  @type instance: L{objects.Instance}
6778
  @param instance: the instance which owns the device
6779
  @type device: L{objects.Disk}
6780
  @param device: the device to create
6781
  @param info: the extra 'metadata' we should attach to the device
6782
      (this will be represented as a LVM tag)
6783
  @type force_open: boolean
6784
  @param force_open: this parameter will be passes to the
6785
      L{backend.BlockdevCreate} function where it specifies
6786
      whether we run on primary or not, and it affects both
6787
      the child assembly and the device own Open() execution
6788

6789
  """
6790
  lu.cfg.SetDiskID(device, node)
6791
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6792
                                       instance.name, force_open, info)
6793
  result.Raise("Can't create block device %s on"
6794
               " node %s for instance %s" % (device, node, instance.name))
6795
  if device.physical_id is None:
6796
    device.physical_id = result.payload
6797

    
6798

    
6799
def _GenerateUniqueNames(lu, exts):
6800
  """Generate a suitable LV name.
6801

6802
  This will generate a logical volume name for the given instance.
6803

6804
  """
6805
  results = []
6806
  for val in exts:
6807
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6808
    results.append("%s%s" % (new_id, val))
6809
  return results
6810

    
6811

    
6812
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
6813
                         iv_name, p_minor, s_minor):
6814
  """Generate a drbd8 device complete with its children.
6815

6816
  """
6817
  assert len(vgnames) == len(names) == 2
6818
  port = lu.cfg.AllocatePort()
6819
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6820
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6821
                          logical_id=(vgnames[0], names[0]))
6822
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6823
                          logical_id=(vgnames[1], names[1]))
6824
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6825
                          logical_id=(primary, secondary, port,
6826
                                      p_minor, s_minor,
6827
                                      shared_secret),
6828
                          children=[dev_data, dev_meta],
6829
                          iv_name=iv_name)
6830
  return drbd_dev
6831

    
6832

    
6833
def _GenerateDiskTemplate(lu, template_name,
6834
                          instance_name, primary_node,
6835
                          secondary_nodes, disk_info,
6836
                          file_storage_dir, file_driver,
6837
                          base_index, feedback_fn):
6838
  """Generate the entire disk layout for a given template type.
6839

6840
  """
6841
  #TODO: compute space requirements
6842

    
6843
  vgname = lu.cfg.GetVGName()
6844
  disk_count = len(disk_info)
6845
  disks = []
6846
  if template_name == constants.DT_DISKLESS:
6847
    pass
6848
  elif template_name == constants.DT_PLAIN:
6849
    if len(secondary_nodes) != 0:
6850
      raise errors.ProgrammerError("Wrong template configuration")
6851

    
6852
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6853
                                      for i in range(disk_count)])
6854
    for idx, disk in enumerate(disk_info):
6855
      disk_index = idx + base_index
6856
      vg = disk.get("vg", vgname)
6857
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6858
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6859
                              logical_id=(vg, names[idx]),
6860
                              iv_name="disk/%d" % disk_index,
6861
                              mode=disk["mode"])
6862
      disks.append(disk_dev)
6863
  elif template_name == constants.DT_DRBD8:
6864
    if len(secondary_nodes) != 1:
6865
      raise errors.ProgrammerError("Wrong template configuration")
6866
    remote_node = secondary_nodes[0]
6867
    minors = lu.cfg.AllocateDRBDMinor(
6868
      [primary_node, remote_node] * len(disk_info), instance_name)
6869

    
6870
    names = []
6871
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6872
                                               for i in range(disk_count)]):
6873
      names.append(lv_prefix + "_data")
6874
      names.append(lv_prefix + "_meta")
6875
    for idx, disk in enumerate(disk_info):
6876
      disk_index = idx + base_index
6877
      data_vg = disk.get("vg", vgname)
6878
      meta_vg = disk.get("metavg", data_vg)
6879
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6880
                                      disk["size"], [data_vg, meta_vg],
6881
                                      names[idx*2:idx*2+2],
6882
                                      "disk/%d" % disk_index,
6883
                                      minors[idx*2], minors[idx*2+1])
6884
      disk_dev.mode = disk["mode"]
6885
      disks.append(disk_dev)
6886
  elif template_name == constants.DT_FILE:
6887
    if len(secondary_nodes) != 0:
6888
      raise errors.ProgrammerError("Wrong template configuration")
6889

    
6890
    opcodes.RequireFileStorage()
6891

    
6892
    for idx, disk in enumerate(disk_info):
6893
      disk_index = idx + base_index
6894
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6895
                              iv_name="disk/%d" % disk_index,
6896
                              logical_id=(file_driver,
6897
                                          "%s/disk%d" % (file_storage_dir,
6898
                                                         disk_index)),
6899
                              mode=disk["mode"])
6900
      disks.append(disk_dev)
6901
  elif template_name == constants.DT_SHARED_FILE:
6902
    if len(secondary_nodes) != 0:
6903
      raise errors.ProgrammerError("Wrong template configuration")
6904

    
6905
    opcodes.RequireSharedFileStorage()
6906

    
6907
    for idx, disk in enumerate(disk_info):
6908
      disk_index = idx + base_index
6909
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6910
                              iv_name="disk/%d" % disk_index,
6911
                              logical_id=(file_driver,
6912
                                          "%s/disk%d" % (file_storage_dir,
6913
                                                         disk_index)),
6914
                              mode=disk["mode"])
6915
      disks.append(disk_dev)
6916
  elif template_name == constants.DT_BLOCK:
6917
    if len(secondary_nodes) != 0:
6918
      raise errors.ProgrammerError("Wrong template configuration")
6919

    
6920
    for idx, disk in enumerate(disk_info):
6921
      disk_index = idx + base_index
6922
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV, size=disk["size"],
6923
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
6924
                                          disk["adopt"]),
6925
                              iv_name="disk/%d" % disk_index,
6926
                              mode=disk["mode"])
6927
      disks.append(disk_dev)
6928

    
6929
  else:
6930
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6931
  return disks
6932

    
6933

    
6934
def _GetInstanceInfoText(instance):
6935
  """Compute that text that should be added to the disk's metadata.
6936

6937
  """
6938
  return "originstname+%s" % instance.name
6939

    
6940

    
6941
def _CalcEta(time_taken, written, total_size):
6942
  """Calculates the ETA based on size written and total size.
6943

6944
  @param time_taken: The time taken so far
6945
  @param written: amount written so far
6946
  @param total_size: The total size of data to be written
6947
  @return: The remaining time in seconds
6948

6949
  """
6950
  avg_time = time_taken / float(written)
6951
  return (total_size - written) * avg_time
6952

    
6953

    
6954
def _WipeDisks(lu, instance):
6955
  """Wipes instance disks.
6956

6957
  @type lu: L{LogicalUnit}
6958
  @param lu: the logical unit on whose behalf we execute
6959
  @type instance: L{objects.Instance}
6960
  @param instance: the instance whose disks we should create
6961
  @return: the success of the wipe
6962

6963
  """
6964
  node = instance.primary_node
6965

    
6966
  for device in instance.disks:
6967
    lu.cfg.SetDiskID(device, node)
6968

    
6969
  logging.info("Pause sync of instance %s disks", instance.name)
6970
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6971

    
6972
  for idx, success in enumerate(result.payload):
6973
    if not success:
6974
      logging.warn("pause-sync of instance %s for disks %d failed",
6975
                   instance.name, idx)
6976

    
6977
  try:
6978
    for idx, device in enumerate(instance.disks):
6979
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6980
      # MAX_WIPE_CHUNK at max
6981
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6982
                            constants.MIN_WIPE_CHUNK_PERCENT)
6983
      # we _must_ make this an int, otherwise rounding errors will
6984
      # occur
6985
      wipe_chunk_size = int(wipe_chunk_size)
6986

    
6987
      lu.LogInfo("* Wiping disk %d", idx)
6988
      logging.info("Wiping disk %d for instance %s, node %s using"
6989
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
6990

    
6991
      offset = 0
6992
      size = device.size
6993
      last_output = 0
6994
      start_time = time.time()
6995

    
6996
      while offset < size:
6997
        wipe_size = min(wipe_chunk_size, size - offset)
6998
        logging.debug("Wiping disk %d, offset %s, chunk %s",
6999
                      idx, offset, wipe_size)
7000
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7001
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7002
                     (idx, offset, wipe_size))
7003
        now = time.time()
7004
        offset += wipe_size
7005
        if now - last_output >= 60:
7006
          eta = _CalcEta(now - start_time, offset, size)
7007
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7008
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7009
          last_output = now
7010
  finally:
7011
    logging.info("Resume sync of instance %s disks", instance.name)
7012

    
7013
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7014

    
7015
    for idx, success in enumerate(result.payload):
7016
      if not success:
7017
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
7018
                      " look at the status and troubleshoot the issue.", idx)
7019
        logging.warn("resume-sync of instance %s for disks %d failed",
7020
                     instance.name, idx)
7021

    
7022

    
7023
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7024
  """Create all disks for an instance.
7025

7026
  This abstracts away some work from AddInstance.
7027

7028
  @type lu: L{LogicalUnit}
7029
  @param lu: the logical unit on whose behalf we execute
7030
  @type instance: L{objects.Instance}
7031
  @param instance: the instance whose disks we should create
7032
  @type to_skip: list
7033
  @param to_skip: list of indices to skip
7034
  @type target_node: string
7035
  @param target_node: if passed, overrides the target node for creation
7036
  @rtype: boolean
7037
  @return: the success of the creation
7038

7039
  """
7040
  info = _GetInstanceInfoText(instance)
7041
  if target_node is None:
7042
    pnode = instance.primary_node
7043
    all_nodes = instance.all_nodes
7044
  else:
7045
    pnode = target_node
7046
    all_nodes = [pnode]
7047

    
7048
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
7049
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7050
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7051

    
7052
    result.Raise("Failed to create directory '%s' on"
7053
                 " node %s" % (file_storage_dir, pnode))
7054

    
7055
  # Note: this needs to be kept in sync with adding of disks in
7056
  # LUInstanceSetParams
7057
  for idx, device in enumerate(instance.disks):
7058
    if to_skip and idx in to_skip:
7059
      continue
7060
    logging.info("Creating volume %s for instance %s",
7061
                 device.iv_name, instance.name)
7062
    #HARDCODE
7063
    for node in all_nodes:
7064
      f_create = node == pnode
7065
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7066

    
7067

    
7068
def _RemoveDisks(lu, instance, target_node=None):
7069
  """Remove all disks for an instance.
7070

7071
  This abstracts away some work from `AddInstance()` and
7072
  `RemoveInstance()`. Note that in case some of the devices couldn't
7073
  be removed, the removal will continue with the other ones (compare
7074
  with `_CreateDisks()`).
7075

7076
  @type lu: L{LogicalUnit}
7077
  @param lu: the logical unit on whose behalf we execute
7078
  @type instance: L{objects.Instance}
7079
  @param instance: the instance whose disks we should remove
7080
  @type target_node: string
7081
  @param target_node: used to override the node on which to remove the disks
7082
  @rtype: boolean
7083
  @return: the success of the removal
7084

7085
  """
7086
  logging.info("Removing block devices for instance %s", instance.name)
7087

    
7088
  all_result = True
7089
  for device in instance.disks:
7090
    if target_node:
7091
      edata = [(target_node, device)]
7092
    else:
7093
      edata = device.ComputeNodeTree(instance.primary_node)
7094
    for node, disk in edata:
7095
      lu.cfg.SetDiskID(disk, node)
7096
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7097
      if msg:
7098
        lu.LogWarning("Could not remove block device %s on node %s,"
7099
                      " continuing anyway: %s", device.iv_name, node, msg)
7100
        all_result = False
7101

    
7102
  if instance.disk_template == constants.DT_FILE:
7103
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7104
    if target_node:
7105
      tgt = target_node
7106
    else:
7107
      tgt = instance.primary_node
7108
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7109
    if result.fail_msg:
7110
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7111
                    file_storage_dir, instance.primary_node, result.fail_msg)
7112
      all_result = False
7113

    
7114
  return all_result
7115

    
7116

    
7117
def _ComputeDiskSizePerVG(disk_template, disks):
7118
  """Compute disk size requirements in the volume group
7119

7120
  """
7121
  def _compute(disks, payload):
7122
    """Universal algorithm
7123

7124
    """
7125
    vgs = {}
7126
    for disk in disks:
7127
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
7128

    
7129
    return vgs
7130

    
7131
  # Required free disk space as a function of disk and swap space
7132
  req_size_dict = {
7133
    constants.DT_DISKLESS: {},
7134
    constants.DT_PLAIN: _compute(disks, 0),
7135
    # 128 MB are added for drbd metadata for each disk
7136
    constants.DT_DRBD8: _compute(disks, 128),
7137
    constants.DT_FILE: {},
7138
    constants.DT_SHARED_FILE: {},
7139
  }
7140

    
7141
  if disk_template not in req_size_dict:
7142
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7143
                                 " is unknown" %  disk_template)
7144

    
7145
  return req_size_dict[disk_template]
7146

    
7147

    
7148
def _ComputeDiskSize(disk_template, disks):
7149
  """Compute disk size requirements in the volume group
7150

7151
  """
7152
  # Required free disk space as a function of disk and swap space
7153
  req_size_dict = {
7154
    constants.DT_DISKLESS: None,
7155
    constants.DT_PLAIN: sum(d["size"] for d in disks),
7156
    # 128 MB are added for drbd metadata for each disk
7157
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
7158
    constants.DT_FILE: None,
7159
    constants.DT_SHARED_FILE: 0,
7160
    constants.DT_BLOCK: 0,
7161
  }
7162

    
7163
  if disk_template not in req_size_dict:
7164
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7165
                                 " is unknown" %  disk_template)
7166

    
7167
  return req_size_dict[disk_template]
7168

    
7169

    
7170
def _FilterVmNodes(lu, nodenames):
7171
  """Filters out non-vm_capable nodes from a list.
7172

7173
  @type lu: L{LogicalUnit}
7174
  @param lu: the logical unit for which we check
7175
  @type nodenames: list
7176
  @param nodenames: the list of nodes on which we should check
7177
  @rtype: list
7178
  @return: the list of vm-capable nodes
7179

7180
  """
7181
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7182
  return [name for name in nodenames if name not in vm_nodes]
7183

    
7184

    
7185
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7186
  """Hypervisor parameter validation.
7187

7188
  This function abstract the hypervisor parameter validation to be
7189
  used in both instance create and instance modify.
7190

7191
  @type lu: L{LogicalUnit}
7192
  @param lu: the logical unit for which we check
7193
  @type nodenames: list
7194
  @param nodenames: the list of nodes on which we should check
7195
  @type hvname: string
7196
  @param hvname: the name of the hypervisor we should use
7197
  @type hvparams: dict
7198
  @param hvparams: the parameters which we need to check
7199
  @raise errors.OpPrereqError: if the parameters are not valid
7200

7201
  """
7202
  nodenames = _FilterVmNodes(lu, nodenames)
7203
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7204
                                                  hvname,
7205
                                                  hvparams)
7206
  for node in nodenames:
7207
    info = hvinfo[node]
7208
    if info.offline:
7209
      continue
7210
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7211

    
7212

    
7213
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7214
  """OS parameters validation.
7215

7216
  @type lu: L{LogicalUnit}
7217
  @param lu: the logical unit for which we check
7218
  @type required: boolean
7219
  @param required: whether the validation should fail if the OS is not
7220
      found
7221
  @type nodenames: list
7222
  @param nodenames: the list of nodes on which we should check
7223
  @type osname: string
7224
  @param osname: the name of the hypervisor we should use
7225
  @type osparams: dict
7226
  @param osparams: the parameters which we need to check
7227
  @raise errors.OpPrereqError: if the parameters are not valid
7228

7229
  """
7230
  nodenames = _FilterVmNodes(lu, nodenames)
7231
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7232
                                   [constants.OS_VALIDATE_PARAMETERS],
7233
                                   osparams)
7234
  for node, nres in result.items():
7235
    # we don't check for offline cases since this should be run only
7236
    # against the master node and/or an instance's nodes
7237
    nres.Raise("OS Parameters validation failed on node %s" % node)
7238
    if not nres.payload:
7239
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7240
                 osname, node)
7241

    
7242

    
7243
class LUInstanceCreate(LogicalUnit):
7244
  """Create an instance.
7245

7246
  """
7247
  HPATH = "instance-add"
7248
  HTYPE = constants.HTYPE_INSTANCE
7249
  REQ_BGL = False
7250

    
7251
  def CheckArguments(self):
7252
    """Check arguments.
7253

7254
    """
7255
    # do not require name_check to ease forward/backward compatibility
7256
    # for tools
7257
    if self.op.no_install and self.op.start:
7258
      self.LogInfo("No-installation mode selected, disabling startup")
7259
      self.op.start = False
7260
    # validate/normalize the instance name
7261
    self.op.instance_name = \
7262
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7263

    
7264
    if self.op.ip_check and not self.op.name_check:
7265
      # TODO: make the ip check more flexible and not depend on the name check
7266
      raise errors.OpPrereqError("Cannot do ip check without a name check",
7267
                                 errors.ECODE_INVAL)
7268

    
7269
    # check nics' parameter names
7270
    for nic in self.op.nics:
7271
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7272

    
7273
    # check disks. parameter names and consistent adopt/no-adopt strategy
7274
    has_adopt = has_no_adopt = False
7275
    for disk in self.op.disks:
7276
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7277
      if "adopt" in disk:
7278
        has_adopt = True
7279
      else:
7280
        has_no_adopt = True
7281
    if has_adopt and has_no_adopt:
7282
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7283
                                 errors.ECODE_INVAL)
7284
    if has_adopt:
7285
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7286
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7287
                                   " '%s' disk template" %
7288
                                   self.op.disk_template,
7289
                                   errors.ECODE_INVAL)
7290
      if self.op.iallocator is not None:
7291
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7292
                                   " iallocator script", errors.ECODE_INVAL)
7293
      if self.op.mode == constants.INSTANCE_IMPORT:
7294
        raise errors.OpPrereqError("Disk adoption not allowed for"
7295
                                   " instance import", errors.ECODE_INVAL)
7296
    else:
7297
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7298
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7299
                                   " but no 'adopt' parameter given" %
7300
                                   self.op.disk_template,
7301
                                   errors.ECODE_INVAL)
7302

    
7303
    self.adopt_disks = has_adopt
7304

    
7305
    # instance name verification
7306
    if self.op.name_check:
7307
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7308
      self.op.instance_name = self.hostname1.name
7309
      # used in CheckPrereq for ip ping check
7310
      self.check_ip = self.hostname1.ip
7311
    else:
7312
      self.check_ip = None
7313

    
7314
    # file storage checks
7315
    if (self.op.file_driver and
7316
        not self.op.file_driver in constants.FILE_DRIVER):
7317
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7318
                                 self.op.file_driver, errors.ECODE_INVAL)
7319

    
7320
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7321
      raise errors.OpPrereqError("File storage directory path not absolute",
7322
                                 errors.ECODE_INVAL)
7323

    
7324
    ### Node/iallocator related checks
7325
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7326

    
7327
    if self.op.pnode is not None:
7328
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7329
        if self.op.snode is None:
7330
          raise errors.OpPrereqError("The networked disk templates need"
7331
                                     " a mirror node", errors.ECODE_INVAL)
7332
      elif self.op.snode:
7333
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7334
                        " template")
7335
        self.op.snode = None
7336

    
7337
    self._cds = _GetClusterDomainSecret()
7338

    
7339
    if self.op.mode == constants.INSTANCE_IMPORT:
7340
      # On import force_variant must be True, because if we forced it at
7341
      # initial install, our only chance when importing it back is that it
7342
      # works again!
7343
      self.op.force_variant = True
7344

    
7345
      if self.op.no_install:
7346
        self.LogInfo("No-installation mode has no effect during import")
7347

    
7348
    elif self.op.mode == constants.INSTANCE_CREATE:
7349
      if self.op.os_type is None:
7350
        raise errors.OpPrereqError("No guest OS specified",
7351
                                   errors.ECODE_INVAL)
7352
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7353
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7354
                                   " installation" % self.op.os_type,
7355
                                   errors.ECODE_STATE)
7356
      if self.op.disk_template is None:
7357
        raise errors.OpPrereqError("No disk template specified",
7358
                                   errors.ECODE_INVAL)
7359

    
7360
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7361
      # Check handshake to ensure both clusters have the same domain secret
7362
      src_handshake = self.op.source_handshake
7363
      if not src_handshake:
7364
        raise errors.OpPrereqError("Missing source handshake",
7365
                                   errors.ECODE_INVAL)
7366

    
7367
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7368
                                                           src_handshake)
7369
      if errmsg:
7370
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7371
                                   errors.ECODE_INVAL)
7372

    
7373
      # Load and check source CA
7374
      self.source_x509_ca_pem = self.op.source_x509_ca
7375
      if not self.source_x509_ca_pem:
7376
        raise errors.OpPrereqError("Missing source X509 CA",
7377
                                   errors.ECODE_INVAL)
7378

    
7379
      try:
7380
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7381
                                                    self._cds)
7382
      except OpenSSL.crypto.Error, err:
7383
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7384
                                   (err, ), errors.ECODE_INVAL)
7385

    
7386
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7387
      if errcode is not None:
7388
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7389
                                   errors.ECODE_INVAL)
7390

    
7391
      self.source_x509_ca = cert
7392

    
7393
      src_instance_name = self.op.source_instance_name
7394
      if not src_instance_name:
7395
        raise errors.OpPrereqError("Missing source instance name",
7396
                                   errors.ECODE_INVAL)
7397

    
7398
      self.source_instance_name = \
7399
          netutils.GetHostname(name=src_instance_name).name
7400

    
7401
    else:
7402
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7403
                                 self.op.mode, errors.ECODE_INVAL)
7404

    
7405
  def ExpandNames(self):
7406
    """ExpandNames for CreateInstance.
7407

7408
    Figure out the right locks for instance creation.
7409

7410
    """
7411
    self.needed_locks = {}
7412

    
7413
    instance_name = self.op.instance_name
7414
    # this is just a preventive check, but someone might still add this
7415
    # instance in the meantime, and creation will fail at lock-add time
7416
    if instance_name in self.cfg.GetInstanceList():
7417
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7418
                                 instance_name, errors.ECODE_EXISTS)
7419

    
7420
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7421

    
7422
    if self.op.iallocator:
7423
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7424
    else:
7425
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7426
      nodelist = [self.op.pnode]
7427
      if self.op.snode is not None:
7428
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7429
        nodelist.append(self.op.snode)
7430
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7431

    
7432
    # in case of import lock the source node too
7433
    if self.op.mode == constants.INSTANCE_IMPORT:
7434
      src_node = self.op.src_node
7435
      src_path = self.op.src_path
7436

    
7437
      if src_path is None:
7438
        self.op.src_path = src_path = self.op.instance_name
7439

    
7440
      if src_node is None:
7441
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7442
        self.op.src_node = None
7443
        if os.path.isabs(src_path):
7444
          raise errors.OpPrereqError("Importing an instance from an absolute"
7445
                                     " path requires a source node option.",
7446
                                     errors.ECODE_INVAL)
7447
      else:
7448
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7449
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7450
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7451
        if not os.path.isabs(src_path):
7452
          self.op.src_path = src_path = \
7453
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7454

    
7455
  def _RunAllocator(self):
7456
    """Run the allocator based on input opcode.
7457

7458
    """
7459
    nics = [n.ToDict() for n in self.nics]
7460
    ial = IAllocator(self.cfg, self.rpc,
7461
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7462
                     name=self.op.instance_name,
7463
                     disk_template=self.op.disk_template,
7464
                     tags=[],
7465
                     os=self.op.os_type,
7466
                     vcpus=self.be_full[constants.BE_VCPUS],
7467
                     mem_size=self.be_full[constants.BE_MEMORY],
7468
                     disks=self.disks,
7469
                     nics=nics,
7470
                     hypervisor=self.op.hypervisor,
7471
                     )
7472

    
7473
    ial.Run(self.op.iallocator)
7474

    
7475
    if not ial.success:
7476
      raise errors.OpPrereqError("Can't compute nodes using"
7477
                                 " iallocator '%s': %s" %
7478
                                 (self.op.iallocator, ial.info),
7479
                                 errors.ECODE_NORES)
7480
    if len(ial.result) != ial.required_nodes:
7481
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7482
                                 " of nodes (%s), required %s" %
7483
                                 (self.op.iallocator, len(ial.result),
7484
                                  ial.required_nodes), errors.ECODE_FAULT)
7485
    self.op.pnode = ial.result[0]
7486
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7487
                 self.op.instance_name, self.op.iallocator,
7488
                 utils.CommaJoin(ial.result))
7489
    if ial.required_nodes == 2:
7490
      self.op.snode = ial.result[1]
7491

    
7492
  def BuildHooksEnv(self):
7493
    """Build hooks env.
7494

7495
    This runs on master, primary and secondary nodes of the instance.
7496

7497
    """
7498
    env = {
7499
      "ADD_MODE": self.op.mode,
7500
      }
7501
    if self.op.mode == constants.INSTANCE_IMPORT:
7502
      env["SRC_NODE"] = self.op.src_node
7503
      env["SRC_PATH"] = self.op.src_path
7504
      env["SRC_IMAGES"] = self.src_images
7505

    
7506
    env.update(_BuildInstanceHookEnv(
7507
      name=self.op.instance_name,
7508
      primary_node=self.op.pnode,
7509
      secondary_nodes=self.secondaries,
7510
      status=self.op.start,
7511
      os_type=self.op.os_type,
7512
      memory=self.be_full[constants.BE_MEMORY],
7513
      vcpus=self.be_full[constants.BE_VCPUS],
7514
      nics=_NICListToTuple(self, self.nics),
7515
      disk_template=self.op.disk_template,
7516
      disks=[(d["size"], d["mode"]) for d in self.disks],
7517
      bep=self.be_full,
7518
      hvp=self.hv_full,
7519
      hypervisor_name=self.op.hypervisor,
7520
    ))
7521

    
7522
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7523
          self.secondaries)
7524
    return env, nl, nl
7525

    
7526
  def _ReadExportInfo(self):
7527
    """Reads the export information from disk.
7528

7529
    It will override the opcode source node and path with the actual
7530
    information, if these two were not specified before.
7531

7532
    @return: the export information
7533

7534
    """
7535
    assert self.op.mode == constants.INSTANCE_IMPORT
7536

    
7537
    src_node = self.op.src_node
7538
    src_path = self.op.src_path
7539

    
7540
    if src_node is None:
7541
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7542
      exp_list = self.rpc.call_export_list(locked_nodes)
7543
      found = False
7544
      for node in exp_list:
7545
        if exp_list[node].fail_msg:
7546
          continue
7547
        if src_path in exp_list[node].payload:
7548
          found = True
7549
          self.op.src_node = src_node = node
7550
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7551
                                                       src_path)
7552
          break
7553
      if not found:
7554
        raise errors.OpPrereqError("No export found for relative path %s" %
7555
                                    src_path, errors.ECODE_INVAL)
7556

    
7557
    _CheckNodeOnline(self, src_node)
7558
    result = self.rpc.call_export_info(src_node, src_path)
7559
    result.Raise("No export or invalid export found in dir %s" % src_path)
7560

    
7561
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7562
    if not export_info.has_section(constants.INISECT_EXP):
7563
      raise errors.ProgrammerError("Corrupted export config",
7564
                                   errors.ECODE_ENVIRON)
7565

    
7566
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7567
    if (int(ei_version) != constants.EXPORT_VERSION):
7568
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7569
                                 (ei_version, constants.EXPORT_VERSION),
7570
                                 errors.ECODE_ENVIRON)
7571
    return export_info
7572

    
7573
  def _ReadExportParams(self, einfo):
7574
    """Use export parameters as defaults.
7575

7576
    In case the opcode doesn't specify (as in override) some instance
7577
    parameters, then try to use them from the export information, if
7578
    that declares them.
7579

7580
    """
7581
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7582

    
7583
    if self.op.disk_template is None:
7584
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7585
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7586
                                          "disk_template")
7587
      else:
7588
        raise errors.OpPrereqError("No disk template specified and the export"
7589
                                   " is missing the disk_template information",
7590
                                   errors.ECODE_INVAL)
7591

    
7592
    if not self.op.disks:
7593
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7594
        disks = []
7595
        # TODO: import the disk iv_name too
7596
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7597
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7598
          disks.append({"size": disk_sz})
7599
        self.op.disks = disks
7600
      else:
7601
        raise errors.OpPrereqError("No disk info specified and the export"
7602
                                   " is missing the disk information",
7603
                                   errors.ECODE_INVAL)
7604

    
7605
    if (not self.op.nics and
7606
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7607
      nics = []
7608
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7609
        ndict = {}
7610
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7611
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7612
          ndict[name] = v
7613
        nics.append(ndict)
7614
      self.op.nics = nics
7615

    
7616
    if (self.op.hypervisor is None and
7617
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7618
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7619
    if einfo.has_section(constants.INISECT_HYP):
7620
      # use the export parameters but do not override the ones
7621
      # specified by the user
7622
      for name, value in einfo.items(constants.INISECT_HYP):
7623
        if name not in self.op.hvparams:
7624
          self.op.hvparams[name] = value
7625

    
7626
    if einfo.has_section(constants.INISECT_BEP):
7627
      # use the parameters, without overriding
7628
      for name, value in einfo.items(constants.INISECT_BEP):
7629
        if name not in self.op.beparams:
7630
          self.op.beparams[name] = value
7631
    else:
7632
      # try to read the parameters old style, from the main section
7633
      for name in constants.BES_PARAMETERS:
7634
        if (name not in self.op.beparams and
7635
            einfo.has_option(constants.INISECT_INS, name)):
7636
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7637

    
7638
    if einfo.has_section(constants.INISECT_OSP):
7639
      # use the parameters, without overriding
7640
      for name, value in einfo.items(constants.INISECT_OSP):
7641
        if name not in self.op.osparams:
7642
          self.op.osparams[name] = value
7643

    
7644
  def _RevertToDefaults(self, cluster):
7645
    """Revert the instance parameters to the default values.
7646

7647
    """
7648
    # hvparams
7649
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7650
    for name in self.op.hvparams.keys():
7651
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7652
        del self.op.hvparams[name]
7653
    # beparams
7654
    be_defs = cluster.SimpleFillBE({})
7655
    for name in self.op.beparams.keys():
7656
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7657
        del self.op.beparams[name]
7658
    # nic params
7659
    nic_defs = cluster.SimpleFillNIC({})
7660
    for nic in self.op.nics:
7661
      for name in constants.NICS_PARAMETERS:
7662
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7663
          del nic[name]
7664
    # osparams
7665
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7666
    for name in self.op.osparams.keys():
7667
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7668
        del self.op.osparams[name]
7669

    
7670
  def CheckPrereq(self):
7671
    """Check prerequisites.
7672

7673
    """
7674
    if self.op.mode == constants.INSTANCE_IMPORT:
7675
      export_info = self._ReadExportInfo()
7676
      self._ReadExportParams(export_info)
7677

    
7678
    if (not self.cfg.GetVGName() and
7679
        self.op.disk_template not in constants.DTS_NOT_LVM):
7680
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7681
                                 " instances", errors.ECODE_STATE)
7682

    
7683
    if self.op.hypervisor is None:
7684
      self.op.hypervisor = self.cfg.GetHypervisorType()
7685

    
7686
    cluster = self.cfg.GetClusterInfo()
7687
    enabled_hvs = cluster.enabled_hypervisors
7688
    if self.op.hypervisor not in enabled_hvs:
7689
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7690
                                 " cluster (%s)" % (self.op.hypervisor,
7691
                                  ",".join(enabled_hvs)),
7692
                                 errors.ECODE_STATE)
7693

    
7694
    # check hypervisor parameter syntax (locally)
7695
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7696
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7697
                                      self.op.hvparams)
7698
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7699
    hv_type.CheckParameterSyntax(filled_hvp)
7700
    self.hv_full = filled_hvp
7701
    # check that we don't specify global parameters on an instance
7702
    _CheckGlobalHvParams(self.op.hvparams)
7703

    
7704
    # fill and remember the beparams dict
7705
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7706
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7707

    
7708
    # build os parameters
7709
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7710

    
7711
    # now that hvp/bep are in final format, let's reset to defaults,
7712
    # if told to do so
7713
    if self.op.identify_defaults:
7714
      self._RevertToDefaults(cluster)
7715

    
7716
    # NIC buildup
7717
    self.nics = []
7718
    for idx, nic in enumerate(self.op.nics):
7719
      nic_mode_req = nic.get("mode", None)
7720
      nic_mode = nic_mode_req
7721
      if nic_mode is None:
7722
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7723

    
7724
      # bridge verification
7725
      bridge = nic.get("bridge", None)
7726
      link = nic.get("link", None)
7727
      if bridge and link:
7728
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7729
                                   " at the same time", errors.ECODE_INVAL)
7730
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7731
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7732
                                   errors.ECODE_INVAL)
7733
      elif bridge:
7734
        link = bridge
7735

    
7736
      nicparams = {}
7737
      if nic_mode_req:
7738
        nicparams[constants.NIC_MODE] = nic_mode_req
7739
      if link:
7740
        nicparams[constants.NIC_LINK] = link
7741

    
7742
      # in routed mode, for the first nic, the default ip is 'auto'
7743
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7744
        default_ip_mode = constants.VALUE_AUTO
7745
      else:
7746
        default_ip_mode = constants.VALUE_NONE
7747

    
7748
      # ip validity checks
7749
      ip = nic.get("ip", default_ip_mode)
7750
      if ip is None or ip.lower() == constants.VALUE_NONE:
7751
        nic_ip = None
7752
      elif ip.lower() == constants.VALUE_AUTO:
7753
        if not self.op.name_check:
7754
          raise errors.OpPrereqError("IP address set to auto but name checks"
7755
                                     " have been skipped",
7756
                                     errors.ECODE_INVAL)
7757
        nic_ip = self.hostname1.ip
7758
        try:
7759
          self.cfg.ReserveIp(link, nic_ip, self.proc.GetECId())
7760
        except errors.ReservationError:
7761
          raise errors.OpPrereqError("IP address %s already in use"
7762
                                     " in cluster" % nic_ip,
7763
                                     errors.ECODE_NOTUNIQUE)
7764
      elif ip.lower() == constants.NIC_IP_POOL:
7765
        nic_ip = self.cfg.GenerateIp(link, self.proc.GetECId())
7766
        logging.info("Chose ip %s from pool %s" % (nic_ip, link))
7767
      else:
7768
        if not netutils.IPAddress.IsValid(ip):
7769
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7770
                                     errors.ECODE_INVAL)
7771
        nic_ip = ip
7772
        try:
7773
          self.cfg.ReserveIp(link, nic_ip, self.proc.GetECId())
7774
        except errors.ReservationError:
7775
          raise errors.OpPrereqError("IP address %s already in use"
7776
                                     " in cluster" % nic_ip,
7777
                                     errors.ECODE_NOTUNIQUE)
7778

    
7779
      # TODO: check the ip address for uniqueness
7780
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7781
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7782
                                   errors.ECODE_INVAL)
7783

    
7784
      # MAC address verification
7785
      mac = nic.get("mac", constants.VALUE_AUTO)
7786
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7787
        mac = utils.NormalizeAndValidateMac(mac)
7788

    
7789
        try:
7790
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7791
        except errors.ReservationError:
7792
          raise errors.OpPrereqError("MAC address %s already in use"
7793
                                     " in cluster" % mac,
7794
                                     errors.ECODE_NOTUNIQUE)
7795

    
7796
      check_params = cluster.SimpleFillNIC(nicparams)
7797
      objects.NIC.CheckParameterSyntax(check_params)
7798
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7799

    
7800
    # disk checks/pre-build
7801
    self.disks = []
7802
    for disk in self.op.disks:
7803
      mode = disk.get("mode", constants.DISK_RDWR)
7804
      if mode not in constants.DISK_ACCESS_SET:
7805
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7806
                                   mode, errors.ECODE_INVAL)
7807
      size = disk.get("size", None)
7808
      if size is None:
7809
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7810
      try:
7811
        size = int(size)
7812
      except (TypeError, ValueError):
7813
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7814
                                   errors.ECODE_INVAL)
7815
      data_vg = disk.get("vg", self.cfg.GetVGName())
7816
      meta_vg = disk.get("metavg", data_vg)
7817
      new_disk = {"size": size, "mode": mode, "vg": data_vg, "metavg": meta_vg}
7818
      if "adopt" in disk:
7819
        new_disk["adopt"] = disk["adopt"]
7820
      self.disks.append(new_disk)
7821

    
7822
    if self.op.mode == constants.INSTANCE_IMPORT:
7823

    
7824
      # Check that the new instance doesn't have less disks than the export
7825
      instance_disks = len(self.disks)
7826
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7827
      if instance_disks < export_disks:
7828
        raise errors.OpPrereqError("Not enough disks to import."
7829
                                   " (instance: %d, export: %d)" %
7830
                                   (instance_disks, export_disks),
7831
                                   errors.ECODE_INVAL)
7832

    
7833
      disk_images = []
7834
      for idx in range(export_disks):
7835
        option = 'disk%d_dump' % idx
7836
        if export_info.has_option(constants.INISECT_INS, option):
7837
          # FIXME: are the old os-es, disk sizes, etc. useful?
7838
          export_name = export_info.get(constants.INISECT_INS, option)
7839
          image = utils.PathJoin(self.op.src_path, export_name)
7840
          disk_images.append(image)
7841
        else:
7842
          disk_images.append(False)
7843

    
7844
      self.src_images = disk_images
7845

    
7846
      old_name = export_info.get(constants.INISECT_INS, 'name')
7847
      try:
7848
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7849
      except (TypeError, ValueError), err:
7850
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7851
                                   " an integer: %s" % str(err),
7852
                                   errors.ECODE_STATE)
7853
      if self.op.instance_name == old_name:
7854
        for idx, nic in enumerate(self.nics):
7855
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7856
            nic_mac_ini = 'nic%d_mac' % idx
7857
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7858

    
7859
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7860

    
7861
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7862
    if self.op.ip_check:
7863
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7864
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7865
                                   (self.check_ip, self.op.instance_name),
7866
                                   errors.ECODE_NOTUNIQUE)
7867

    
7868
    #### mac address generation
7869
    # By generating here the mac address both the allocator and the hooks get
7870
    # the real final mac address rather than the 'auto' or 'generate' value.
7871
    # There is a race condition between the generation and the instance object
7872
    # creation, which means that we know the mac is valid now, but we're not
7873
    # sure it will be when we actually add the instance. If things go bad
7874
    # adding the instance will abort because of a duplicate mac, and the
7875
    # creation job will fail.
7876
    for nic in self.nics:
7877
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7878
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7879

    
7880
    #### allocator run
7881

    
7882
    if self.op.iallocator is not None:
7883
      self._RunAllocator()
7884

    
7885
    #### node related checks
7886

    
7887
    # check primary node
7888
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7889
    assert self.pnode is not None, \
7890
      "Cannot retrieve locked node %s" % self.op.pnode
7891
    if pnode.offline:
7892
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7893
                                 pnode.name, errors.ECODE_STATE)
7894
    if pnode.drained:
7895
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7896
                                 pnode.name, errors.ECODE_STATE)
7897
    if not pnode.vm_capable:
7898
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7899
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7900

    
7901
    self.secondaries = []
7902

    
7903
    # mirror node verification
7904
    if self.op.disk_template in constants.DTS_INT_MIRROR:
7905
      if self.op.snode == pnode.name:
7906
        raise errors.OpPrereqError("The secondary node cannot be the"
7907
                                   " primary node.", errors.ECODE_INVAL)
7908
      _CheckNodeOnline(self, self.op.snode)
7909
      _CheckNodeNotDrained(self, self.op.snode)
7910
      _CheckNodeVmCapable(self, self.op.snode)
7911
      self.secondaries.append(self.op.snode)
7912

    
7913
    nodenames = [pnode.name] + self.secondaries
7914

    
7915
    if not self.adopt_disks:
7916
      # Check lv size requirements, if not adopting
7917
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7918
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7919

    
7920
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
7921
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7922
      if len(all_lvs) != len(self.disks):
7923
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7924
                                   errors.ECODE_INVAL)
7925
      for lv_name in all_lvs:
7926
        try:
7927
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7928
          # to ReserveLV uses the same syntax
7929
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7930
        except errors.ReservationError:
7931
          raise errors.OpPrereqError("LV named %s used by another instance" %
7932
                                     lv_name, errors.ECODE_NOTUNIQUE)
7933

    
7934
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7935
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7936

    
7937
      node_lvs = self.rpc.call_lv_list([pnode.name],
7938
                                       vg_names.payload.keys())[pnode.name]
7939
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7940
      node_lvs = node_lvs.payload
7941

    
7942
      delta = all_lvs.difference(node_lvs.keys())
7943
      if delta:
7944
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7945
                                   utils.CommaJoin(delta),
7946
                                   errors.ECODE_INVAL)
7947
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7948
      if online_lvs:
7949
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7950
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7951
                                   errors.ECODE_STATE)
7952
      # update the size of disk based on what is found
7953
      for dsk in self.disks:
7954
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7955

    
7956
    elif self.op.disk_template == constants.DT_BLOCK:
7957
      # Normalize and de-duplicate device paths
7958
      all_disks = set([os.path.abspath(i["adopt"]) for i in self.disks])
7959
      if len(all_disks) != len(self.disks):
7960
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
7961
                                   errors.ECODE_INVAL)
7962
      baddisks = [d for d in all_disks
7963
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
7964
      if baddisks:
7965
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
7966
                                   " cannot be adopted" %
7967
                                   (", ".join(baddisks),
7968
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
7969
                                   errors.ECODE_INVAL)
7970

    
7971
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
7972
                                            list(all_disks))[pnode.name]
7973
      node_disks.Raise("Cannot get block device information from node %s" %
7974
                       pnode.name)
7975
      node_disks = node_disks.payload
7976
      delta = all_disks.difference(node_disks.keys())
7977
      if delta:
7978
        raise errors.OpPrereqError("Missing block device(s): %s" %
7979
                                   utils.CommaJoin(delta),
7980
                                   errors.ECODE_INVAL)
7981
      for dsk in self.disks:
7982
        dsk["size"] = int(float(node_disks[dsk["adopt"]]))
7983

    
7984
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7985

    
7986
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7987
    # check OS parameters (remotely)
7988
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7989

    
7990
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7991

    
7992
    # memory check on primary node
7993
    if self.op.start:
7994
      _CheckNodeFreeMemory(self, self.pnode.name,
7995
                           "creating instance %s" % self.op.instance_name,
7996
                           self.be_full[constants.BE_MEMORY],
7997
                           self.op.hypervisor)
7998

    
7999
    self.dry_run_result = list(nodenames)
8000

    
8001
  def Exec(self, feedback_fn):
8002
    """Create and add the instance to the cluster.
8003

8004
    """
8005
    instance = self.op.instance_name
8006
    pnode_name = self.pnode.name
8007

    
8008
    ht_kind = self.op.hypervisor
8009
    if ht_kind in constants.HTS_REQ_PORT:
8010
      network_port = self.cfg.AllocatePort()
8011
    else:
8012
      network_port = None
8013

    
8014
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
8015
      # this is needed because os.path.join does not accept None arguments
8016
      if self.op.file_storage_dir is None:
8017
        string_file_storage_dir = ""
8018
      else:
8019
        string_file_storage_dir = self.op.file_storage_dir
8020

    
8021
      # build the full file storage dir path
8022
      if self.op.disk_template == constants.DT_SHARED_FILE:
8023
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8024
      else:
8025
        get_fsd_fn = self.cfg.GetFileStorageDir
8026

    
8027
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
8028
                                        string_file_storage_dir, instance)
8029
    else:
8030
      file_storage_dir = ""
8031

    
8032
    disks = _GenerateDiskTemplate(self,
8033
                                  self.op.disk_template,
8034
                                  instance, pnode_name,
8035
                                  self.secondaries,
8036
                                  self.disks,
8037
                                  file_storage_dir,
8038
                                  self.op.file_driver,
8039
                                  0,
8040
                                  feedback_fn)
8041

    
8042
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8043
                            primary_node=pnode_name,
8044
                            nics=self.nics, disks=disks,
8045
                            disk_template=self.op.disk_template,
8046
                            admin_up=False,
8047
                            network_port=network_port,
8048
                            beparams=self.op.beparams,
8049
                            hvparams=self.op.hvparams,
8050
                            hypervisor=self.op.hypervisor,
8051
                            osparams=self.op.osparams,
8052
                            )
8053

    
8054
    if self.adopt_disks:
8055
      if self.op.disk_template == constants.DT_PLAIN:
8056
        # rename LVs to the newly-generated names; we need to construct
8057
        # 'fake' LV disks with the old data, plus the new unique_id
8058
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8059
        rename_to = []
8060
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8061
          rename_to.append(t_dsk.logical_id)
8062
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
8063
          self.cfg.SetDiskID(t_dsk, pnode_name)
8064
        result = self.rpc.call_blockdev_rename(pnode_name,
8065
                                               zip(tmp_disks, rename_to))
8066
        result.Raise("Failed to rename adoped LVs")
8067
    else:
8068
      feedback_fn("* creating instance disks...")
8069
      try:
8070
        _CreateDisks(self, iobj)
8071
      except errors.OpExecError:
8072
        self.LogWarning("Device creation failed, reverting...")
8073
        try:
8074
          _RemoveDisks(self, iobj)
8075
        finally:
8076
          self.cfg.ReleaseDRBDMinors(instance)
8077
          raise
8078

    
8079
    feedback_fn("adding instance %s to cluster config" % instance)
8080

    
8081
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8082

    
8083
    # Declare that we don't want to remove the instance lock anymore, as we've
8084
    # added the instance to the config
8085
    del self.remove_locks[locking.LEVEL_INSTANCE]
8086
    # Unlock all the nodes
8087
    if self.op.mode == constants.INSTANCE_IMPORT:
8088
      nodes_keep = [self.op.src_node]
8089
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
8090
                       if node != self.op.src_node]
8091
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
8092
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
8093
    else:
8094
      self.context.glm.release(locking.LEVEL_NODE)
8095
      del self.acquired_locks[locking.LEVEL_NODE]
8096

    
8097
    disk_abort = False
8098
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8099
      feedback_fn("* wiping instance disks...")
8100
      try:
8101
        _WipeDisks(self, iobj)
8102
      except errors.OpExecError, err:
8103
        logging.exception("Wiping disks failed")
8104
        self.LogWarning("Wiping instance disks failed (%s)", err)
8105
        disk_abort = True
8106

    
8107
    if disk_abort:
8108
      # Something is already wrong with the disks, don't do anything else
8109
      pass
8110
    elif self.op.wait_for_sync:
8111
      disk_abort = not _WaitForSync(self, iobj)
8112
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8113
      # make sure the disks are not degraded (still sync-ing is ok)
8114
      time.sleep(15)
8115
      feedback_fn("* checking mirrors status")
8116
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8117
    else:
8118
      disk_abort = False
8119

    
8120
    if disk_abort:
8121
      _RemoveDisks(self, iobj)
8122
      self.cfg.RemoveInstance(iobj.name)
8123
      # Make sure the instance lock gets removed
8124
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8125
      raise errors.OpExecError("There are some degraded disks for"
8126
                               " this instance")
8127

    
8128
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8129
      if self.op.mode == constants.INSTANCE_CREATE:
8130
        if not self.op.no_install:
8131
          feedback_fn("* running the instance OS create scripts...")
8132
          # FIXME: pass debug option from opcode to backend
8133
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8134
                                                 self.op.debug_level)
8135
          result.Raise("Could not add os for instance %s"
8136
                       " on node %s" % (instance, pnode_name))
8137

    
8138
      elif self.op.mode == constants.INSTANCE_IMPORT:
8139
        feedback_fn("* running the instance OS import scripts...")
8140

    
8141
        transfers = []
8142

    
8143
        for idx, image in enumerate(self.src_images):
8144
          if not image:
8145
            continue
8146

    
8147
          # FIXME: pass debug option from opcode to backend
8148
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8149
                                             constants.IEIO_FILE, (image, ),
8150
                                             constants.IEIO_SCRIPT,
8151
                                             (iobj.disks[idx], idx),
8152
                                             None)
8153
          transfers.append(dt)
8154

    
8155
        import_result = \
8156
          masterd.instance.TransferInstanceData(self, feedback_fn,
8157
                                                self.op.src_node, pnode_name,
8158
                                                self.pnode.secondary_ip,
8159
                                                iobj, transfers)
8160
        if not compat.all(import_result):
8161
          self.LogWarning("Some disks for instance %s on node %s were not"
8162
                          " imported successfully" % (instance, pnode_name))
8163

    
8164
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8165
        feedback_fn("* preparing remote import...")
8166
        # The source cluster will stop the instance before attempting to make a
8167
        # connection. In some cases stopping an instance can take a long time,
8168
        # hence the shutdown timeout is added to the connection timeout.
8169
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8170
                           self.op.source_shutdown_timeout)
8171
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8172

    
8173
        assert iobj.primary_node == self.pnode.name
8174
        disk_results = \
8175
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8176
                                        self.source_x509_ca,
8177
                                        self._cds, timeouts)
8178
        if not compat.all(disk_results):
8179
          # TODO: Should the instance still be started, even if some disks
8180
          # failed to import (valid for local imports, too)?
8181
          self.LogWarning("Some disks for instance %s on node %s were not"
8182
                          " imported successfully" % (instance, pnode_name))
8183

    
8184
        # Run rename script on newly imported instance
8185
        assert iobj.name == instance
8186
        feedback_fn("Running rename script for %s" % instance)
8187
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8188
                                                   self.source_instance_name,
8189
                                                   self.op.debug_level)
8190
        if result.fail_msg:
8191
          self.LogWarning("Failed to run rename script for %s on node"
8192
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8193

    
8194
      else:
8195
        # also checked in the prereq part
8196
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8197
                                     % self.op.mode)
8198

    
8199
    if self.op.start:
8200
      iobj.admin_up = True
8201
      self.cfg.Update(iobj, feedback_fn)
8202
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8203
      feedback_fn("* starting instance...")
8204
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8205
      result.Raise("Could not start instance")
8206

    
8207
    return list(iobj.all_nodes)
8208

    
8209

    
8210
class LUInstanceConsole(NoHooksLU):
8211
  """Connect to an instance's console.
8212

8213
  This is somewhat special in that it returns the command line that
8214
  you need to run on the master node in order to connect to the
8215
  console.
8216

8217
  """
8218
  REQ_BGL = False
8219

    
8220
  def ExpandNames(self):
8221
    self._ExpandAndLockInstance()
8222

    
8223
  def CheckPrereq(self):
8224
    """Check prerequisites.
8225

8226
    This checks that the instance is in the cluster.
8227

8228
    """
8229
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8230
    assert self.instance is not None, \
8231
      "Cannot retrieve locked instance %s" % self.op.instance_name
8232
    _CheckNodeOnline(self, self.instance.primary_node)
8233

    
8234
  def Exec(self, feedback_fn):
8235
    """Connect to the console of an instance
8236

8237
    """
8238
    instance = self.instance
8239
    node = instance.primary_node
8240

    
8241
    node_insts = self.rpc.call_instance_list([node],
8242
                                             [instance.hypervisor])[node]
8243
    node_insts.Raise("Can't get node information from %s" % node)
8244

    
8245
    if instance.name not in node_insts.payload:
8246
      if instance.admin_up:
8247
        state = "ERROR_down"
8248
      else:
8249
        state = "ADMIN_down"
8250
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8251
                               (instance.name, state))
8252

    
8253
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8254

    
8255
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8256

    
8257

    
8258
def _GetInstanceConsole(cluster, instance):
8259
  """Returns console information for an instance.
8260

8261
  @type cluster: L{objects.Cluster}
8262
  @type instance: L{objects.Instance}
8263
  @rtype: dict
8264

8265
  """
8266
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8267
  # beparams and hvparams are passed separately, to avoid editing the
8268
  # instance and then saving the defaults in the instance itself.
8269
  hvparams = cluster.FillHV(instance)
8270
  beparams = cluster.FillBE(instance)
8271
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8272

    
8273
  assert console.instance == instance.name
8274
  assert console.Validate()
8275

    
8276
  return console.ToDict()
8277

    
8278

    
8279
class LUInstanceReplaceDisks(LogicalUnit):
8280
  """Replace the disks of an instance.
8281

8282
  """
8283
  HPATH = "mirrors-replace"
8284
  HTYPE = constants.HTYPE_INSTANCE
8285
  REQ_BGL = False
8286

    
8287
  def CheckArguments(self):
8288
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8289
                                  self.op.iallocator)
8290

    
8291
  def ExpandNames(self):
8292
    self._ExpandAndLockInstance()
8293

    
8294
    if self.op.iallocator is not None:
8295
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8296

    
8297
    elif self.op.remote_node is not None:
8298
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8299
      self.op.remote_node = remote_node
8300

    
8301
      # Warning: do not remove the locking of the new secondary here
8302
      # unless DRBD8.AddChildren is changed to work in parallel;
8303
      # currently it doesn't since parallel invocations of
8304
      # FindUnusedMinor will conflict
8305
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
8306
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8307

    
8308
    else:
8309
      self.needed_locks[locking.LEVEL_NODE] = []
8310
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8311

    
8312
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8313
                                   self.op.iallocator, self.op.remote_node,
8314
                                   self.op.disks, False, self.op.early_release)
8315

    
8316
    self.tasklets = [self.replacer]
8317

    
8318
  def DeclareLocks(self, level):
8319
    # If we're not already locking all nodes in the set we have to declare the
8320
    # instance's primary/secondary nodes.
8321
    if (level == locking.LEVEL_NODE and
8322
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
8323
      self._LockInstancesNodes()
8324

    
8325
  def BuildHooksEnv(self):
8326
    """Build hooks env.
8327

8328
    This runs on the master, the primary and all the secondaries.
8329

8330
    """
8331
    instance = self.replacer.instance
8332
    env = {
8333
      "MODE": self.op.mode,
8334
      "NEW_SECONDARY": self.op.remote_node,
8335
      "OLD_SECONDARY": instance.secondary_nodes[0],
8336
      }
8337
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8338
    nl = [
8339
      self.cfg.GetMasterNode(),
8340
      instance.primary_node,
8341
      ]
8342
    if self.op.remote_node is not None:
8343
      nl.append(self.op.remote_node)
8344
    return env, nl, nl
8345

    
8346

    
8347
class TLReplaceDisks(Tasklet):
8348
  """Replaces disks for an instance.
8349

8350
  Note: Locking is not within the scope of this class.
8351

8352
  """
8353
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8354
               disks, delay_iallocator, early_release):
8355
    """Initializes this class.
8356

8357
    """
8358
    Tasklet.__init__(self, lu)
8359

    
8360
    # Parameters
8361
    self.instance_name = instance_name
8362
    self.mode = mode
8363
    self.iallocator_name = iallocator_name
8364
    self.remote_node = remote_node
8365
    self.disks = disks
8366
    self.delay_iallocator = delay_iallocator
8367
    self.early_release = early_release
8368

    
8369
    # Runtime data
8370
    self.instance = None
8371
    self.new_node = None
8372
    self.target_node = None
8373
    self.other_node = None
8374
    self.remote_node_info = None
8375
    self.node_secondary_ip = None
8376

    
8377
  @staticmethod
8378
  def CheckArguments(mode, remote_node, iallocator):
8379
    """Helper function for users of this class.
8380

8381
    """
8382
    # check for valid parameter combination
8383
    if mode == constants.REPLACE_DISK_CHG:
8384
      if remote_node is None and iallocator is None:
8385
        raise errors.OpPrereqError("When changing the secondary either an"
8386
                                   " iallocator script must be used or the"
8387
                                   " new node given", errors.ECODE_INVAL)
8388

    
8389
      if remote_node is not None and iallocator is not None:
8390
        raise errors.OpPrereqError("Give either the iallocator or the new"
8391
                                   " secondary, not both", errors.ECODE_INVAL)
8392

    
8393
    elif remote_node is not None or iallocator is not None:
8394
      # Not replacing the secondary
8395
      raise errors.OpPrereqError("The iallocator and new node options can"
8396
                                 " only be used when changing the"
8397
                                 " secondary node", errors.ECODE_INVAL)
8398

    
8399
  @staticmethod
8400
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8401
    """Compute a new secondary node using an IAllocator.
8402

8403
    """
8404
    ial = IAllocator(lu.cfg, lu.rpc,
8405
                     mode=constants.IALLOCATOR_MODE_RELOC,
8406
                     name=instance_name,
8407
                     relocate_from=relocate_from)
8408

    
8409
    ial.Run(iallocator_name)
8410

    
8411
    if not ial.success:
8412
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8413
                                 " %s" % (iallocator_name, ial.info),
8414
                                 errors.ECODE_NORES)
8415

    
8416
    if len(ial.result) != ial.required_nodes:
8417
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8418
                                 " of nodes (%s), required %s" %
8419
                                 (iallocator_name,
8420
                                  len(ial.result), ial.required_nodes),
8421
                                 errors.ECODE_FAULT)
8422

    
8423
    remote_node_name = ial.result[0]
8424

    
8425
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8426
               instance_name, remote_node_name)
8427

    
8428
    return remote_node_name
8429

    
8430
  def _FindFaultyDisks(self, node_name):
8431
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8432
                                    node_name, True)
8433

    
8434
  def CheckPrereq(self):
8435
    """Check prerequisites.
8436

8437
    This checks that the instance is in the cluster.
8438

8439
    """
8440
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8441
    assert instance is not None, \
8442
      "Cannot retrieve locked instance %s" % self.instance_name
8443

    
8444
    if instance.disk_template != constants.DT_DRBD8:
8445
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8446
                                 " instances", errors.ECODE_INVAL)
8447

    
8448
    if len(instance.secondary_nodes) != 1:
8449
      raise errors.OpPrereqError("The instance has a strange layout,"
8450
                                 " expected one secondary but found %d" %
8451
                                 len(instance.secondary_nodes),
8452
                                 errors.ECODE_FAULT)
8453

    
8454
    if not self.delay_iallocator:
8455
      self._CheckPrereq2()
8456

    
8457
  def _CheckPrereq2(self):
8458
    """Check prerequisites, second part.
8459

8460
    This function should always be part of CheckPrereq. It was separated and is
8461
    now called from Exec because during node evacuation iallocator was only
8462
    called with an unmodified cluster model, not taking planned changes into
8463
    account.
8464

8465
    """
8466
    instance = self.instance
8467
    secondary_node = instance.secondary_nodes[0]
8468

    
8469
    if self.iallocator_name is None:
8470
      remote_node = self.remote_node
8471
    else:
8472
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8473
                                       instance.name, instance.secondary_nodes)
8474

    
8475
    if remote_node is not None:
8476
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8477
      assert self.remote_node_info is not None, \
8478
        "Cannot retrieve locked node %s" % remote_node
8479
    else:
8480
      self.remote_node_info = None
8481

    
8482
    if remote_node == self.instance.primary_node:
8483
      raise errors.OpPrereqError("The specified node is the primary node of"
8484
                                 " the instance.", errors.ECODE_INVAL)
8485

    
8486
    if remote_node == secondary_node:
8487
      raise errors.OpPrereqError("The specified node is already the"
8488
                                 " secondary node of the instance.",
8489
                                 errors.ECODE_INVAL)
8490

    
8491
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8492
                                    constants.REPLACE_DISK_CHG):
8493
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8494
                                 errors.ECODE_INVAL)
8495

    
8496
    if self.mode == constants.REPLACE_DISK_AUTO:
8497
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8498
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8499

    
8500
      if faulty_primary and faulty_secondary:
8501
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8502
                                   " one node and can not be repaired"
8503
                                   " automatically" % self.instance_name,
8504
                                   errors.ECODE_STATE)
8505

    
8506
      if faulty_primary:
8507
        self.disks = faulty_primary
8508
        self.target_node = instance.primary_node
8509
        self.other_node = secondary_node
8510
        check_nodes = [self.target_node, self.other_node]
8511
      elif faulty_secondary:
8512
        self.disks = faulty_secondary
8513
        self.target_node = secondary_node
8514
        self.other_node = instance.primary_node
8515
        check_nodes = [self.target_node, self.other_node]
8516
      else:
8517
        self.disks = []
8518
        check_nodes = []
8519

    
8520
    else:
8521
      # Non-automatic modes
8522
      if self.mode == constants.REPLACE_DISK_PRI:
8523
        self.target_node = instance.primary_node
8524
        self.other_node = secondary_node
8525
        check_nodes = [self.target_node, self.other_node]
8526

    
8527
      elif self.mode == constants.REPLACE_DISK_SEC:
8528
        self.target_node = secondary_node
8529
        self.other_node = instance.primary_node
8530
        check_nodes = [self.target_node, self.other_node]
8531

    
8532
      elif self.mode == constants.REPLACE_DISK_CHG:
8533
        self.new_node = remote_node
8534
        self.other_node = instance.primary_node
8535
        self.target_node = secondary_node
8536
        check_nodes = [self.new_node, self.other_node]
8537

    
8538
        _CheckNodeNotDrained(self.lu, remote_node)
8539
        _CheckNodeVmCapable(self.lu, remote_node)
8540

    
8541
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8542
        assert old_node_info is not None
8543
        if old_node_info.offline and not self.early_release:
8544
          # doesn't make sense to delay the release
8545
          self.early_release = True
8546
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8547
                          " early-release mode", secondary_node)
8548

    
8549
      else:
8550
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8551
                                     self.mode)
8552

    
8553
      # If not specified all disks should be replaced
8554
      if not self.disks:
8555
        self.disks = range(len(self.instance.disks))
8556

    
8557
    for node in check_nodes:
8558
      _CheckNodeOnline(self.lu, node)
8559

    
8560
    touched_nodes = frozenset([self.new_node, self.other_node,
8561
                               self.target_node])
8562

    
8563
    if self.lu.needed_locks[locking.LEVEL_NODE] == locking.ALL_SET:
8564
      # Release unneeded node locks
8565
      for name in self.lu.acquired_locks[locking.LEVEL_NODE]:
8566
        if name not in touched_nodes:
8567
          self._ReleaseNodeLock(name)
8568

    
8569
    # Check whether disks are valid
8570
    for disk_idx in self.disks:
8571
      instance.FindDisk(disk_idx)
8572

    
8573
    # Get secondary node IP addresses
8574
    self.node_secondary_ip = \
8575
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
8576
           for node_name in touched_nodes
8577
           if node_name is not None)
8578

    
8579
  def Exec(self, feedback_fn):
8580
    """Execute disk replacement.
8581

8582
    This dispatches the disk replacement to the appropriate handler.
8583

8584
    """
8585
    if self.delay_iallocator:
8586
      self._CheckPrereq2()
8587

    
8588
    if (self.lu.needed_locks[locking.LEVEL_NODE] == locking.ALL_SET and
8589
        __debug__):
8590
      # Verify owned locks before starting operation
8591
      owned_locks = self.lu.context.glm.list_owned(locking.LEVEL_NODE)
8592
      assert set(owned_locks) == set(self.node_secondary_ip), \
8593
          "Not owning the correct locks: %s" % (owned_locks, )
8594

    
8595
    if not self.disks:
8596
      feedback_fn("No disks need replacement")
8597
      return
8598

    
8599
    feedback_fn("Replacing disk(s) %s for %s" %
8600
                (utils.CommaJoin(self.disks), self.instance.name))
8601

    
8602
    activate_disks = (not self.instance.admin_up)
8603

    
8604
    # Activate the instance disks if we're replacing them on a down instance
8605
    if activate_disks:
8606
      _StartInstanceDisks(self.lu, self.instance, True)
8607

    
8608
    try:
8609
      # Should we replace the secondary node?
8610
      if self.new_node is not None:
8611
        fn = self._ExecDrbd8Secondary
8612
      else:
8613
        fn = self._ExecDrbd8DiskOnly
8614

    
8615
      return fn(feedback_fn)
8616

    
8617
    finally:
8618
      # Deactivate the instance disks if we're replacing them on a
8619
      # down instance
8620
      if activate_disks:
8621
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8622

    
8623
      if __debug__:
8624
        # Verify owned locks
8625
        owned_locks = self.lu.context.glm.list_owned(locking.LEVEL_NODE)
8626
        assert ((self.early_release and not owned_locks) or
8627
                (not self.early_release and
8628
                 set(owned_locks) == set(self.node_secondary_ip))), \
8629
          ("Not owning the correct locks, early_release=%s, owned=%r" %
8630
           (self.early_release, owned_locks))
8631

    
8632
  def _CheckVolumeGroup(self, nodes):
8633
    self.lu.LogInfo("Checking volume groups")
8634

    
8635
    vgname = self.cfg.GetVGName()
8636

    
8637
    # Make sure volume group exists on all involved nodes
8638
    results = self.rpc.call_vg_list(nodes)
8639
    if not results:
8640
      raise errors.OpExecError("Can't list volume groups on the nodes")
8641

    
8642
    for node in nodes:
8643
      res = results[node]
8644
      res.Raise("Error checking node %s" % node)
8645
      if vgname not in res.payload:
8646
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8647
                                 (vgname, node))
8648

    
8649
  def _CheckDisksExistence(self, nodes):
8650
    # Check disk existence
8651
    for idx, dev in enumerate(self.instance.disks):
8652
      if idx not in self.disks:
8653
        continue
8654

    
8655
      for node in nodes:
8656
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8657
        self.cfg.SetDiskID(dev, node)
8658

    
8659
        result = self.rpc.call_blockdev_find(node, dev)
8660

    
8661
        msg = result.fail_msg
8662
        if msg or not result.payload:
8663
          if not msg:
8664
            msg = "disk not found"
8665
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8666
                                   (idx, node, msg))
8667

    
8668
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8669
    for idx, dev in enumerate(self.instance.disks):
8670
      if idx not in self.disks:
8671
        continue
8672

    
8673
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8674
                      (idx, node_name))
8675

    
8676
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8677
                                   ldisk=ldisk):
8678
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8679
                                 " replace disks for instance %s" %
8680
                                 (node_name, self.instance.name))
8681

    
8682
  def _CreateNewStorage(self, node_name):
8683
    iv_names = {}
8684

    
8685
    for idx, dev in enumerate(self.instance.disks):
8686
      if idx not in self.disks:
8687
        continue
8688

    
8689
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8690

    
8691
      self.cfg.SetDiskID(dev, node_name)
8692

    
8693
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8694
      names = _GenerateUniqueNames(self.lu, lv_names)
8695

    
8696
      vg_data = dev.children[0].logical_id[0]
8697
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8698
                             logical_id=(vg_data, names[0]))
8699
      vg_meta = dev.children[1].logical_id[0]
8700
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8701
                             logical_id=(vg_meta, names[1]))
8702

    
8703
      new_lvs = [lv_data, lv_meta]
8704
      old_lvs = dev.children
8705
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8706

    
8707
      # we pass force_create=True to force the LVM creation
8708
      for new_lv in new_lvs:
8709
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8710
                        _GetInstanceInfoText(self.instance), False)
8711

    
8712
    return iv_names
8713

    
8714
  def _CheckDevices(self, node_name, iv_names):
8715
    for name, (dev, _, _) in iv_names.iteritems():
8716
      self.cfg.SetDiskID(dev, node_name)
8717

    
8718
      result = self.rpc.call_blockdev_find(node_name, dev)
8719

    
8720
      msg = result.fail_msg
8721
      if msg or not result.payload:
8722
        if not msg:
8723
          msg = "disk not found"
8724
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8725
                                 (name, msg))
8726

    
8727
      if result.payload.is_degraded:
8728
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8729

    
8730
  def _RemoveOldStorage(self, node_name, iv_names):
8731
    for name, (_, old_lvs, _) in iv_names.iteritems():
8732
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8733

    
8734
      for lv in old_lvs:
8735
        self.cfg.SetDiskID(lv, node_name)
8736

    
8737
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8738
        if msg:
8739
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8740
                             hint="remove unused LVs manually")
8741

    
8742
  def _ReleaseNodeLock(self, node_name):
8743
    """Releases the lock for a given node."""
8744
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8745

    
8746
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8747
    """Replace a disk on the primary or secondary for DRBD 8.
8748

8749
    The algorithm for replace is quite complicated:
8750

8751
      1. for each disk to be replaced:
8752

8753
        1. create new LVs on the target node with unique names
8754
        1. detach old LVs from the drbd device
8755
        1. rename old LVs to name_replaced.<time_t>
8756
        1. rename new LVs to old LVs
8757
        1. attach the new LVs (with the old names now) to the drbd device
8758

8759
      1. wait for sync across all devices
8760

8761
      1. for each modified disk:
8762

8763
        1. remove old LVs (which have the name name_replaces.<time_t>)
8764

8765
    Failures are not very well handled.
8766

8767
    """
8768
    steps_total = 6
8769

    
8770
    # Step: check device activation
8771
    self.lu.LogStep(1, steps_total, "Check device existence")
8772
    self._CheckDisksExistence([self.other_node, self.target_node])
8773
    self._CheckVolumeGroup([self.target_node, self.other_node])
8774

    
8775
    # Step: check other node consistency
8776
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8777
    self._CheckDisksConsistency(self.other_node,
8778
                                self.other_node == self.instance.primary_node,
8779
                                False)
8780

    
8781
    # Step: create new storage
8782
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8783
    iv_names = self._CreateNewStorage(self.target_node)
8784

    
8785
    # Step: for each lv, detach+rename*2+attach
8786
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8787
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8788
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8789

    
8790
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8791
                                                     old_lvs)
8792
      result.Raise("Can't detach drbd from local storage on node"
8793
                   " %s for device %s" % (self.target_node, dev.iv_name))
8794
      #dev.children = []
8795
      #cfg.Update(instance)
8796

    
8797
      # ok, we created the new LVs, so now we know we have the needed
8798
      # storage; as such, we proceed on the target node to rename
8799
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8800
      # using the assumption that logical_id == physical_id (which in
8801
      # turn is the unique_id on that node)
8802

    
8803
      # FIXME(iustin): use a better name for the replaced LVs
8804
      temp_suffix = int(time.time())
8805
      ren_fn = lambda d, suff: (d.physical_id[0],
8806
                                d.physical_id[1] + "_replaced-%s" % suff)
8807

    
8808
      # Build the rename list based on what LVs exist on the node
8809
      rename_old_to_new = []
8810
      for to_ren in old_lvs:
8811
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8812
        if not result.fail_msg and result.payload:
8813
          # device exists
8814
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8815

    
8816
      self.lu.LogInfo("Renaming the old LVs on the target node")
8817
      result = self.rpc.call_blockdev_rename(self.target_node,
8818
                                             rename_old_to_new)
8819
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8820

    
8821
      # Now we rename the new LVs to the old LVs
8822
      self.lu.LogInfo("Renaming the new LVs on the target node")
8823
      rename_new_to_old = [(new, old.physical_id)
8824
                           for old, new in zip(old_lvs, new_lvs)]
8825
      result = self.rpc.call_blockdev_rename(self.target_node,
8826
                                             rename_new_to_old)
8827
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8828

    
8829
      for old, new in zip(old_lvs, new_lvs):
8830
        new.logical_id = old.logical_id
8831
        self.cfg.SetDiskID(new, self.target_node)
8832

    
8833
      for disk in old_lvs:
8834
        disk.logical_id = ren_fn(disk, temp_suffix)
8835
        self.cfg.SetDiskID(disk, self.target_node)
8836

    
8837
      # Now that the new lvs have the old name, we can add them to the device
8838
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8839
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8840
                                                  new_lvs)
8841
      msg = result.fail_msg
8842
      if msg:
8843
        for new_lv in new_lvs:
8844
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8845
                                               new_lv).fail_msg
8846
          if msg2:
8847
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8848
                               hint=("cleanup manually the unused logical"
8849
                                     "volumes"))
8850
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8851

    
8852
      dev.children = new_lvs
8853

    
8854
      self.cfg.Update(self.instance, feedback_fn)
8855

    
8856
    cstep = 5
8857
    if self.early_release:
8858
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8859
      cstep += 1
8860
      self._RemoveOldStorage(self.target_node, iv_names)
8861
      # WARNING: we release both node locks here, do not do other RPCs
8862
      # than WaitForSync to the primary node
8863
      self._ReleaseNodeLock([self.target_node, self.other_node])
8864

    
8865
    # Wait for sync
8866
    # This can fail as the old devices are degraded and _WaitForSync
8867
    # does a combined result over all disks, so we don't check its return value
8868
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8869
    cstep += 1
8870
    _WaitForSync(self.lu, self.instance)
8871

    
8872
    # Check all devices manually
8873
    self._CheckDevices(self.instance.primary_node, iv_names)
8874

    
8875
    # Step: remove old storage
8876
    if not self.early_release:
8877
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8878
      cstep += 1
8879
      self._RemoveOldStorage(self.target_node, iv_names)
8880

    
8881
  def _ExecDrbd8Secondary(self, feedback_fn):
8882
    """Replace the secondary node for DRBD 8.
8883

8884
    The algorithm for replace is quite complicated:
8885
      - for all disks of the instance:
8886
        - create new LVs on the new node with same names
8887
        - shutdown the drbd device on the old secondary
8888
        - disconnect the drbd network on the primary
8889
        - create the drbd device on the new secondary
8890
        - network attach the drbd on the primary, using an artifice:
8891
          the drbd code for Attach() will connect to the network if it
8892
          finds a device which is connected to the good local disks but
8893
          not network enabled
8894
      - wait for sync across all devices
8895
      - remove all disks from the old secondary
8896

8897
    Failures are not very well handled.
8898

8899
    """
8900
    steps_total = 6
8901

    
8902
    # Step: check device activation
8903
    self.lu.LogStep(1, steps_total, "Check device existence")
8904
    self._CheckDisksExistence([self.instance.primary_node])
8905
    self._CheckVolumeGroup([self.instance.primary_node])
8906

    
8907
    # Step: check other node consistency
8908
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8909
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8910

    
8911
    # Step: create new storage
8912
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8913
    for idx, dev in enumerate(self.instance.disks):
8914
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8915
                      (self.new_node, idx))
8916
      # we pass force_create=True to force LVM creation
8917
      for new_lv in dev.children:
8918
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8919
                        _GetInstanceInfoText(self.instance), False)
8920

    
8921
    # Step 4: dbrd minors and drbd setups changes
8922
    # after this, we must manually remove the drbd minors on both the
8923
    # error and the success paths
8924
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8925
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8926
                                         for dev in self.instance.disks],
8927
                                        self.instance.name)
8928
    logging.debug("Allocated minors %r", minors)
8929

    
8930
    iv_names = {}
8931
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8932
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8933
                      (self.new_node, idx))
8934
      # create new devices on new_node; note that we create two IDs:
8935
      # one without port, so the drbd will be activated without
8936
      # networking information on the new node at this stage, and one
8937
      # with network, for the latter activation in step 4
8938
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8939
      if self.instance.primary_node == o_node1:
8940
        p_minor = o_minor1
8941
      else:
8942
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8943
        p_minor = o_minor2
8944

    
8945
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8946
                      p_minor, new_minor, o_secret)
8947
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8948
                    p_minor, new_minor, o_secret)
8949

    
8950
      iv_names[idx] = (dev, dev.children, new_net_id)
8951
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8952
                    new_net_id)
8953
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8954
                              logical_id=new_alone_id,
8955
                              children=dev.children,
8956
                              size=dev.size)
8957
      try:
8958
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8959
                              _GetInstanceInfoText(self.instance), False)
8960
      except errors.GenericError:
8961
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8962
        raise
8963

    
8964
    # We have new devices, shutdown the drbd on the old secondary
8965
    for idx, dev in enumerate(self.instance.disks):
8966
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8967
      self.cfg.SetDiskID(dev, self.target_node)
8968
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8969
      if msg:
8970
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8971
                           "node: %s" % (idx, msg),
8972
                           hint=("Please cleanup this device manually as"
8973
                                 " soon as possible"))
8974

    
8975
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8976
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8977
                                               self.node_secondary_ip,
8978
                                               self.instance.disks)\
8979
                                              [self.instance.primary_node]
8980

    
8981
    msg = result.fail_msg
8982
    if msg:
8983
      # detaches didn't succeed (unlikely)
8984
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8985
      raise errors.OpExecError("Can't detach the disks from the network on"
8986
                               " old node: %s" % (msg,))
8987

    
8988
    # if we managed to detach at least one, we update all the disks of
8989
    # the instance to point to the new secondary
8990
    self.lu.LogInfo("Updating instance configuration")
8991
    for dev, _, new_logical_id in iv_names.itervalues():
8992
      dev.logical_id = new_logical_id
8993
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8994

    
8995
    self.cfg.Update(self.instance, feedback_fn)
8996

    
8997
    # and now perform the drbd attach
8998
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8999
                    " (standalone => connected)")
9000
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9001
                                            self.new_node],
9002
                                           self.node_secondary_ip,
9003
                                           self.instance.disks,
9004
                                           self.instance.name,
9005
                                           False)
9006
    for to_node, to_result in result.items():
9007
      msg = to_result.fail_msg
9008
      if msg:
9009
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9010
                           to_node, msg,
9011
                           hint=("please do a gnt-instance info to see the"
9012
                                 " status of disks"))
9013
    cstep = 5
9014
    if self.early_release:
9015
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9016
      cstep += 1
9017
      self._RemoveOldStorage(self.target_node, iv_names)
9018
      # WARNING: we release all node locks here, do not do other RPCs
9019
      # than WaitForSync to the primary node
9020
      self._ReleaseNodeLock([self.instance.primary_node,
9021
                             self.target_node,
9022
                             self.new_node])
9023

    
9024
    # Wait for sync
9025
    # This can fail as the old devices are degraded and _WaitForSync
9026
    # does a combined result over all disks, so we don't check its return value
9027
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9028
    cstep += 1
9029
    _WaitForSync(self.lu, self.instance)
9030

    
9031
    # Check all devices manually
9032
    self._CheckDevices(self.instance.primary_node, iv_names)
9033

    
9034
    # Step: remove old storage
9035
    if not self.early_release:
9036
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9037
      self._RemoveOldStorage(self.target_node, iv_names)
9038

    
9039

    
9040
class LURepairNodeStorage(NoHooksLU):
9041
  """Repairs the volume group on a node.
9042

9043
  """
9044
  REQ_BGL = False
9045

    
9046
  def CheckArguments(self):
9047
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9048

    
9049
    storage_type = self.op.storage_type
9050

    
9051
    if (constants.SO_FIX_CONSISTENCY not in
9052
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9053
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9054
                                 " repaired" % storage_type,
9055
                                 errors.ECODE_INVAL)
9056

    
9057
  def ExpandNames(self):
9058
    self.needed_locks = {
9059
      locking.LEVEL_NODE: [self.op.node_name],
9060
      }
9061

    
9062
  def _CheckFaultyDisks(self, instance, node_name):
9063
    """Ensure faulty disks abort the opcode or at least warn."""
9064
    try:
9065
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9066
                                  node_name, True):
9067
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9068
                                   " node '%s'" % (instance.name, node_name),
9069
                                   errors.ECODE_STATE)
9070
    except errors.OpPrereqError, err:
9071
      if self.op.ignore_consistency:
9072
        self.proc.LogWarning(str(err.args[0]))
9073
      else:
9074
        raise
9075

    
9076
  def CheckPrereq(self):
9077
    """Check prerequisites.
9078

9079
    """
9080
    # Check whether any instance on this node has faulty disks
9081
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9082
      if not inst.admin_up:
9083
        continue
9084
      check_nodes = set(inst.all_nodes)
9085
      check_nodes.discard(self.op.node_name)
9086
      for inst_node_name in check_nodes:
9087
        self._CheckFaultyDisks(inst, inst_node_name)
9088

    
9089
  def Exec(self, feedback_fn):
9090
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9091
                (self.op.name, self.op.node_name))
9092

    
9093
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9094
    result = self.rpc.call_storage_execute(self.op.node_name,
9095
                                           self.op.storage_type, st_args,
9096
                                           self.op.name,
9097
                                           constants.SO_FIX_CONSISTENCY)
9098
    result.Raise("Failed to repair storage unit '%s' on %s" %
9099
                 (self.op.name, self.op.node_name))
9100

    
9101

    
9102
class LUNodeEvacStrategy(NoHooksLU):
9103
  """Computes the node evacuation strategy.
9104

9105
  """
9106
  REQ_BGL = False
9107

    
9108
  def CheckArguments(self):
9109
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9110

    
9111
  def ExpandNames(self):
9112
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9113
    self.needed_locks = locks = {}
9114
    if self.op.remote_node is None:
9115
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9116
    else:
9117
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9118
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9119

    
9120
  def Exec(self, feedback_fn):
9121
    if self.op.remote_node is not None:
9122
      instances = []
9123
      for node in self.op.nodes:
9124
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9125
      result = []
9126
      for i in instances:
9127
        if i.primary_node == self.op.remote_node:
9128
          raise errors.OpPrereqError("Node %s is the primary node of"
9129
                                     " instance %s, cannot use it as"
9130
                                     " secondary" %
9131
                                     (self.op.remote_node, i.name),
9132
                                     errors.ECODE_INVAL)
9133
        result.append([i.name, self.op.remote_node])
9134
    else:
9135
      ial = IAllocator(self.cfg, self.rpc,
9136
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9137
                       evac_nodes=self.op.nodes)
9138
      ial.Run(self.op.iallocator, validate=True)
9139
      if not ial.success:
9140
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9141
                                 errors.ECODE_NORES)
9142
      result = ial.result
9143
    return result
9144

    
9145

    
9146
class LUInstanceGrowDisk(LogicalUnit):
9147
  """Grow a disk of an instance.
9148

9149
  """
9150
  HPATH = "disk-grow"
9151
  HTYPE = constants.HTYPE_INSTANCE
9152
  REQ_BGL = False
9153

    
9154
  def ExpandNames(self):
9155
    self._ExpandAndLockInstance()
9156
    self.needed_locks[locking.LEVEL_NODE] = []
9157
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9158

    
9159
  def DeclareLocks(self, level):
9160
    if level == locking.LEVEL_NODE:
9161
      self._LockInstancesNodes()
9162

    
9163
  def BuildHooksEnv(self):
9164
    """Build hooks env.
9165

9166
    This runs on the master, the primary and all the secondaries.
9167

9168
    """
9169
    env = {
9170
      "DISK": self.op.disk,
9171
      "AMOUNT": self.op.amount,
9172
      }
9173
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9174
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9175
    return env, nl, nl
9176

    
9177
  def CheckPrereq(self):
9178
    """Check prerequisites.
9179

9180
    This checks that the instance is in the cluster.
9181

9182
    """
9183
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9184
    assert instance is not None, \
9185
      "Cannot retrieve locked instance %s" % self.op.instance_name
9186
    nodenames = list(instance.all_nodes)
9187
    for node in nodenames:
9188
      _CheckNodeOnline(self, node)
9189

    
9190
    self.instance = instance
9191

    
9192
    if instance.disk_template not in constants.DTS_GROWABLE:
9193
      raise errors.OpPrereqError("Instance's disk layout does not support"
9194
                                 " growing.", errors.ECODE_INVAL)
9195

    
9196
    self.disk = instance.FindDisk(self.op.disk)
9197

    
9198
    if instance.disk_template not in (constants.DT_FILE,
9199
                                      constants.DT_SHARED_FILE):
9200
      # TODO: check the free disk space for file, when that feature will be
9201
      # supported
9202
      _CheckNodesFreeDiskPerVG(self, nodenames,
9203
                               self.disk.ComputeGrowth(self.op.amount))
9204

    
9205
  def Exec(self, feedback_fn):
9206
    """Execute disk grow.
9207

9208
    """
9209
    instance = self.instance
9210
    disk = self.disk
9211

    
9212
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9213
    if not disks_ok:
9214
      raise errors.OpExecError("Cannot activate block device to grow")
9215

    
9216
    for node in instance.all_nodes:
9217
      self.cfg.SetDiskID(disk, node)
9218
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
9219
      result.Raise("Grow request failed to node %s" % node)
9220

    
9221
      # TODO: Rewrite code to work properly
9222
      # DRBD goes into sync mode for a short amount of time after executing the
9223
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9224
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9225
      # time is a work-around.
9226
      time.sleep(5)
9227

    
9228
    disk.RecordGrow(self.op.amount)
9229
    self.cfg.Update(instance, feedback_fn)
9230
    if self.op.wait_for_sync:
9231
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9232
      if disk_abort:
9233
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
9234
                             " status.\nPlease check the instance.")
9235
      if not instance.admin_up:
9236
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9237
    elif not instance.admin_up:
9238
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9239
                           " not supposed to be running because no wait for"
9240
                           " sync mode was requested.")
9241

    
9242

    
9243
class LUInstanceQueryData(NoHooksLU):
9244
  """Query runtime instance data.
9245

9246
  """
9247
  REQ_BGL = False
9248

    
9249
  def ExpandNames(self):
9250
    self.needed_locks = {}
9251

    
9252
    # Use locking if requested or when non-static information is wanted
9253
    if not (self.op.static or self.op.use_locking):
9254
      self.LogWarning("Non-static data requested, locks need to be acquired")
9255
      self.op.use_locking = True
9256

    
9257
    if self.op.instances or not self.op.use_locking:
9258
      # Expand instance names right here
9259
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
9260
    else:
9261
      # Will use acquired locks
9262
      self.wanted_names = None
9263

    
9264
    if self.op.use_locking:
9265
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9266

    
9267
      if self.wanted_names is None:
9268
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9269
      else:
9270
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9271

    
9272
      self.needed_locks[locking.LEVEL_NODE] = []
9273
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9274
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9275

    
9276
  def DeclareLocks(self, level):
9277
    if self.op.use_locking and level == locking.LEVEL_NODE:
9278
      self._LockInstancesNodes()
9279

    
9280
  def CheckPrereq(self):
9281
    """Check prerequisites.
9282

9283
    This only checks the optional instance list against the existing names.
9284

9285
    """
9286
    if self.wanted_names is None:
9287
      assert self.op.use_locking, "Locking was not used"
9288
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
9289

    
9290
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
9291
                             for name in self.wanted_names]
9292

    
9293
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9294
    """Returns the status of a block device
9295

9296
    """
9297
    if self.op.static or not node:
9298
      return None
9299

    
9300
    self.cfg.SetDiskID(dev, node)
9301

    
9302
    result = self.rpc.call_blockdev_find(node, dev)
9303
    if result.offline:
9304
      return None
9305

    
9306
    result.Raise("Can't compute disk status for %s" % instance_name)
9307

    
9308
    status = result.payload
9309
    if status is None:
9310
      return None
9311

    
9312
    return (status.dev_path, status.major, status.minor,
9313
            status.sync_percent, status.estimated_time,
9314
            status.is_degraded, status.ldisk_status)
9315

    
9316
  def _ComputeDiskStatus(self, instance, snode, dev):
9317
    """Compute block device status.
9318

9319
    """
9320
    if dev.dev_type in constants.LDS_DRBD:
9321
      # we change the snode then (otherwise we use the one passed in)
9322
      if dev.logical_id[0] == instance.primary_node:
9323
        snode = dev.logical_id[1]
9324
      else:
9325
        snode = dev.logical_id[0]
9326

    
9327
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9328
                                              instance.name, dev)
9329
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9330

    
9331
    if dev.children:
9332
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9333
                      for child in dev.children]
9334
    else:
9335
      dev_children = []
9336

    
9337
    return {
9338
      "iv_name": dev.iv_name,
9339
      "dev_type": dev.dev_type,
9340
      "logical_id": dev.logical_id,
9341
      "physical_id": dev.physical_id,
9342
      "pstatus": dev_pstatus,
9343
      "sstatus": dev_sstatus,
9344
      "children": dev_children,
9345
      "mode": dev.mode,
9346
      "size": dev.size,
9347
      }
9348

    
9349
  def Exec(self, feedback_fn):
9350
    """Gather and return data"""
9351
    result = {}
9352

    
9353
    cluster = self.cfg.GetClusterInfo()
9354

    
9355
    for instance in self.wanted_instances:
9356
      if not self.op.static:
9357
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9358
                                                  instance.name,
9359
                                                  instance.hypervisor)
9360
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9361
        remote_info = remote_info.payload
9362
        if remote_info and "state" in remote_info:
9363
          remote_state = "up"
9364
        else:
9365
          remote_state = "down"
9366
      else:
9367
        remote_state = None
9368
      if instance.admin_up:
9369
        config_state = "up"
9370
      else:
9371
        config_state = "down"
9372

    
9373
      disks = [self._ComputeDiskStatus(instance, None, device)
9374
               for device in instance.disks]
9375

    
9376
      result[instance.name] = {
9377
        "name": instance.name,
9378
        "config_state": config_state,
9379
        "run_state": remote_state,
9380
        "pnode": instance.primary_node,
9381
        "snodes": instance.secondary_nodes,
9382
        "os": instance.os,
9383
        # this happens to be the same format used for hooks
9384
        "nics": _NICListToTuple(self, instance.nics),
9385
        "disk_template": instance.disk_template,
9386
        "disks": disks,
9387
        "hypervisor": instance.hypervisor,
9388
        "network_port": instance.network_port,
9389
        "hv_instance": instance.hvparams,
9390
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9391
        "be_instance": instance.beparams,
9392
        "be_actual": cluster.FillBE(instance),
9393
        "os_instance": instance.osparams,
9394
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9395
        "serial_no": instance.serial_no,
9396
        "mtime": instance.mtime,
9397
        "ctime": instance.ctime,
9398
        "uuid": instance.uuid,
9399
        }
9400

    
9401
    return result
9402

    
9403

    
9404
class LUInstanceSetParams(LogicalUnit):
9405
  """Modifies an instances's parameters.
9406

9407
  """
9408
  HPATH = "instance-modify"
9409
  HTYPE = constants.HTYPE_INSTANCE
9410
  REQ_BGL = False
9411

    
9412
  def CheckArguments(self):
9413
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9414
            self.op.hvparams or self.op.beparams or self.op.os_name):
9415
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9416

    
9417
    if self.op.hvparams:
9418
      _CheckGlobalHvParams(self.op.hvparams)
9419

    
9420
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9421

    
9422
    # Disk validation
9423
    disk_addremove = 0
9424
    for disk_op, disk_dict in self.op.disks:
9425
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9426
      if disk_op == constants.DDM_REMOVE:
9427
        disk_addremove += 1
9428
        continue
9429
      elif disk_op == constants.DDM_ADD:
9430
        disk_addremove += 1
9431
      else:
9432
        if not isinstance(disk_op, int):
9433
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9434
        if not isinstance(disk_dict, dict):
9435
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9436
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9437

    
9438
      if disk_op == constants.DDM_ADD:
9439
        if "adopt" in disk_dict:
9440
          has_adopt = True
9441
        else:
9442
          has_adopt = False
9443

    
9444
        if has_adopt:
9445
          if instance.disk_template not in constants.DTS_MAY_ADOPT:
9446
            raise errors.OpPrereqError("Disk adoption is not supported for the"
9447
                                       " '%s' disk template" %
9448
                                       instance.disk_template,
9449
                                       errors.ECODE_INVAL)
9450
        self.adopt_disks = has_adopt
9451

    
9452
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
9453
        if mode not in constants.DISK_ACCESS_SET:
9454
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9455
                                     errors.ECODE_INVAL)
9456
        if not has_adopt:
9457
          size = disk_dict.get('size', None)
9458
          if size is None:
9459
            raise errors.OpPrereqError("Required disk parameter size missing",
9460
                                       errors.ECODE_INVAL)
9461
          try:
9462
            size = int(size)
9463
          except (TypeError, ValueError), err:
9464
            raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9465
                                       str(err), errors.ECODE_INVAL)
9466
          disk_dict['size'] = size
9467
      else:
9468
        # modification of disk
9469
        if 'size' in disk_dict:
9470
          raise errors.OpPrereqError("Disk size change not possible, use"
9471
                                     " grow-disk", errors.ECODE_INVAL)
9472

    
9473
    if disk_addremove > 1:
9474
      raise errors.OpPrereqError("Only one disk add or remove operation"
9475
                                 " supported at a time", errors.ECODE_INVAL)
9476

    
9477
    if self.op.disks and self.op.disk_template is not None:
9478
      raise errors.OpPrereqError("Disk template conversion and other disk"
9479
                                 " changes not supported at the same time",
9480
                                 errors.ECODE_INVAL)
9481

    
9482
    if (self.op.disk_template and
9483
        self.op.disk_template in constants.DTS_INT_MIRROR and
9484
        self.op.remote_node is None):
9485
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9486
                                 " one requires specifying a secondary node",
9487
                                 errors.ECODE_INVAL)
9488

    
9489
    # NIC validation
9490
    nic_addremove = 0
9491
    for nic_op, nic_dict in self.op.nics:
9492
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9493
      if nic_op == constants.DDM_REMOVE:
9494
        nic_addremove += 1
9495
        continue
9496
      elif nic_op == constants.DDM_ADD:
9497
        nic_addremove += 1
9498
      else:
9499
        if not isinstance(nic_op, int):
9500
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9501
        if not isinstance(nic_dict, dict):
9502
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9503
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9504

    
9505
      # nic_dict should be a dict
9506
      nic_ip = nic_dict.get('ip', None)
9507
      if nic_ip is not None:
9508
        if nic_ip.lower() == constants.VALUE_NONE:
9509
          nic_dict['ip'] = None
9510
        else:
9511
          if not netutils.IPAddress.IsValid(nic_ip):
9512
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9513
                                       errors.ECODE_INVAL)
9514

    
9515
      nic_bridge = nic_dict.get('bridge', None)
9516
      nic_link = nic_dict.get('link', None)
9517
      if nic_bridge and nic_link:
9518
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9519
                                   " at the same time", errors.ECODE_INVAL)
9520
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9521
        nic_dict['bridge'] = None
9522
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9523
        nic_dict['link'] = None
9524

    
9525
      if nic_op == constants.DDM_ADD:
9526
        nic_mac = nic_dict.get('mac', None)
9527
        if nic_mac is None:
9528
          nic_dict['mac'] = constants.VALUE_AUTO
9529

    
9530
      if 'mac' in nic_dict:
9531
        nic_mac = nic_dict['mac']
9532
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9533
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9534

    
9535
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9536
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9537
                                     " modifying an existing nic",
9538
                                     errors.ECODE_INVAL)
9539

    
9540
    if nic_addremove > 1:
9541
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9542
                                 " supported at a time", errors.ECODE_INVAL)
9543

    
9544
  def ExpandNames(self):
9545
    self._ExpandAndLockInstance()
9546
    self.needed_locks[locking.LEVEL_NODE] = []
9547
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9548

    
9549
  def DeclareLocks(self, level):
9550
    if level == locking.LEVEL_NODE:
9551
      self._LockInstancesNodes()
9552
      if self.op.disk_template and self.op.remote_node:
9553
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9554
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9555

    
9556
  def BuildHooksEnv(self):
9557
    """Build hooks env.
9558

9559
    This runs on the master, primary and secondaries.
9560

9561
    """
9562
    args = dict()
9563
    if constants.BE_MEMORY in self.be_new:
9564
      args['memory'] = self.be_new[constants.BE_MEMORY]
9565
    if constants.BE_VCPUS in self.be_new:
9566
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9567
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9568
    # information at all.
9569
    if self.op.nics:
9570
      args['nics'] = []
9571
      nic_override = dict(self.op.nics)
9572
      for idx, nic in enumerate(self.instance.nics):
9573
        if idx in nic_override:
9574
          this_nic_override = nic_override[idx]
9575
        else:
9576
          this_nic_override = {}
9577
        if 'ip' in this_nic_override:
9578
          ip = this_nic_override['ip']
9579
        else:
9580
          ip = nic.ip
9581
        if 'mac' in this_nic_override:
9582
          mac = this_nic_override['mac']
9583
        else:
9584
          mac = nic.mac
9585
        if idx in self.nic_pnew:
9586
          nicparams = self.nic_pnew[idx]
9587
        else:
9588
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9589
        mode = nicparams[constants.NIC_MODE]
9590
        link = nicparams[constants.NIC_LINK]
9591
        args['nics'].append((ip, mac, mode, link))
9592
      if constants.DDM_ADD in nic_override:
9593
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9594
        mac = nic_override[constants.DDM_ADD]['mac']
9595
        nicparams = self.nic_pnew[constants.DDM_ADD]
9596
        mode = nicparams[constants.NIC_MODE]
9597
        link = nicparams[constants.NIC_LINK]
9598
        args['nics'].append((ip, mac, mode, link))
9599
      elif constants.DDM_REMOVE in nic_override:
9600
        del args['nics'][-1]
9601

    
9602
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9603
    if self.op.disk_template:
9604
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9605
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9606
    return env, nl, nl
9607

    
9608
  def CheckPrereq(self):
9609
    """Check prerequisites.
9610

9611
    This only checks the instance list against the existing names.
9612

9613
    """
9614
    # checking the new params on the primary/secondary nodes
9615

    
9616
    instance = self.instance
9617
    cluster = self.cluster = self.cfg.GetClusterInfo()
9618
    assert self.instance is not None, \
9619
      "Cannot retrieve locked instance %s" % self.op.instance_name
9620
    pnode = instance.primary_node
9621
    nodelist = list(instance.all_nodes)
9622

    
9623
    # OS change
9624
    if self.op.os_name and not self.op.force:
9625
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9626
                      self.op.force_variant)
9627
      instance_os = self.op.os_name
9628
    else:
9629
      instance_os = instance.os
9630

    
9631
    if self.op.disk_template:
9632
      if instance.disk_template == self.op.disk_template:
9633
        raise errors.OpPrereqError("Instance already has disk template %s" %
9634
                                   instance.disk_template, errors.ECODE_INVAL)
9635

    
9636
      if (instance.disk_template,
9637
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9638
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9639
                                   " %s to %s" % (instance.disk_template,
9640
                                                  self.op.disk_template),
9641
                                   errors.ECODE_INVAL)
9642
      _CheckInstanceDown(self, instance, "cannot change disk template")
9643
      if self.op.disk_template in constants.DTS_INT_MIRROR:
9644
        if self.op.remote_node == pnode:
9645
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9646
                                     " as the primary node of the instance" %
9647
                                     self.op.remote_node, errors.ECODE_STATE)
9648
        _CheckNodeOnline(self, self.op.remote_node)
9649
        _CheckNodeNotDrained(self, self.op.remote_node)
9650
        # FIXME: here we assume that the old instance type is DT_PLAIN
9651
        assert instance.disk_template == constants.DT_PLAIN
9652
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9653
                 for d in instance.disks]
9654
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9655
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9656

    
9657
    # hvparams processing
9658
    if self.op.hvparams:
9659
      hv_type = instance.hypervisor
9660
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9661
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9662
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9663

    
9664
      # local check
9665
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9666
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9667
      self.hv_new = hv_new # the new actual values
9668
      self.hv_inst = i_hvdict # the new dict (without defaults)
9669
    else:
9670
      self.hv_new = self.hv_inst = {}
9671

    
9672
    # beparams processing
9673
    if self.op.beparams:
9674
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9675
                                   use_none=True)
9676
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9677
      be_new = cluster.SimpleFillBE(i_bedict)
9678
      self.be_new = be_new # the new actual values
9679
      self.be_inst = i_bedict # the new dict (without defaults)
9680
    else:
9681
      self.be_new = self.be_inst = {}
9682
    be_old = cluster.FillBE(instance)
9683

    
9684
    # osparams processing
9685
    if self.op.osparams:
9686
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9687
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9688
      self.os_inst = i_osdict # the new dict (without defaults)
9689
    else:
9690
      self.os_inst = {}
9691

    
9692
    self.warn = []
9693

    
9694
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
9695
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
9696
      mem_check_list = [pnode]
9697
      if be_new[constants.BE_AUTO_BALANCE]:
9698
        # either we changed auto_balance to yes or it was from before
9699
        mem_check_list.extend(instance.secondary_nodes)
9700
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9701
                                                  instance.hypervisor)
9702
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9703
                                         instance.hypervisor)
9704
      pninfo = nodeinfo[pnode]
9705
      msg = pninfo.fail_msg
9706
      if msg:
9707
        # Assume the primary node is unreachable and go ahead
9708
        self.warn.append("Can't get info from primary node %s: %s" %
9709
                         (pnode,  msg))
9710
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9711
        self.warn.append("Node data from primary node %s doesn't contain"
9712
                         " free memory information" % pnode)
9713
      elif instance_info.fail_msg:
9714
        self.warn.append("Can't get instance runtime information: %s" %
9715
                        instance_info.fail_msg)
9716
      else:
9717
        if instance_info.payload:
9718
          current_mem = int(instance_info.payload['memory'])
9719
        else:
9720
          # Assume instance not running
9721
          # (there is a slight race condition here, but it's not very probable,
9722
          # and we have no other way to check)
9723
          current_mem = 0
9724
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9725
                    pninfo.payload['memory_free'])
9726
        if miss_mem > 0:
9727
          raise errors.OpPrereqError("This change will prevent the instance"
9728
                                     " from starting, due to %d MB of memory"
9729
                                     " missing on its primary node" % miss_mem,
9730
                                     errors.ECODE_NORES)
9731

    
9732
      if be_new[constants.BE_AUTO_BALANCE]:
9733
        for node, nres in nodeinfo.items():
9734
          if node not in instance.secondary_nodes:
9735
            continue
9736
          nres.Raise("Can't get info from secondary node %s" % node,
9737
                     prereq=True, ecode=errors.ECODE_STATE)
9738
          if not isinstance(nres.payload.get('memory_free', None), int):
9739
            raise errors.OpPrereqError("Secondary node %s didn't return free"
9740
                                       " memory information" % node,
9741
                                       errors.ECODE_STATE)
9742
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9743
            raise errors.OpPrereqError("This change will prevent the instance"
9744
                                       " from failover to its secondary node"
9745
                                       " %s, due to not enough memory" % node,
9746
                                       errors.ECODE_STATE)
9747

    
9748
    # NIC processing
9749
    self.nic_pnew = {}
9750
    self.nic_pinst = {}
9751
    for nic_op, nic_dict in self.op.nics:
9752
      if nic_op == constants.DDM_REMOVE:
9753
        if not instance.nics:
9754
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9755
                                     errors.ECODE_INVAL)
9756
        continue
9757
      if nic_op != constants.DDM_ADD:
9758
        # an existing nic
9759
        if not instance.nics:
9760
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9761
                                     " no NICs" % nic_op,
9762
                                     errors.ECODE_INVAL)
9763
        if nic_op < 0 or nic_op >= len(instance.nics):
9764
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9765
                                     " are 0 to %d" %
9766
                                     (nic_op, len(instance.nics) - 1),
9767
                                     errors.ECODE_INVAL)
9768
        old_nic_params = instance.nics[nic_op].nicparams
9769
        old_nic_ip = instance.nics[nic_op].ip
9770
      else:
9771
        old_nic_params = {}
9772
        old_nic_ip = None
9773

    
9774
      update_params_dict = dict([(key, nic_dict[key])
9775
                                 for key in constants.NICS_PARAMETERS
9776
                                 if key in nic_dict])
9777

    
9778
      if 'bridge' in nic_dict:
9779
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9780

    
9781
      new_nic_params = _GetUpdatedParams(old_nic_params,
9782
                                         update_params_dict)
9783
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9784
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9785
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9786
      self.nic_pinst[nic_op] = new_nic_params
9787
      self.nic_pnew[nic_op] = new_filled_nic_params
9788
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9789

    
9790
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9791
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9792
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9793
        if msg:
9794
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9795
          if self.op.force:
9796
            self.warn.append(msg)
9797
          else:
9798
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9799
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9800
        if 'ip' in nic_dict:
9801
          nic_ip = nic_dict['ip']
9802
        else:
9803
          nic_ip = old_nic_ip
9804
        if nic_ip is None:
9805
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9806
                                     ' on a routed nic', errors.ECODE_INVAL)
9807
      if 'mac' in nic_dict:
9808
        nic_mac = nic_dict['mac']
9809
        if nic_mac is None:
9810
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9811
                                     errors.ECODE_INVAL)
9812
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9813
          # otherwise generate the mac
9814
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9815
        else:
9816
          # or validate/reserve the current one
9817
          try:
9818
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9819
          except errors.ReservationError:
9820
            raise errors.OpPrereqError("MAC address %s already in use"
9821
                                       " in cluster" % nic_mac,
9822
                                       errors.ECODE_NOTUNIQUE)
9823

    
9824
    # DISK processing
9825
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9826
      raise errors.OpPrereqError("Disk operations not supported for"
9827
                                 " diskless instances",
9828
                                 errors.ECODE_INVAL)
9829
    for disk_op, disk_dict in self.op.disks:
9830
      if disk_op == constants.DDM_REMOVE:
9831
        if len(instance.disks) == 1:
9832
          raise errors.OpPrereqError("Cannot remove the last disk of"
9833
                                     " an instance", errors.ECODE_INVAL)
9834
        _CheckInstanceDown(self, instance, "cannot remove disks")
9835

    
9836
      if (disk_op == constants.DDM_ADD and
9837
          len(instance.disks) >= constants.MAX_DISKS):
9838
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9839
                                   " add more" % constants.MAX_DISKS,
9840
                                   errors.ECODE_STATE)
9841
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9842
        # an existing disk
9843
        if disk_op < 0 or disk_op >= len(instance.disks):
9844
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9845
                                     " are 0 to %d" %
9846
                                     (disk_op, len(instance.disks)),
9847
                                     errors.ECODE_INVAL)
9848

    
9849
      if disk_op == constants.DDM_ADD and self.adopt_disks:
9850
        if instance.disk_template == constants.DT_PLAIN:
9851
          # Check the adoption data
9852
          vg = disk_dict.get("vg", self.cfg.GetVGName())
9853
          lv_name = vg + "/" + disk_dict["adopt"]
9854
          try:
9855
            # FIXME: lv_name here is "vg/lv" need to ensure that other calls
9856
            # to ReserveLV uses the same syntax
9857
            self.cfg.ReserveLV(lv_name, self.proc.GetECId())
9858
          except errors.ReservationError:
9859
            raise errors.OpPrereqError("LV named %s used by another instance" %
9860
                                       lv_name, errors.ECODE_NOTUNIQUE)
9861

    
9862
          vg_names = self.rpc.call_vg_list([instance.primary_node])
9863
          vg_names = vg_names[instance.primary_node]
9864
          vg_names.Raise("Cannot get VG information from node %s" %
9865
                         instance.primary_node)
9866

    
9867
          node_lvs = self.rpc.call_lv_list([instance.primary_node],
9868
                                           vg_names.payload.keys()
9869
                                          )[instance.primary_node]
9870
          node_lvs.Raise("Cannot get LV information from node %s" %
9871
                         instance.primary_node)
9872
          node_lvs = node_lvs.payload
9873

    
9874
          if lv_name not in node_lvs:
9875
            raise errors.OpPrereqError("Logical volume: %s not present "
9876
                                       " on node %s" %
9877
                                       (lv_name, instance.primary_node),
9878
                                       errors.ECODE_INVAL)
9879
          if node_lvs[lv_name][2]:
9880
            raise errors.OpPrereqError("Logical volume %s is online, cannot"
9881
                                       " adopt." % lv_name,
9882
                                       errors.ECODE_STATE)
9883
          # update the size of disk based on what is found
9884
          disk_dict["size"] = int(float(node_lvs[lv_name][0]))
9885

    
9886
        elif instance.disk_template == constants.DT_BLOCK:
9887
          disk = disk_dict["adopt"]
9888
          node_disks = self.rpc.call_bdev_sizes([instance.primary_node],
9889
                                                [disk])[instance.primary_node]
9890
          node_disks = node_disks.payload
9891
          if disk not in node_disks:
9892
            raise errors.OpPrereqError("Missing block device %s" % disk,
9893
                                       errors.ECODE_INVAL)
9894
          disk_dict["size"] = int(float(node_disks[disk]))
9895

    
9896
    return
9897

    
9898
  def _ConvertPlainToDrbd(self, feedback_fn):
9899
    """Converts an instance from plain to drbd.
9900

9901
    """
9902
    feedback_fn("Converting template to drbd")
9903
    instance = self.instance
9904
    pnode = instance.primary_node
9905
    snode = self.op.remote_node
9906

    
9907
    # create a fake disk info for _GenerateDiskTemplate
9908
    disk_info = [{"size": d.size, "mode": d.mode,
9909
                  "vg": d.logical_id[0]} for d in instance.disks]
9910
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9911
                                      instance.name, pnode, [snode],
9912
                                      disk_info, None, None, 0, feedback_fn)
9913
    info = _GetInstanceInfoText(instance)
9914
    feedback_fn("Creating aditional volumes...")
9915
    # first, create the missing data and meta devices
9916
    for disk in new_disks:
9917
      # unfortunately this is... not too nice
9918
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9919
                            info, True)
9920
      for child in disk.children:
9921
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9922
    # at this stage, all new LVs have been created, we can rename the
9923
    # old ones
9924
    feedback_fn("Renaming original volumes...")
9925
    rename_list = [(o, n.children[0].logical_id)
9926
                   for (o, n) in zip(instance.disks, new_disks)]
9927
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9928
    result.Raise("Failed to rename original LVs")
9929

    
9930
    feedback_fn("Initializing DRBD devices...")
9931
    # all child devices are in place, we can now create the DRBD devices
9932
    for disk in new_disks:
9933
      for node in [pnode, snode]:
9934
        f_create = node == pnode
9935
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9936

    
9937
    # at this point, the instance has been modified
9938
    instance.disk_template = constants.DT_DRBD8
9939
    instance.disks = new_disks
9940
    self.cfg.Update(instance, feedback_fn)
9941

    
9942
    # disks are created, waiting for sync
9943
    disk_abort = not _WaitForSync(self, instance,
9944
                                  oneshot=not self.op.wait_for_sync)
9945
    if disk_abort:
9946
      raise errors.OpExecError("There are some degraded disks for"
9947
                               " this instance, please cleanup manually")
9948

    
9949
  def _ConvertDrbdToPlain(self, feedback_fn):
9950
    """Converts an instance from drbd to plain.
9951

9952
    """
9953
    instance = self.instance
9954
    assert len(instance.secondary_nodes) == 1
9955
    pnode = instance.primary_node
9956
    snode = instance.secondary_nodes[0]
9957
    feedback_fn("Converting template to plain")
9958

    
9959
    old_disks = instance.disks
9960
    new_disks = [d.children[0] for d in old_disks]
9961

    
9962
    # copy over size and mode
9963
    for parent, child in zip(old_disks, new_disks):
9964
      child.size = parent.size
9965
      child.mode = parent.mode
9966

    
9967
    # update instance structure
9968
    instance.disks = new_disks
9969
    instance.disk_template = constants.DT_PLAIN
9970
    self.cfg.Update(instance, feedback_fn)
9971

    
9972
    feedback_fn("Removing volumes on the secondary node...")
9973
    for disk in old_disks:
9974
      self.cfg.SetDiskID(disk, snode)
9975
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9976
      if msg:
9977
        self.LogWarning("Could not remove block device %s on node %s,"
9978
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9979

    
9980
    feedback_fn("Removing unneeded volumes on the primary node...")
9981
    for idx, disk in enumerate(old_disks):
9982
      meta = disk.children[1]
9983
      self.cfg.SetDiskID(meta, pnode)
9984
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9985
      if msg:
9986
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9987
                        " continuing anyway: %s", idx, pnode, msg)
9988

    
9989
  def Exec(self, feedback_fn):
9990
    """Modifies an instance.
9991

9992
    All parameters take effect only at the next restart of the instance.
9993

9994
    """
9995
    # Process here the warnings from CheckPrereq, as we don't have a
9996
    # feedback_fn there.
9997
    for warn in self.warn:
9998
      feedback_fn("WARNING: %s" % warn)
9999

    
10000
    result = []
10001
    instance = self.instance
10002
    # disk changes
10003
    for disk_op, disk_dict in self.op.disks:
10004
      if disk_op == constants.DDM_REMOVE:
10005
        # remove the last disk
10006
        device = instance.disks.pop()
10007
        device_idx = len(instance.disks)
10008
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10009
          self.cfg.SetDiskID(disk, node)
10010
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10011
          if msg:
10012
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10013
                            " continuing anyway", device_idx, node, msg)
10014
        result.append(("disk/%d" % device_idx, "remove"))
10015
      elif disk_op == constants.DDM_ADD:
10016
        # add a new disk
10017
        if instance.disk_template in (constants.DT_FILE,
10018
                                        constants.DT_SHARED_FILE):
10019
          file_driver, file_path = instance.disks[0].logical_id
10020
          file_path = os.path.dirname(file_path)
10021
        else:
10022
          file_driver = file_path = None
10023
        disk_idx_base = len(instance.disks)
10024
        new_disk = _GenerateDiskTemplate(self,
10025
                                         instance.disk_template,
10026
                                         instance.name, instance.primary_node,
10027
                                         instance.secondary_nodes,
10028
                                         [disk_dict],
10029
                                         file_path,
10030
                                         file_driver,
10031
                                         disk_idx_base, feedback_fn)[0]
10032
        instance.disks.append(new_disk)
10033
        info = _GetInstanceInfoText(instance)
10034

    
10035
        if self.adopt_disks:
10036
          if instance.disk_template == constants.DT_PLAIN:
10037
            # rename LV to the a newly-generated name; we need to construct
10038
            # 'fake' LV disk with the old data, plus the new unique_id
10039
            tmp_disk = objects.Disk.FromDict(disk_dict)
10040
            rename_to = tmp_disk.logical_id
10041
            tmp_disk.logical_id = (tmp_disk.logical_id[0], disk_dict["adopt"])
10042
            self.cfg.SetDiskID(tmp_disk, instance.primary_node)
10043
            result = self.rpc.call_blockdev_rename(instance.primary_node,
10044
                                                   [(tmp_disk, rename_to)])
10045
            result.Raise("Failed to rename adopted LV")
10046
          result.append(("disk/%d" % disk_idx_base, "add:adopt=%s,mode=%s" %
10047
                         (disk_dict["adopt"], new_disk.mode)))
10048
        else:
10049
          logging.info("Creating volume %s for instance %s",
10050
                       new_disk.iv_name, instance.name)
10051
          # Note: this needs to be kept in sync with _CreateDisks
10052
          #HARDCODE
10053
          for node in instance.all_nodes:
10054
            f_create = node == instance.primary_node
10055
            try:
10056
              _CreateBlockDev(self, node, instance, new_disk,
10057
                              f_create, info, f_create)
10058
            except errors.OpExecError, err:
10059
              self.LogWarning("Failed to create volume %s (%s) on"
10060
                              " node %s: %s",
10061
                              new_disk.iv_name, new_disk, node, err)
10062
          result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10063
                         (new_disk.size, new_disk.mode)))
10064
      else:
10065
        # change a given disk
10066
        instance.disks[disk_op].mode = disk_dict['mode']
10067
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
10068

    
10069
    if self.op.disk_template:
10070
      r_shut = _ShutdownInstanceDisks(self, instance)
10071
      if not r_shut:
10072
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10073
                                 " proceed with disk template conversion")
10074
      mode = (instance.disk_template, self.op.disk_template)
10075
      try:
10076
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10077
      except:
10078
        self.cfg.ReleaseDRBDMinors(instance.name)
10079
        raise
10080
      result.append(("disk_template", self.op.disk_template))
10081

    
10082
    # NIC changes
10083
    for nic_op, nic_dict in self.op.nics:
10084
      if nic_op == constants.DDM_REMOVE:
10085
        # remove the last nic
10086
        del instance.nics[-1]
10087
        result.append(("nic.%d" % len(instance.nics), "remove"))
10088
      elif nic_op == constants.DDM_ADD:
10089
        # mac and bridge should be set, by now
10090
        mac = nic_dict['mac']
10091
        ip = nic_dict.get('ip', None)
10092
        nicparams = self.nic_pinst[constants.DDM_ADD]
10093
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10094
        instance.nics.append(new_nic)
10095
        result.append(("nic.%d" % (len(instance.nics) - 1),
10096
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10097
                       (new_nic.mac, new_nic.ip,
10098
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10099
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10100
                       )))
10101
      else:
10102
        for key in 'mac', 'ip':
10103
          if key in nic_dict:
10104
            setattr(instance.nics[nic_op], key, nic_dict[key])
10105
        if nic_op in self.nic_pinst:
10106
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10107
        for key, val in nic_dict.iteritems():
10108
          result.append(("nic.%s/%d" % (key, nic_op), val))
10109

    
10110
    # hvparams changes
10111
    if self.op.hvparams:
10112
      instance.hvparams = self.hv_inst
10113
      for key, val in self.op.hvparams.iteritems():
10114
        result.append(("hv/%s" % key, val))
10115

    
10116
    # beparams changes
10117
    if self.op.beparams:
10118
      instance.beparams = self.be_inst
10119
      for key, val in self.op.beparams.iteritems():
10120
        result.append(("be/%s" % key, val))
10121

    
10122
    # OS change
10123
    if self.op.os_name:
10124
      instance.os = self.op.os_name
10125

    
10126
    # osparams changes
10127
    if self.op.osparams:
10128
      instance.osparams = self.os_inst
10129
      for key, val in self.op.osparams.iteritems():
10130
        result.append(("os/%s" % key, val))
10131

    
10132
    self.cfg.Update(instance, feedback_fn)
10133

    
10134
    return result
10135

    
10136
  _DISK_CONVERSIONS = {
10137
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10138
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10139
    }
10140

    
10141

    
10142
class LUBackupQuery(NoHooksLU):
10143
  """Query the exports list
10144

10145
  """
10146
  REQ_BGL = False
10147

    
10148
  def ExpandNames(self):
10149
    self.needed_locks = {}
10150
    self.share_locks[locking.LEVEL_NODE] = 1
10151
    if not self.op.nodes:
10152
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10153
    else:
10154
      self.needed_locks[locking.LEVEL_NODE] = \
10155
        _GetWantedNodes(self, self.op.nodes)
10156

    
10157
  def Exec(self, feedback_fn):
10158
    """Compute the list of all the exported system images.
10159

10160
    @rtype: dict
10161
    @return: a dictionary with the structure node->(export-list)
10162
        where export-list is a list of the instances exported on
10163
        that node.
10164

10165
    """
10166
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
10167
    rpcresult = self.rpc.call_export_list(self.nodes)
10168
    result = {}
10169
    for node in rpcresult:
10170
      if rpcresult[node].fail_msg:
10171
        result[node] = False
10172
      else:
10173
        result[node] = rpcresult[node].payload
10174

    
10175
    return result
10176

    
10177

    
10178
class LUBackupPrepare(NoHooksLU):
10179
  """Prepares an instance for an export and returns useful information.
10180

10181
  """
10182
  REQ_BGL = False
10183

    
10184
  def ExpandNames(self):
10185
    self._ExpandAndLockInstance()
10186

    
10187
  def CheckPrereq(self):
10188
    """Check prerequisites.
10189

10190
    """
10191
    instance_name = self.op.instance_name
10192

    
10193
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10194
    assert self.instance is not None, \
10195
          "Cannot retrieve locked instance %s" % self.op.instance_name
10196
    _CheckNodeOnline(self, self.instance.primary_node)
10197

    
10198
    self._cds = _GetClusterDomainSecret()
10199

    
10200
  def Exec(self, feedback_fn):
10201
    """Prepares an instance for an export.
10202

10203
    """
10204
    instance = self.instance
10205

    
10206
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10207
      salt = utils.GenerateSecret(8)
10208

    
10209
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10210
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10211
                                              constants.RIE_CERT_VALIDITY)
10212
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10213

    
10214
      (name, cert_pem) = result.payload
10215

    
10216
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10217
                                             cert_pem)
10218

    
10219
      return {
10220
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10221
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10222
                          salt),
10223
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10224
        }
10225

    
10226
    return None
10227

    
10228

    
10229
class LUBackupExport(LogicalUnit):
10230
  """Export an instance to an image in the cluster.
10231

10232
  """
10233
  HPATH = "instance-export"
10234
  HTYPE = constants.HTYPE_INSTANCE
10235
  REQ_BGL = False
10236

    
10237
  def CheckArguments(self):
10238
    """Check the arguments.
10239

10240
    """
10241
    self.x509_key_name = self.op.x509_key_name
10242
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10243

    
10244
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10245
      if not self.x509_key_name:
10246
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10247
                                   errors.ECODE_INVAL)
10248

    
10249
      if not self.dest_x509_ca_pem:
10250
        raise errors.OpPrereqError("Missing destination X509 CA",
10251
                                   errors.ECODE_INVAL)
10252

    
10253
  def ExpandNames(self):
10254
    self._ExpandAndLockInstance()
10255

    
10256
    # Lock all nodes for local exports
10257
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10258
      # FIXME: lock only instance primary and destination node
10259
      #
10260
      # Sad but true, for now we have do lock all nodes, as we don't know where
10261
      # the previous export might be, and in this LU we search for it and
10262
      # remove it from its current node. In the future we could fix this by:
10263
      #  - making a tasklet to search (share-lock all), then create the
10264
      #    new one, then one to remove, after
10265
      #  - removing the removal operation altogether
10266
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10267

    
10268
  def DeclareLocks(self, level):
10269
    """Last minute lock declaration."""
10270
    # All nodes are locked anyway, so nothing to do here.
10271

    
10272
  def BuildHooksEnv(self):
10273
    """Build hooks env.
10274

10275
    This will run on the master, primary node and target node.
10276

10277
    """
10278
    env = {
10279
      "EXPORT_MODE": self.op.mode,
10280
      "EXPORT_NODE": self.op.target_node,
10281
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10282
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10283
      # TODO: Generic function for boolean env variables
10284
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10285
      }
10286

    
10287
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10288

    
10289
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10290

    
10291
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10292
      nl.append(self.op.target_node)
10293

    
10294
    return env, nl, nl
10295

    
10296
  def CheckPrereq(self):
10297
    """Check prerequisites.
10298

10299
    This checks that the instance and node names are valid.
10300

10301
    """
10302
    instance_name = self.op.instance_name
10303

    
10304
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10305
    assert self.instance is not None, \
10306
          "Cannot retrieve locked instance %s" % self.op.instance_name
10307
    _CheckNodeOnline(self, self.instance.primary_node)
10308

    
10309
    if (self.op.remove_instance and self.instance.admin_up and
10310
        not self.op.shutdown):
10311
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10312
                                 " down before")
10313

    
10314
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10315
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10316
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10317
      assert self.dst_node is not None
10318

    
10319
      _CheckNodeOnline(self, self.dst_node.name)
10320
      _CheckNodeNotDrained(self, self.dst_node.name)
10321

    
10322
      self._cds = None
10323
      self.dest_disk_info = None
10324
      self.dest_x509_ca = None
10325

    
10326
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10327
      self.dst_node = None
10328

    
10329
      if len(self.op.target_node) != len(self.instance.disks):
10330
        raise errors.OpPrereqError(("Received destination information for %s"
10331
                                    " disks, but instance %s has %s disks") %
10332
                                   (len(self.op.target_node), instance_name,
10333
                                    len(self.instance.disks)),
10334
                                   errors.ECODE_INVAL)
10335

    
10336
      cds = _GetClusterDomainSecret()
10337

    
10338
      # Check X509 key name
10339
      try:
10340
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10341
      except (TypeError, ValueError), err:
10342
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10343

    
10344
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10345
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10346
                                   errors.ECODE_INVAL)
10347

    
10348
      # Load and verify CA
10349
      try:
10350
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10351
      except OpenSSL.crypto.Error, err:
10352
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10353
                                   (err, ), errors.ECODE_INVAL)
10354

    
10355
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10356
      if errcode is not None:
10357
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10358
                                   (msg, ), errors.ECODE_INVAL)
10359

    
10360
      self.dest_x509_ca = cert
10361

    
10362
      # Verify target information
10363
      disk_info = []
10364
      for idx, disk_data in enumerate(self.op.target_node):
10365
        try:
10366
          (host, port, magic) = \
10367
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10368
        except errors.GenericError, err:
10369
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10370
                                     (idx, err), errors.ECODE_INVAL)
10371

    
10372
        disk_info.append((host, port, magic))
10373

    
10374
      assert len(disk_info) == len(self.op.target_node)
10375
      self.dest_disk_info = disk_info
10376

    
10377
    else:
10378
      raise errors.ProgrammerError("Unhandled export mode %r" %
10379
                                   self.op.mode)
10380

    
10381
    # instance disk type verification
10382
    # TODO: Implement export support for file-based disks
10383
    for disk in self.instance.disks:
10384
      if disk.dev_type == constants.LD_FILE:
10385
        raise errors.OpPrereqError("Export not supported for instances with"
10386
                                   " file-based disks", errors.ECODE_INVAL)
10387

    
10388
  def _CleanupExports(self, feedback_fn):
10389
    """Removes exports of current instance from all other nodes.
10390

10391
    If an instance in a cluster with nodes A..D was exported to node C, its
10392
    exports will be removed from the nodes A, B and D.
10393

10394
    """
10395
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10396

    
10397
    nodelist = self.cfg.GetNodeList()
10398
    nodelist.remove(self.dst_node.name)
10399

    
10400
    # on one-node clusters nodelist will be empty after the removal
10401
    # if we proceed the backup would be removed because OpBackupQuery
10402
    # substitutes an empty list with the full cluster node list.
10403
    iname = self.instance.name
10404
    if nodelist:
10405
      feedback_fn("Removing old exports for instance %s" % iname)
10406
      exportlist = self.rpc.call_export_list(nodelist)
10407
      for node in exportlist:
10408
        if exportlist[node].fail_msg:
10409
          continue
10410
        if iname in exportlist[node].payload:
10411
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10412
          if msg:
10413
            self.LogWarning("Could not remove older export for instance %s"
10414
                            " on node %s: %s", iname, node, msg)
10415

    
10416
  def Exec(self, feedback_fn):
10417
    """Export an instance to an image in the cluster.
10418

10419
    """
10420
    assert self.op.mode in constants.EXPORT_MODES
10421

    
10422
    instance = self.instance
10423
    src_node = instance.primary_node
10424

    
10425
    if self.op.shutdown:
10426
      # shutdown the instance, but not the disks
10427
      feedback_fn("Shutting down instance %s" % instance.name)
10428
      result = self.rpc.call_instance_shutdown(src_node, instance,
10429
                                               self.op.shutdown_timeout)
10430
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10431
      result.Raise("Could not shutdown instance %s on"
10432
                   " node %s" % (instance.name, src_node))
10433

    
10434
    # set the disks ID correctly since call_instance_start needs the
10435
    # correct drbd minor to create the symlinks
10436
    for disk in instance.disks:
10437
      self.cfg.SetDiskID(disk, src_node)
10438

    
10439
    activate_disks = (not instance.admin_up)
10440

    
10441
    if activate_disks:
10442
      # Activate the instance disks if we'exporting a stopped instance
10443
      feedback_fn("Activating disks for %s" % instance.name)
10444
      _StartInstanceDisks(self, instance, None)
10445

    
10446
    try:
10447
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10448
                                                     instance)
10449

    
10450
      helper.CreateSnapshots()
10451
      try:
10452
        if (self.op.shutdown and instance.admin_up and
10453
            not self.op.remove_instance):
10454
          assert not activate_disks
10455
          feedback_fn("Starting instance %s" % instance.name)
10456
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10457
          msg = result.fail_msg
10458
          if msg:
10459
            feedback_fn("Failed to start instance: %s" % msg)
10460
            _ShutdownInstanceDisks(self, instance)
10461
            raise errors.OpExecError("Could not start instance: %s" % msg)
10462

    
10463
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10464
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10465
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10466
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10467
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10468

    
10469
          (key_name, _, _) = self.x509_key_name
10470

    
10471
          dest_ca_pem = \
10472
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10473
                                            self.dest_x509_ca)
10474

    
10475
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10476
                                                     key_name, dest_ca_pem,
10477
                                                     timeouts)
10478
      finally:
10479
        helper.Cleanup()
10480

    
10481
      # Check for backwards compatibility
10482
      assert len(dresults) == len(instance.disks)
10483
      assert compat.all(isinstance(i, bool) for i in dresults), \
10484
             "Not all results are boolean: %r" % dresults
10485

    
10486
    finally:
10487
      if activate_disks:
10488
        feedback_fn("Deactivating disks for %s" % instance.name)
10489
        _ShutdownInstanceDisks(self, instance)
10490

    
10491
    if not (compat.all(dresults) and fin_resu):
10492
      failures = []
10493
      if not fin_resu:
10494
        failures.append("export finalization")
10495
      if not compat.all(dresults):
10496
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10497
                               if not dsk)
10498
        failures.append("disk export: disk(s) %s" % fdsk)
10499

    
10500
      raise errors.OpExecError("Export failed, errors in %s" %
10501
                               utils.CommaJoin(failures))
10502

    
10503
    # At this point, the export was successful, we can cleanup/finish
10504

    
10505
    # Remove instance if requested
10506
    if self.op.remove_instance:
10507
      feedback_fn("Removing instance %s" % instance.name)
10508
      _RemoveInstance(self, feedback_fn, instance,
10509
                      self.op.ignore_remove_failures)
10510

    
10511
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10512
      self._CleanupExports(feedback_fn)
10513

    
10514
    return fin_resu, dresults
10515

    
10516

    
10517
class LUBackupRemove(NoHooksLU):
10518
  """Remove exports related to the named instance.
10519

10520
  """
10521
  REQ_BGL = False
10522

    
10523
  def ExpandNames(self):
10524
    self.needed_locks = {}
10525
    # We need all nodes to be locked in order for RemoveExport to work, but we
10526
    # don't need to lock the instance itself, as nothing will happen to it (and
10527
    # we can remove exports also for a removed instance)
10528
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10529

    
10530
  def Exec(self, feedback_fn):
10531
    """Remove any export.
10532

10533
    """
10534
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10535
    # If the instance was not found we'll try with the name that was passed in.
10536
    # This will only work if it was an FQDN, though.
10537
    fqdn_warn = False
10538
    if not instance_name:
10539
      fqdn_warn = True
10540
      instance_name = self.op.instance_name
10541

    
10542
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10543
    exportlist = self.rpc.call_export_list(locked_nodes)
10544
    found = False
10545
    for node in exportlist:
10546
      msg = exportlist[node].fail_msg
10547
      if msg:
10548
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10549
        continue
10550
      if instance_name in exportlist[node].payload:
10551
        found = True
10552
        result = self.rpc.call_export_remove(node, instance_name)
10553
        msg = result.fail_msg
10554
        if msg:
10555
          logging.error("Could not remove export for instance %s"
10556
                        " on node %s: %s", instance_name, node, msg)
10557

    
10558
    if fqdn_warn and not found:
10559
      feedback_fn("Export not found. If trying to remove an export belonging"
10560
                  " to a deleted instance please use its Fully Qualified"
10561
                  " Domain Name.")
10562

    
10563

    
10564
class LUGroupAdd(LogicalUnit):
10565
  """Logical unit for creating node groups.
10566

10567
  """
10568
  HPATH = "group-add"
10569
  HTYPE = constants.HTYPE_GROUP
10570
  REQ_BGL = False
10571

    
10572
  def ExpandNames(self):
10573
    # We need the new group's UUID here so that we can create and acquire the
10574
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10575
    # that it should not check whether the UUID exists in the configuration.
10576
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10577
    self.needed_locks = {}
10578
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10579

    
10580
  def CheckPrereq(self):
10581
    """Check prerequisites.
10582

10583
    This checks that the given group name is not an existing node group
10584
    already.
10585

10586
    """
10587
    try:
10588
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10589
    except errors.OpPrereqError:
10590
      pass
10591
    else:
10592
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10593
                                 " node group (UUID: %s)" %
10594
                                 (self.op.group_name, existing_uuid),
10595
                                 errors.ECODE_EXISTS)
10596

    
10597
    if self.op.ndparams:
10598
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10599

    
10600
  def BuildHooksEnv(self):
10601
    """Build hooks env.
10602

10603
    """
10604
    env = {
10605
      "GROUP_NAME": self.op.group_name,
10606
      }
10607
    mn = self.cfg.GetMasterNode()
10608
    return env, [mn], [mn]
10609

    
10610
  def Exec(self, feedback_fn):
10611
    """Add the node group to the cluster.
10612

10613
    """
10614
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10615
                                  uuid=self.group_uuid,
10616
                                  alloc_policy=self.op.alloc_policy,
10617
                                  ndparams=self.op.ndparams)
10618

    
10619
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10620
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10621

    
10622

    
10623
class LUGroupAssignNodes(NoHooksLU):
10624
  """Logical unit for assigning nodes to groups.
10625

10626
  """
10627
  REQ_BGL = False
10628

    
10629
  def ExpandNames(self):
10630
    # These raise errors.OpPrereqError on their own:
10631
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10632
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10633

    
10634
    # We want to lock all the affected nodes and groups. We have readily
10635
    # available the list of nodes, and the *destination* group. To gather the
10636
    # list of "source" groups, we need to fetch node information later on.
10637
    self.needed_locks = {
10638
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
10639
      locking.LEVEL_NODE: self.op.nodes,
10640
      }
10641

    
10642
  def DeclareLocks(self, level):
10643
    if level == locking.LEVEL_NODEGROUP:
10644
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
10645

    
10646
      # Try to get all affected nodes' groups without having the group or node
10647
      # lock yet. Needs verification later in the code flow.
10648
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
10649

    
10650
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
10651

    
10652
  def CheckPrereq(self):
10653
    """Check prerequisites.
10654

10655
    """
10656
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
10657
    assert (frozenset(self.acquired_locks[locking.LEVEL_NODE]) ==
10658
            frozenset(self.op.nodes))
10659

    
10660
    expected_locks = (set([self.group_uuid]) |
10661
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
10662
    actual_locks = self.acquired_locks[locking.LEVEL_NODEGROUP]
10663
    if actual_locks != expected_locks:
10664
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
10665
                               " current groups are '%s', used to be '%s'" %
10666
                               (utils.CommaJoin(expected_locks),
10667
                                utils.CommaJoin(actual_locks)))
10668

    
10669
    self.node_data = self.cfg.GetAllNodesInfo()
10670
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10671
    instance_data = self.cfg.GetAllInstancesInfo()
10672

    
10673
    if self.group is None:
10674
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10675
                               (self.op.group_name, self.group_uuid))
10676

    
10677
    (new_splits, previous_splits) = \
10678
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10679
                                             for node in self.op.nodes],
10680
                                            self.node_data, instance_data)
10681

    
10682
    if new_splits:
10683
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10684

    
10685
      if not self.op.force:
10686
        raise errors.OpExecError("The following instances get split by this"
10687
                                 " change and --force was not given: %s" %
10688
                                 fmt_new_splits)
10689
      else:
10690
        self.LogWarning("This operation will split the following instances: %s",
10691
                        fmt_new_splits)
10692

    
10693
        if previous_splits:
10694
          self.LogWarning("In addition, these already-split instances continue"
10695
                          " to be split across groups: %s",
10696
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10697

    
10698
  def Exec(self, feedback_fn):
10699
    """Assign nodes to a new group.
10700

10701
    """
10702
    for node in self.op.nodes:
10703
      self.node_data[node].group = self.group_uuid
10704

    
10705
    # FIXME: Depends on side-effects of modifying the result of
10706
    # C{cfg.GetAllNodesInfo}
10707

    
10708
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10709

    
10710
  @staticmethod
10711
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10712
    """Check for split instances after a node assignment.
10713

10714
    This method considers a series of node assignments as an atomic operation,
10715
    and returns information about split instances after applying the set of
10716
    changes.
10717

10718
    In particular, it returns information about newly split instances, and
10719
    instances that were already split, and remain so after the change.
10720

10721
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
10722
    considered.
10723

10724
    @type changes: list of (node_name, new_group_uuid) pairs.
10725
    @param changes: list of node assignments to consider.
10726
    @param node_data: a dict with data for all nodes
10727
    @param instance_data: a dict with all instances to consider
10728
    @rtype: a two-tuple
10729
    @return: a list of instances that were previously okay and result split as a
10730
      consequence of this change, and a list of instances that were previously
10731
      split and this change does not fix.
10732

10733
    """
10734
    changed_nodes = dict((node, group) for node, group in changes
10735
                         if node_data[node].group != group)
10736

    
10737
    all_split_instances = set()
10738
    previously_split_instances = set()
10739

    
10740
    def InstanceNodes(instance):
10741
      return [instance.primary_node] + list(instance.secondary_nodes)
10742

    
10743
    for inst in instance_data.values():
10744
      if inst.disk_template not in constants.DTS_INT_MIRROR:
10745
        continue
10746

    
10747
      instance_nodes = InstanceNodes(inst)
10748

    
10749
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10750
        previously_split_instances.add(inst.name)
10751

    
10752
      if len(set(changed_nodes.get(node, node_data[node].group)
10753
                 for node in instance_nodes)) > 1:
10754
        all_split_instances.add(inst.name)
10755

    
10756
    return (list(all_split_instances - previously_split_instances),
10757
            list(previously_split_instances & all_split_instances))
10758

    
10759

    
10760
class _GroupQuery(_QueryBase):
10761

    
10762
  FIELDS = query.GROUP_FIELDS
10763

    
10764
  def ExpandNames(self, lu):
10765
    lu.needed_locks = {}
10766

    
10767
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10768
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10769

    
10770
    if not self.names:
10771
      self.wanted = [name_to_uuid[name]
10772
                     for name in utils.NiceSort(name_to_uuid.keys())]
10773
    else:
10774
      # Accept names to be either names or UUIDs.
10775
      missing = []
10776
      self.wanted = []
10777
      all_uuid = frozenset(self._all_groups.keys())
10778

    
10779
      for name in self.names:
10780
        if name in all_uuid:
10781
          self.wanted.append(name)
10782
        elif name in name_to_uuid:
10783
          self.wanted.append(name_to_uuid[name])
10784
        else:
10785
          missing.append(name)
10786

    
10787
      if missing:
10788
        raise errors.OpPrereqError("Some groups do not exist: %s" %
10789
                                   utils.CommaJoin(missing),
10790
                                   errors.ECODE_NOENT)
10791

    
10792
  def DeclareLocks(self, lu, level):
10793
    pass
10794

    
10795
  def _GetQueryData(self, lu):
10796
    """Computes the list of node groups and their attributes.
10797

10798
    """
10799
    do_nodes = query.GQ_NODE in self.requested_data
10800
    do_instances = query.GQ_INST in self.requested_data
10801

    
10802
    group_to_nodes = None
10803
    group_to_instances = None
10804

    
10805
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10806
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10807
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10808
    # instance->node. Hence, we will need to process nodes even if we only need
10809
    # instance information.
10810
    if do_nodes or do_instances:
10811
      all_nodes = lu.cfg.GetAllNodesInfo()
10812
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10813
      node_to_group = {}
10814

    
10815
      for node in all_nodes.values():
10816
        if node.group in group_to_nodes:
10817
          group_to_nodes[node.group].append(node.name)
10818
          node_to_group[node.name] = node.group
10819

    
10820
      if do_instances:
10821
        all_instances = lu.cfg.GetAllInstancesInfo()
10822
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10823

    
10824
        for instance in all_instances.values():
10825
          node = instance.primary_node
10826
          if node in node_to_group:
10827
            group_to_instances[node_to_group[node]].append(instance.name)
10828

    
10829
        if not do_nodes:
10830
          # Do not pass on node information if it was not requested.
10831
          group_to_nodes = None
10832

    
10833
    return query.GroupQueryData([self._all_groups[uuid]
10834
                                 for uuid in self.wanted],
10835
                                group_to_nodes, group_to_instances)
10836

    
10837

    
10838
class LUGroupQuery(NoHooksLU):
10839
  """Logical unit for querying node groups.
10840

10841
  """
10842
  REQ_BGL = False
10843

    
10844
  def CheckArguments(self):
10845
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10846

    
10847
  def ExpandNames(self):
10848
    self.gq.ExpandNames(self)
10849

    
10850
  def Exec(self, feedback_fn):
10851
    return self.gq.OldStyleQuery(self)
10852

    
10853

    
10854
class LUGroupSetParams(LogicalUnit):
10855
  """Modifies the parameters of a node group.
10856

10857
  """
10858
  HPATH = "group-modify"
10859
  HTYPE = constants.HTYPE_GROUP
10860
  REQ_BGL = False
10861

    
10862
  def CheckArguments(self):
10863
    all_changes = [
10864
      self.op.ndparams,
10865
      self.op.alloc_policy,
10866
      ]
10867

    
10868
    if all_changes.count(None) == len(all_changes):
10869
      raise errors.OpPrereqError("Please pass at least one modification",
10870
                                 errors.ECODE_INVAL)
10871

    
10872
  def ExpandNames(self):
10873
    # This raises errors.OpPrereqError on its own:
10874
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10875

    
10876
    self.needed_locks = {
10877
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10878
      }
10879

    
10880
  def CheckPrereq(self):
10881
    """Check prerequisites.
10882

10883
    """
10884
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10885

    
10886
    if self.group is None:
10887
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10888
                               (self.op.group_name, self.group_uuid))
10889

    
10890
    if self.op.ndparams:
10891
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10892
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10893
      self.new_ndparams = new_ndparams
10894

    
10895
  def BuildHooksEnv(self):
10896
    """Build hooks env.
10897

10898
    """
10899
    env = {
10900
      "GROUP_NAME": self.op.group_name,
10901
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10902
      }
10903
    mn = self.cfg.GetMasterNode()
10904
    return env, [mn], [mn]
10905

    
10906
  def Exec(self, feedback_fn):
10907
    """Modifies the node group.
10908

10909
    """
10910
    result = []
10911

    
10912
    if self.op.ndparams:
10913
      self.group.ndparams = self.new_ndparams
10914
      result.append(("ndparams", str(self.group.ndparams)))
10915

    
10916
    if self.op.alloc_policy:
10917
      self.group.alloc_policy = self.op.alloc_policy
10918

    
10919
    self.cfg.Update(self.group, feedback_fn)
10920
    return result
10921

    
10922

    
10923

    
10924
class LUGroupRemove(LogicalUnit):
10925
  HPATH = "group-remove"
10926
  HTYPE = constants.HTYPE_GROUP
10927
  REQ_BGL = False
10928

    
10929
  def ExpandNames(self):
10930
    # This will raises errors.OpPrereqError on its own:
10931
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10932
    self.needed_locks = {
10933
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10934
      }
10935

    
10936
  def CheckPrereq(self):
10937
    """Check prerequisites.
10938

10939
    This checks that the given group name exists as a node group, that is
10940
    empty (i.e., contains no nodes), and that is not the last group of the
10941
    cluster.
10942

10943
    """
10944
    # Verify that the group is empty.
10945
    group_nodes = [node.name
10946
                   for node in self.cfg.GetAllNodesInfo().values()
10947
                   if node.group == self.group_uuid]
10948

    
10949
    if group_nodes:
10950
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10951
                                 " nodes: %s" %
10952
                                 (self.op.group_name,
10953
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10954
                                 errors.ECODE_STATE)
10955

    
10956
    # Verify the cluster would not be left group-less.
10957
    if len(self.cfg.GetNodeGroupList()) == 1:
10958
      raise errors.OpPrereqError("Group '%s' is the only group,"
10959
                                 " cannot be removed" %
10960
                                 self.op.group_name,
10961
                                 errors.ECODE_STATE)
10962

    
10963
  def BuildHooksEnv(self):
10964
    """Build hooks env.
10965

10966
    """
10967
    env = {
10968
      "GROUP_NAME": self.op.group_name,
10969
      }
10970
    mn = self.cfg.GetMasterNode()
10971
    return env, [mn], [mn]
10972

    
10973
  def Exec(self, feedback_fn):
10974
    """Remove the node group.
10975

10976
    """
10977
    try:
10978
      self.cfg.RemoveNodeGroup(self.group_uuid)
10979
    except errors.ConfigurationError:
10980
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10981
                               (self.op.group_name, self.group_uuid))
10982

    
10983
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10984

    
10985

    
10986
class LUGroupRename(LogicalUnit):
10987
  HPATH = "group-rename"
10988
  HTYPE = constants.HTYPE_GROUP
10989
  REQ_BGL = False
10990

    
10991
  def ExpandNames(self):
10992
    # This raises errors.OpPrereqError on its own:
10993
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10994

    
10995
    self.needed_locks = {
10996
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10997
      }
10998

    
10999
  def CheckPrereq(self):
11000
    """Check prerequisites.
11001

11002
    This checks that the given old_name exists as a node group, and that
11003
    new_name doesn't.
11004

11005
    """
11006
    try:
11007
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11008
    except errors.OpPrereqError:
11009
      pass
11010
    else:
11011
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11012
                                 " node group (UUID: %s)" %
11013
                                 (self.op.new_name, new_name_uuid),
11014
                                 errors.ECODE_EXISTS)
11015

    
11016
  def BuildHooksEnv(self):
11017
    """Build hooks env.
11018

11019
    """
11020
    env = {
11021
      "OLD_NAME": self.op.old_name,
11022
      "NEW_NAME": self.op.new_name,
11023
      }
11024

    
11025
    mn = self.cfg.GetMasterNode()
11026
    all_nodes = self.cfg.GetAllNodesInfo()
11027
    run_nodes = [mn]
11028
    all_nodes.pop(mn, None)
11029

    
11030
    for node in all_nodes.values():
11031
      if node.group == self.group_uuid:
11032
        run_nodes.append(node.name)
11033

    
11034
    return env, run_nodes, run_nodes
11035

    
11036
  def Exec(self, feedback_fn):
11037
    """Rename the node group.
11038

11039
    """
11040
    group = self.cfg.GetNodeGroup(self.group_uuid)
11041

    
11042
    if group is None:
11043
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11044
                               (self.op.old_name, self.group_uuid))
11045

    
11046
    group.name = self.op.new_name
11047
    self.cfg.Update(group, feedback_fn)
11048

    
11049
    return self.op.new_name
11050

    
11051

    
11052
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11053
  """Generic tags LU.
11054

11055
  This is an abstract class which is the parent of all the other tags LUs.
11056

11057
  """
11058

    
11059
  def ExpandNames(self):
11060
    self.needed_locks = {}
11061
    if self.op.kind == constants.TAG_NODE:
11062
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11063
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11064
    elif self.op.kind == constants.TAG_INSTANCE:
11065
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11066
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11067

    
11068
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11069
    # not possible to acquire the BGL based on opcode parameters)
11070

    
11071
  def CheckPrereq(self):
11072
    """Check prerequisites.
11073

11074
    """
11075
    if self.op.kind == constants.TAG_CLUSTER:
11076
      self.target = self.cfg.GetClusterInfo()
11077
    elif self.op.kind == constants.TAG_NODE:
11078
      self.target = self.cfg.GetNodeInfo(self.op.name)
11079
    elif self.op.kind == constants.TAG_INSTANCE:
11080
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11081
    else:
11082
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11083
                                 str(self.op.kind), errors.ECODE_INVAL)
11084

    
11085

    
11086
class LUTagsGet(TagsLU):
11087
  """Returns the tags of a given object.
11088

11089
  """
11090
  REQ_BGL = False
11091

    
11092
  def ExpandNames(self):
11093
    TagsLU.ExpandNames(self)
11094

    
11095
    # Share locks as this is only a read operation
11096
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11097

    
11098
  def Exec(self, feedback_fn):
11099
    """Returns the tag list.
11100

11101
    """
11102
    return list(self.target.GetTags())
11103

    
11104

    
11105
class LUTagsSearch(NoHooksLU):
11106
  """Searches the tags for a given pattern.
11107

11108
  """
11109
  REQ_BGL = False
11110

    
11111
  def ExpandNames(self):
11112
    self.needed_locks = {}
11113

    
11114
  def CheckPrereq(self):
11115
    """Check prerequisites.
11116

11117
    This checks the pattern passed for validity by compiling it.
11118

11119
    """
11120
    try:
11121
      self.re = re.compile(self.op.pattern)
11122
    except re.error, err:
11123
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11124
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11125

    
11126
  def Exec(self, feedback_fn):
11127
    """Returns the tag list.
11128

11129
    """
11130
    cfg = self.cfg
11131
    tgts = [("/cluster", cfg.GetClusterInfo())]
11132
    ilist = cfg.GetAllInstancesInfo().values()
11133
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11134
    nlist = cfg.GetAllNodesInfo().values()
11135
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11136
    results = []
11137
    for path, target in tgts:
11138
      for tag in target.GetTags():
11139
        if self.re.search(tag):
11140
          results.append((path, tag))
11141
    return results
11142

    
11143

    
11144
class LUTagsSet(TagsLU):
11145
  """Sets a tag on a given object.
11146

11147
  """
11148
  REQ_BGL = False
11149

    
11150
  def CheckPrereq(self):
11151
    """Check prerequisites.
11152

11153
    This checks the type and length of the tag name and value.
11154

11155
    """
11156
    TagsLU.CheckPrereq(self)
11157
    for tag in self.op.tags:
11158
      objects.TaggableObject.ValidateTag(tag)
11159

    
11160
  def Exec(self, feedback_fn):
11161
    """Sets the tag.
11162

11163
    """
11164
    try:
11165
      for tag in self.op.tags:
11166
        self.target.AddTag(tag)
11167
    except errors.TagError, err:
11168
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11169
    self.cfg.Update(self.target, feedback_fn)
11170

    
11171

    
11172
class LUTagsDel(TagsLU):
11173
  """Delete a list of tags from a given object.
11174

11175
  """
11176
  REQ_BGL = False
11177

    
11178
  def CheckPrereq(self):
11179
    """Check prerequisites.
11180

11181
    This checks that we have the given tag.
11182

11183
    """
11184
    TagsLU.CheckPrereq(self)
11185
    for tag in self.op.tags:
11186
      objects.TaggableObject.ValidateTag(tag)
11187
    del_tags = frozenset(self.op.tags)
11188
    cur_tags = self.target.GetTags()
11189

    
11190
    diff_tags = del_tags - cur_tags
11191
    if diff_tags:
11192
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11193
      raise errors.OpPrereqError("Tag(s) %s not found" %
11194
                                 (utils.CommaJoin(diff_names), ),
11195
                                 errors.ECODE_NOENT)
11196

    
11197
  def Exec(self, feedback_fn):
11198
    """Remove the tag from the object.
11199

11200
    """
11201
    for tag in self.op.tags:
11202
      self.target.RemoveTag(tag)
11203
    self.cfg.Update(self.target, feedback_fn)
11204

    
11205

    
11206
class LUTestDelay(NoHooksLU):
11207
  """Sleep for a specified amount of time.
11208

11209
  This LU sleeps on the master and/or nodes for a specified amount of
11210
  time.
11211

11212
  """
11213
  REQ_BGL = False
11214

    
11215
  def ExpandNames(self):
11216
    """Expand names and set required locks.
11217

11218
    This expands the node list, if any.
11219

11220
    """
11221
    self.needed_locks = {}
11222
    if self.op.on_nodes:
11223
      # _GetWantedNodes can be used here, but is not always appropriate to use
11224
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11225
      # more information.
11226
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11227
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11228

    
11229
  def _TestDelay(self):
11230
    """Do the actual sleep.
11231

11232
    """
11233
    if self.op.on_master:
11234
      if not utils.TestDelay(self.op.duration):
11235
        raise errors.OpExecError("Error during master delay test")
11236
    if self.op.on_nodes:
11237
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11238
      for node, node_result in result.items():
11239
        node_result.Raise("Failure during rpc call to node %s" % node)
11240

    
11241
  def Exec(self, feedback_fn):
11242
    """Execute the test delay opcode, with the wanted repetitions.
11243

11244
    """
11245
    if self.op.repeat == 0:
11246
      self._TestDelay()
11247
    else:
11248
      top_value = self.op.repeat - 1
11249
      for i in range(self.op.repeat):
11250
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11251
        self._TestDelay()
11252

    
11253

    
11254
class LUTestJqueue(NoHooksLU):
11255
  """Utility LU to test some aspects of the job queue.
11256

11257
  """
11258
  REQ_BGL = False
11259

    
11260
  # Must be lower than default timeout for WaitForJobChange to see whether it
11261
  # notices changed jobs
11262
  _CLIENT_CONNECT_TIMEOUT = 20.0
11263
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11264

    
11265
  @classmethod
11266
  def _NotifyUsingSocket(cls, cb, errcls):
11267
    """Opens a Unix socket and waits for another program to connect.
11268

11269
    @type cb: callable
11270
    @param cb: Callback to send socket name to client
11271
    @type errcls: class
11272
    @param errcls: Exception class to use for errors
11273

11274
    """
11275
    # Using a temporary directory as there's no easy way to create temporary
11276
    # sockets without writing a custom loop around tempfile.mktemp and
11277
    # socket.bind
11278
    tmpdir = tempfile.mkdtemp()
11279
    try:
11280
      tmpsock = utils.PathJoin(tmpdir, "sock")
11281

    
11282
      logging.debug("Creating temporary socket at %s", tmpsock)
11283
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11284
      try:
11285
        sock.bind(tmpsock)
11286
        sock.listen(1)
11287

    
11288
        # Send details to client
11289
        cb(tmpsock)
11290

    
11291
        # Wait for client to connect before continuing
11292
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11293
        try:
11294
          (conn, _) = sock.accept()
11295
        except socket.error, err:
11296
          raise errcls("Client didn't connect in time (%s)" % err)
11297
      finally:
11298
        sock.close()
11299
    finally:
11300
      # Remove as soon as client is connected
11301
      shutil.rmtree(tmpdir)
11302

    
11303
    # Wait for client to close
11304
    try:
11305
      try:
11306
        # pylint: disable-msg=E1101
11307
        # Instance of '_socketobject' has no ... member
11308
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11309
        conn.recv(1)
11310
      except socket.error, err:
11311
        raise errcls("Client failed to confirm notification (%s)" % err)
11312
    finally:
11313
      conn.close()
11314

    
11315
  def _SendNotification(self, test, arg, sockname):
11316
    """Sends a notification to the client.
11317

11318
    @type test: string
11319
    @param test: Test name
11320
    @param arg: Test argument (depends on test)
11321
    @type sockname: string
11322
    @param sockname: Socket path
11323

11324
    """
11325
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11326

    
11327
  def _Notify(self, prereq, test, arg):
11328
    """Notifies the client of a test.
11329

11330
    @type prereq: bool
11331
    @param prereq: Whether this is a prereq-phase test
11332
    @type test: string
11333
    @param test: Test name
11334
    @param arg: Test argument (depends on test)
11335

11336
    """
11337
    if prereq:
11338
      errcls = errors.OpPrereqError
11339
    else:
11340
      errcls = errors.OpExecError
11341

    
11342
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11343
                                                  test, arg),
11344
                                   errcls)
11345

    
11346
  def CheckArguments(self):
11347
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11348
    self.expandnames_calls = 0
11349

    
11350
  def ExpandNames(self):
11351
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11352
    if checkargs_calls < 1:
11353
      raise errors.ProgrammerError("CheckArguments was not called")
11354

    
11355
    self.expandnames_calls += 1
11356

    
11357
    if self.op.notify_waitlock:
11358
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11359

    
11360
    self.LogInfo("Expanding names")
11361

    
11362
    # Get lock on master node (just to get a lock, not for a particular reason)
11363
    self.needed_locks = {
11364
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11365
      }
11366

    
11367
  def Exec(self, feedback_fn):
11368
    if self.expandnames_calls < 1:
11369
      raise errors.ProgrammerError("ExpandNames was not called")
11370

    
11371
    if self.op.notify_exec:
11372
      self._Notify(False, constants.JQT_EXEC, None)
11373

    
11374
    self.LogInfo("Executing")
11375

    
11376
    if self.op.log_messages:
11377
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11378
      for idx, msg in enumerate(self.op.log_messages):
11379
        self.LogInfo("Sending log message %s", idx + 1)
11380
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11381
        # Report how many test messages have been sent
11382
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11383

    
11384
    if self.op.fail:
11385
      raise errors.OpExecError("Opcode failure was requested")
11386

    
11387
    return True
11388

    
11389

    
11390
class IAllocator(object):
11391
  """IAllocator framework.
11392

11393
  An IAllocator instance has three sets of attributes:
11394
    - cfg that is needed to query the cluster
11395
    - input data (all members of the _KEYS class attribute are required)
11396
    - four buffer attributes (in|out_data|text), that represent the
11397
      input (to the external script) in text and data structure format,
11398
      and the output from it, again in two formats
11399
    - the result variables from the script (success, info, nodes) for
11400
      easy usage
11401

11402
  """
11403
  # pylint: disable-msg=R0902
11404
  # lots of instance attributes
11405
  _ALLO_KEYS = [
11406
    "name", "mem_size", "disks", "disk_template",
11407
    "os", "tags", "nics", "vcpus", "hypervisor",
11408
    ]
11409
  _RELO_KEYS = [
11410
    "name", "relocate_from",
11411
    ]
11412
  _EVAC_KEYS = [
11413
    "evac_nodes",
11414
    ]
11415

    
11416
  def __init__(self, cfg, rpc, mode, **kwargs):
11417
    self.cfg = cfg
11418
    self.rpc = rpc
11419
    # init buffer variables
11420
    self.in_text = self.out_text = self.in_data = self.out_data = None
11421
    # init all input fields so that pylint is happy
11422
    self.mode = mode
11423
    self.mem_size = self.disks = self.disk_template = None
11424
    self.os = self.tags = self.nics = self.vcpus = None
11425
    self.hypervisor = None
11426
    self.relocate_from = None
11427
    self.name = None
11428
    self.evac_nodes = None
11429
    # computed fields
11430
    self.required_nodes = None
11431
    # init result fields
11432
    self.success = self.info = self.result = None
11433
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11434
      keyset = self._ALLO_KEYS
11435
      fn = self._AddNewInstance
11436
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11437
      keyset = self._RELO_KEYS
11438
      fn = self._AddRelocateInstance
11439
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11440
      keyset = self._EVAC_KEYS
11441
      fn = self._AddEvacuateNodes
11442
    else:
11443
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11444
                                   " IAllocator" % self.mode)
11445
    for key in kwargs:
11446
      if key not in keyset:
11447
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11448
                                     " IAllocator" % key)
11449
      setattr(self, key, kwargs[key])
11450

    
11451
    for key in keyset:
11452
      if key not in kwargs:
11453
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11454
                                     " IAllocator" % key)
11455
    self._BuildInputData(fn)
11456

    
11457
  def _ComputeClusterData(self):
11458
    """Compute the generic allocator input data.
11459

11460
    This is the data that is independent of the actual operation.
11461

11462
    """
11463
    cfg = self.cfg
11464
    cluster_info = cfg.GetClusterInfo()
11465
    # cluster data
11466
    data = {
11467
      "version": constants.IALLOCATOR_VERSION,
11468
      "cluster_name": cfg.GetClusterName(),
11469
      "cluster_tags": list(cluster_info.GetTags()),
11470
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11471
      # we don't have job IDs
11472
      }
11473
    ninfo = cfg.GetAllNodesInfo()
11474
    iinfo = cfg.GetAllInstancesInfo().values()
11475
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11476

    
11477
    # node data
11478
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11479

    
11480
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11481
      hypervisor_name = self.hypervisor
11482
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11483
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11484
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11485
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11486

    
11487
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11488
                                        hypervisor_name)
11489
    node_iinfo = \
11490
      self.rpc.call_all_instances_info(node_list,
11491
                                       cluster_info.enabled_hypervisors)
11492

    
11493
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11494

    
11495
    config_ndata = self._ComputeBasicNodeData(ninfo)
11496
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
11497
                                                 i_list, config_ndata)
11498
    assert len(data["nodes"]) == len(ninfo), \
11499
        "Incomplete node data computed"
11500

    
11501
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
11502

    
11503
    self.in_data = data
11504

    
11505
  @staticmethod
11506
  def _ComputeNodeGroupData(cfg):
11507
    """Compute node groups data.
11508

11509
    """
11510
    ng = {}
11511
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
11512
      ng[guuid] = {
11513
        "name": gdata.name,
11514
        "alloc_policy": gdata.alloc_policy,
11515
        }
11516
    return ng
11517

    
11518
  @staticmethod
11519
  def _ComputeBasicNodeData(node_cfg):
11520
    """Compute global node data.
11521

11522
    @rtype: dict
11523
    @returns: a dict of name: (node dict, node config)
11524

11525
    """
11526
    node_results = {}
11527
    for ninfo in node_cfg.values():
11528
      # fill in static (config-based) values
11529
      pnr = {
11530
        "tags": list(ninfo.GetTags()),
11531
        "primary_ip": ninfo.primary_ip,
11532
        "secondary_ip": ninfo.secondary_ip,
11533
        "offline": ninfo.offline,
11534
        "drained": ninfo.drained,
11535
        "master_candidate": ninfo.master_candidate,
11536
        "group": ninfo.group,
11537
        "master_capable": ninfo.master_capable,
11538
        "vm_capable": ninfo.vm_capable,
11539
        }
11540

    
11541
      node_results[ninfo.name] = pnr
11542

    
11543
    return node_results
11544

    
11545
  @staticmethod
11546
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
11547
                              node_results):
11548
    """Compute global node data.
11549

11550
    @param node_results: the basic node structures as filled from the config
11551

11552
    """
11553
    # make a copy of the current dict
11554
    node_results = dict(node_results)
11555
    for nname, nresult in node_data.items():
11556
      assert nname in node_results, "Missing basic data for node %s" % nname
11557
      ninfo = node_cfg[nname]
11558

    
11559
      if not (ninfo.offline or ninfo.drained):
11560
        nresult.Raise("Can't get data for node %s" % nname)
11561
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11562
                                nname)
11563
        remote_info = nresult.payload
11564

    
11565
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11566
                     'vg_size', 'vg_free', 'cpu_total']:
11567
          if attr not in remote_info:
11568
            raise errors.OpExecError("Node '%s' didn't return attribute"
11569
                                     " '%s'" % (nname, attr))
11570
          if not isinstance(remote_info[attr], int):
11571
            raise errors.OpExecError("Node '%s' returned invalid value"
11572
                                     " for '%s': %s" %
11573
                                     (nname, attr, remote_info[attr]))
11574
        # compute memory used by primary instances
11575
        i_p_mem = i_p_up_mem = 0
11576
        for iinfo, beinfo in i_list:
11577
          if iinfo.primary_node == nname:
11578
            i_p_mem += beinfo[constants.BE_MEMORY]
11579
            if iinfo.name not in node_iinfo[nname].payload:
11580
              i_used_mem = 0
11581
            else:
11582
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11583
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11584
            remote_info['memory_free'] -= max(0, i_mem_diff)
11585

    
11586
            if iinfo.admin_up:
11587
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11588

    
11589
        # compute memory used by instances
11590
        pnr_dyn = {
11591
          "total_memory": remote_info['memory_total'],
11592
          "reserved_memory": remote_info['memory_dom0'],
11593
          "free_memory": remote_info['memory_free'],
11594
          "total_disk": remote_info['vg_size'],
11595
          "free_disk": remote_info['vg_free'],
11596
          "total_cpus": remote_info['cpu_total'],
11597
          "i_pri_memory": i_p_mem,
11598
          "i_pri_up_memory": i_p_up_mem,
11599
          }
11600
        pnr_dyn.update(node_results[nname])
11601
        node_results[nname] = pnr_dyn
11602

    
11603
    return node_results
11604

    
11605
  @staticmethod
11606
  def _ComputeInstanceData(cluster_info, i_list):
11607
    """Compute global instance data.
11608

11609
    """
11610
    instance_data = {}
11611
    for iinfo, beinfo in i_list:
11612
      nic_data = []
11613
      for nic in iinfo.nics:
11614
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11615
        nic_dict = {"mac": nic.mac,
11616
                    "ip": nic.ip,
11617
                    "mode": filled_params[constants.NIC_MODE],
11618
                    "link": filled_params[constants.NIC_LINK],
11619
                   }
11620
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11621
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11622
        nic_data.append(nic_dict)
11623
      pir = {
11624
        "tags": list(iinfo.GetTags()),
11625
        "admin_up": iinfo.admin_up,
11626
        "vcpus": beinfo[constants.BE_VCPUS],
11627
        "memory": beinfo[constants.BE_MEMORY],
11628
        "os": iinfo.os,
11629
        "nics": nic_data,
11630
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
11631
        "disk_template": iinfo.disk_template,
11632
        "hypervisor": iinfo.hypervisor,
11633
        }
11634
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
11635
                                                 pir["disks"])
11636
      # hail's relocation mode does not work without secondaries,
11637
      # as it exclusively tries replace-secondary moves. So, let's trick hail
11638
      # by specifying our primary and secondary node to be the same.
11639
      if iinfo.disk_template in constants.DTS_EXT_MIRROR:
11640
        pir["nodes"] = [iinfo.primary_node, iinfo.primary_node]
11641
      else:
11642
        pir["nodes"] = [iinfo.primary_node] + list(iinfo.secondary_nodes)
11643
      instance_data[iinfo.name] = pir
11644

    
11645
    return instance_data
11646

    
11647
  def _AddNewInstance(self):
11648
    """Add new instance data to allocator structure.
11649

11650
    This in combination with _AllocatorGetClusterData will create the
11651
    correct structure needed as input for the allocator.
11652

11653
    The checks for the completeness of the opcode must have already been
11654
    done.
11655

11656
    """
11657
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11658

    
11659
    if self.disk_template in constants.DTS_INT_MIRROR:
11660
      self.required_nodes = 2
11661
    else:
11662
      self.required_nodes = 1
11663
    request = {
11664
      "name": self.name,
11665
      "disk_template": self.disk_template,
11666
      "tags": self.tags,
11667
      "os": self.os,
11668
      "vcpus": self.vcpus,
11669
      "memory": self.mem_size,
11670
      "disks": self.disks,
11671
      "disk_space_total": disk_space,
11672
      "nics": self.nics,
11673
      "required_nodes": self.required_nodes,
11674
      }
11675
    return request
11676

    
11677
  def _AddRelocateInstance(self):
11678
    """Add relocate instance data to allocator structure.
11679

11680
    This in combination with _IAllocatorGetClusterData will create the
11681
    correct structure needed as input for the allocator.
11682

11683
    The checks for the completeness of the opcode must have already been
11684
    done.
11685

11686
    """
11687
    instance = self.cfg.GetInstanceInfo(self.name)
11688
    if instance is None:
11689
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11690
                                   " IAllocator" % self.name)
11691

    
11692
    if instance.disk_template not in constants.DTS_MIRRORED:
11693
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11694
                                 errors.ECODE_INVAL)
11695

    
11696
    if instance.disk_template in constants.DTS_INT_MIRROR and \
11697
        len(instance.secondary_nodes) != 1:
11698
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11699
                                 errors.ECODE_STATE)
11700

    
11701
    self.required_nodes = 1
11702
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11703
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11704

    
11705
    request = {
11706
      "name": self.name,
11707
      "disk_space_total": disk_space,
11708
      "required_nodes": self.required_nodes,
11709
      "relocate_from": self.relocate_from,
11710
      }
11711
    return request
11712

    
11713
  def _AddEvacuateNodes(self):
11714
    """Add evacuate nodes data to allocator structure.
11715

11716
    """
11717
    request = {
11718
      "evac_nodes": self.evac_nodes
11719
      }
11720
    return request
11721

    
11722
  def _BuildInputData(self, fn):
11723
    """Build input data structures.
11724

11725
    """
11726
    self._ComputeClusterData()
11727

    
11728
    request = fn()
11729
    request["type"] = self.mode
11730
    self.in_data["request"] = request
11731

    
11732
    self.in_text = serializer.Dump(self.in_data)
11733

    
11734
  def Run(self, name, validate=True, call_fn=None):
11735
    """Run an instance allocator and return the results.
11736

11737
    """
11738
    if call_fn is None:
11739
      call_fn = self.rpc.call_iallocator_runner
11740

    
11741
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11742
    result.Raise("Failure while running the iallocator script")
11743

    
11744
    self.out_text = result.payload
11745
    if validate:
11746
      self._ValidateResult()
11747

    
11748
  def _ValidateResult(self):
11749
    """Process the allocator results.
11750

11751
    This will process and if successful save the result in
11752
    self.out_data and the other parameters.
11753

11754
    """
11755
    try:
11756
      rdict = serializer.Load(self.out_text)
11757
    except Exception, err:
11758
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11759

    
11760
    if not isinstance(rdict, dict):
11761
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11762

    
11763
    # TODO: remove backwards compatiblity in later versions
11764
    if "nodes" in rdict and "result" not in rdict:
11765
      rdict["result"] = rdict["nodes"]
11766
      del rdict["nodes"]
11767

    
11768
    for key in "success", "info", "result":
11769
      if key not in rdict:
11770
        raise errors.OpExecError("Can't parse iallocator results:"
11771
                                 " missing key '%s'" % key)
11772
      setattr(self, key, rdict[key])
11773

    
11774
    if not isinstance(rdict["result"], list):
11775
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11776
                               " is not a list")
11777
    self.out_data = rdict
11778

    
11779

    
11780
class LUTestAllocator(NoHooksLU):
11781
  """Run allocator tests.
11782

11783
  This LU runs the allocator tests
11784

11785
  """
11786
  def CheckPrereq(self):
11787
    """Check prerequisites.
11788

11789
    This checks the opcode parameters depending on the director and mode test.
11790

11791
    """
11792
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11793
      for attr in ["mem_size", "disks", "disk_template",
11794
                   "os", "tags", "nics", "vcpus"]:
11795
        if not hasattr(self.op, attr):
11796
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11797
                                     attr, errors.ECODE_INVAL)
11798
      iname = self.cfg.ExpandInstanceName(self.op.name)
11799
      if iname is not None:
11800
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11801
                                   iname, errors.ECODE_EXISTS)
11802
      if not isinstance(self.op.nics, list):
11803
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11804
                                   errors.ECODE_INVAL)
11805
      if not isinstance(self.op.disks, list):
11806
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11807
                                   errors.ECODE_INVAL)
11808
      for row in self.op.disks:
11809
        if (not isinstance(row, dict) or
11810
            "size" not in row or
11811
            not isinstance(row["size"], int) or
11812
            "mode" not in row or
11813
            row["mode"] not in ['r', 'w']):
11814
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11815
                                     " parameter", errors.ECODE_INVAL)
11816
      if self.op.hypervisor is None:
11817
        self.op.hypervisor = self.cfg.GetHypervisorType()
11818
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11819
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11820
      self.op.name = fname
11821
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11822
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11823
      if not hasattr(self.op, "evac_nodes"):
11824
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11825
                                   " opcode input", errors.ECODE_INVAL)
11826
    else:
11827
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11828
                                 self.op.mode, errors.ECODE_INVAL)
11829

    
11830
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11831
      if self.op.allocator is None:
11832
        raise errors.OpPrereqError("Missing allocator name",
11833
                                   errors.ECODE_INVAL)
11834
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11835
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11836
                                 self.op.direction, errors.ECODE_INVAL)
11837

    
11838
  def Exec(self, feedback_fn):
11839
    """Run the allocator test.
11840

11841
    """
11842
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11843
      ial = IAllocator(self.cfg, self.rpc,
11844
                       mode=self.op.mode,
11845
                       name=self.op.name,
11846
                       mem_size=self.op.mem_size,
11847
                       disks=self.op.disks,
11848
                       disk_template=self.op.disk_template,
11849
                       os=self.op.os,
11850
                       tags=self.op.tags,
11851
                       nics=self.op.nics,
11852
                       vcpus=self.op.vcpus,
11853
                       hypervisor=self.op.hypervisor,
11854
                       )
11855
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11856
      ial = IAllocator(self.cfg, self.rpc,
11857
                       mode=self.op.mode,
11858
                       name=self.op.name,
11859
                       relocate_from=list(self.relocate_from),
11860
                       )
11861
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11862
      ial = IAllocator(self.cfg, self.rpc,
11863
                       mode=self.op.mode,
11864
                       evac_nodes=self.op.evac_nodes)
11865
    else:
11866
      raise errors.ProgrammerError("Uncatched mode %s in"
11867
                                   " LUTestAllocator.Exec", self.op.mode)
11868

    
11869
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11870
      result = ial.in_text
11871
    else:
11872
      ial.Run(self.op.allocator, validate=False)
11873
      result = ial.out_text
11874
    return result
11875

    
11876

    
11877
# Network LUs
11878
class LUNetworkAdd(LogicalUnit):
11879
  """Logical unit for creating node groups.
11880

11881
  """
11882
  HPATH = "network-add"
11883
  HTYPE = constants.HTYPE_NETWORK
11884
  REQ_BGL = False
11885

    
11886
  def ExpandNames(self):
11887
    self.needed_locks = {
11888
      locking.LEVEL_NODE: locking.ALL_SET,
11889
    }
11890
    self.share_locks[locking.LEVEL_NODE] = 1
11891

    
11892
  def CheckPrereq(self):
11893
    """Check prerequisites.
11894

11895
    This checks that the given group name is not an existing node group
11896
    already.
11897

11898
    """
11899
    try:
11900
      uuid = self.cfg.LookupNetwork(self.op.network_name)
11901
    except errors.OpPrereqError:
11902
      uuid = None
11903

    
11904
    if uuid is not None:
11905
      raise errors.OpPrereqError("Network '%s' already defined" %
11906
                                 self.op.network, errors.ECODE_EXISTS)
11907

    
11908
  def BuildHooksEnv(self):
11909
    """Build hooks env.
11910

11911
    """
11912
    env = {
11913
      "NETWORK_NAME": self.op.network_name,
11914
      "NETWORK_SUBNET": self.op.network,
11915
      "NETWORK_GATEWAY": self.op.gateway,
11916
      }
11917
    mn = self.cfg.GetMasterNode()
11918
    return env, [mn], [mn]
11919

    
11920
  def Exec(self, feedback_fn):
11921
    """Add the ip pool to the cluster.
11922

11923
    """
11924
    #FIXME: error handling
11925
    nobj = objects.Network(name=self.op.network_name,
11926
                           network=self.op.network,
11927
                           gateway=self.op.gateway,
11928
                           family=4)
11929

    
11930
    # Initialize the associated address pool
11931
    pool = network.AddressPool.InitializeNetwork(nobj)
11932

    
11933
    # Check if we need to reserve the nodes and the cluster master IP
11934
    # These may not be allocated to any instances in routed mode, as
11935
    # they wouldn't function anyway.
11936
    for node in self.cfg.GetAllNodesInfo().values():
11937
      for ip in [node.primary_ip, node.secondary_ip]:
11938
        try:
11939
          pool.Reserve(ip)
11940
          self.LogInfo("Reserved node %s's IP (%s)", node.name, ip)
11941

    
11942
        except errors.AddressPoolError:
11943
          pass
11944

    
11945
    master_ip = self.cfg.GetClusterInfo().master_ip
11946
    try:
11947
      pool.Reserve(master_ip)
11948
      self.LogInfo("Reserved cluster master IP (%s)", master_ip)
11949
    except errors.AddressPoolError:
11950
      pass
11951

    
11952
    if self.op.reserved_ips:
11953
      for ip in self.op.reserved_ips:
11954
        pool.Reserve(ip, external=True)
11955

    
11956
    self.cfg.AddNetwork(nobj, self.proc.GetECId())
11957

    
11958

    
11959
class _NetworkQuery(_QueryBase):
11960
  FIELDS = query.NETWORK_FIELDS
11961

    
11962
  def ExpandNames(self, lu):
11963
    lu.needed_locks = {}
11964

    
11965
    self._all_networks = lu.cfg.GetAllNetworksInfo()
11966
    name_to_uuid = dict((n.name, n.uuid) for n in self._all_networks.values())
11967

    
11968
    if not self.names:
11969
      self.wanted = [name_to_uuid[name]
11970
                     for name in utils.NiceSort(name_to_uuid.keys())]
11971
    else:
11972
      # Accept names to be either names or UUIDs.
11973
      missing = []
11974
      self.wanted = []
11975
      all_uuid = frozenset(self._all_networks.keys())
11976

    
11977
      for name in self.names:
11978
        if name in all_uuid:
11979
          self.wanted.append(name)
11980
        elif name in name_to_uuid:
11981
          self.wanted.append(name_to_uuid[name])
11982
        else:
11983
          missing.append(name)
11984

    
11985
      if missing:
11986
        raise errors.OpPrereqError("Some networks do not exist: %s" % missing,
11987
                                   errors.ECODE_NOENT)
11988

    
11989
  def DeclareLocks(self, lu, level):
11990
    pass
11991

    
11992
  def _GetQueryData(self, lu):
11993
    """Computes the list of networks and their attributes.
11994

11995
    """
11996
    do_instances = query.NETQ_INST in self.requested_data
11997
    do_groups = do_instances or (query.NETQ_GROUP in self.requested_data)
11998
    do_stats = query.NETQ_STATS in self.requested_data
11999

    
12000
    network_to_groups = None
12001
    network_to_instances = None
12002
    stats = None
12003

    
12004
    # For NETQ_GROUP, we need to map network->[groups]
12005
    if do_groups:
12006
      all_groups = lu.cfg.GetAllNodeGroupsInfo()
12007
      network_to_groups = dict((uuid, []) for uuid in self.wanted)
12008

    
12009
      if do_instances:
12010
        all_instances = lu.cfg.GetAllInstancesInfo()
12011
        all_nodes = lu.cfg.GetAllNodesInfo()
12012
        network_to_instances = dict((uuid, []) for uuid in self.wanted)
12013

    
12014
      for group in all_groups.values():
12015
        if do_instances:
12016
          group_nodes = [node.name for node in all_nodes.values() if
12017
                         node.group == group.uuid]
12018
          group_instances = [instance for instance in all_instances.values()
12019
                             if instance.primary_node in group_nodes]
12020

    
12021
        for uuid, link in group.networks.items():
12022
          if uuid in network_to_groups:
12023
            network_to_groups[uuid].append(":".join((group.name, link)))
12024

    
12025
            if do_instances:
12026
              for instance in group_instances:
12027
                for nic in instance.nics:
12028
                  if nic.nicparams.get(constants.NIC_LINK, None) == link:
12029
                    network_to_instances[uuid].append(instance.name)
12030
                    break
12031

    
12032
    if do_stats:
12033
      stats = {}
12034
      for uuid, net in self._all_networks.items():
12035
        if uuid in self.wanted:
12036
          pool = network.AddressPool(net)
12037
          stats[uuid] = {
12038
            "free_count": pool.GetFreeCount(),
12039
            "reserved_count": pool.GetReservedCount(),
12040
            "map": pool.GetMap(),
12041
            }
12042

    
12043
    return query.NetworkQueryData([self._all_networks[uuid]
12044
                                   for uuid in self.wanted],
12045
                                   network_to_groups,
12046
                                   network_to_instances,
12047
                                   stats)
12048

    
12049

    
12050
class LUNetworkQuery(NoHooksLU):
12051
  """Logical unit for querying node groups.
12052

12053
  """
12054
  REQ_BGL = False
12055

    
12056
  def CheckArguments(self):
12057
    self.nq = _NetworkQuery(self.op.names, self.op.output_fields, False)
12058

    
12059
  def ExpandNames(self):
12060
    self.nq.ExpandNames(self)
12061

    
12062
  def Exec(self, feedback_fn):
12063
    return self.nq.OldStyleQuery(self)
12064

    
12065

    
12066
#: Query type implementations
12067
_QUERY_IMPL = {
12068
  constants.QR_INSTANCE: _InstanceQuery,
12069
  constants.QR_NODE: _NodeQuery,
12070
  constants.QR_GROUP: _GroupQuery,
12071
  constants.QR_NETWORK: _NetworkQuery,
12072
  }
12073

    
12074

    
12075
def _GetQueryImplementation(name):
12076
  """Returns the implemtnation for a query type.
12077

12078
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
12079

12080
  """
12081
  try:
12082
    return _QUERY_IMPL[name]
12083
  except KeyError:
12084
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
12085
                               errors.ECODE_INVAL)