Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ c1391810

History | View | Annotate | Download (412.3 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

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

    
63

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

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

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

    
76

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

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

90
  Note that all commands require root permissions.
91

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

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

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

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

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

    
133
    # Tasklets
134
    self.tasklets = None
135

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

    
139
    self.CheckArguments()
140

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

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

    
149
  ssh = property(fget=__GetSSH)
150

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

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

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

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

166
    """
167
    pass
168

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

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

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

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

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

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

194
    Examples::
195

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

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

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

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

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

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

233
    """
234

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

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

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

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

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

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

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

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

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

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

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

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

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

292
    """
293
    raise NotImplementedError
294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
381
    del self.recalculate_locks[locking.LEVEL_NODE]
382

    
383

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

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

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

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

397
    This just raises an error.
398

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

    
402

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

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

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

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

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

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

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

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

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

435
    """
436
    pass
437

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

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

445
    """
446
    raise NotImplementedError
447

    
448

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

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

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

459
    """
460
    self.use_locking = use_locking
461

    
462
    self.query = query.Query(self.FIELDS, fields, filter_=filter_,
463
                             namefield="name")
464
    self.requested_data = self.query.RequestedData()
465
    self.names = self.query.RequestedNames()
466

    
467
    # Sort only if no names were requested
468
    self.sort_by_name = not self.names
469

    
470
    self.do_locking = None
471
    self.wanted = None
472

    
473
  def _GetNames(self, lu, all_names, lock_level):
474
    """Helper function to determine names asked for in the query.
475

476
    """
477
    if self.do_locking:
478
      names = lu.acquired_locks[lock_level]
479
    else:
480
      names = all_names
481

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

    
487
    # caller specified names and we must keep the same order
488
    assert self.names
489
    assert not self.do_locking or lu.acquired_locks[lock_level]
490

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

    
496
    # Return expanded names
497
    return self.wanted
498

    
499
  def ExpandNames(self, lu):
500
    """Expand names for this query.
501

502
    See L{LogicalUnit.ExpandNames}.
503

504
    """
505
    raise NotImplementedError()
506

    
507
  def DeclareLocks(self, lu, level):
508
    """Declare locks for this query.
509

510
    See L{LogicalUnit.DeclareLocks}.
511

512
    """
513
    raise NotImplementedError()
514

    
515
  def _GetQueryData(self, lu):
516
    """Collects all data for this query.
517

518
    @return: Query data object
519

520
    """
521
    raise NotImplementedError()
522

    
523
  def NewStyleQuery(self, lu):
524
    """Collect data and execute query.
525

526
    """
527
    return query.GetQueryResponse(self.query, self._GetQueryData(lu),
528
                                  sort_by_name=self.sort_by_name)
529

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

533
    """
534
    return self.query.OldStyleQuery(self._GetQueryData(lu),
535
                                    sort_by_name=self.sort_by_name)
536

    
537

    
538
def _GetWantedNodes(lu, nodes):
539
  """Returns list of checked and expanded node names.
540

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

549
  """
550
  if nodes:
551
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
552

    
553
  return utils.NiceSort(lu.cfg.GetNodeList())
554

    
555

    
556
def _GetWantedInstances(lu, instances):
557
  """Returns list of checked and expanded instance names.
558

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

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

    
575

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

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

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

    
608

    
609
def _CheckOutputFields(static, dynamic, selected):
610
  """Checks whether all selected fields are valid.
611

612
  @type static: L{utils.FieldSet}
613
  @param static: static fields set
614
  @type dynamic: L{utils.FieldSet}
615
  @param dynamic: dynamic fields set
616

617
  """
618
  f = utils.FieldSet()
619
  f.Extend(static)
620
  f.Extend(dynamic)
621

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

    
627

    
628
def _CheckGlobalHvParams(params):
629
  """Validates that given hypervisor params are not global ones.
630

631
  This will ensure that instances don't get customised versions of
632
  global params.
633

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

    
642

    
643
def _CheckNodeOnline(lu, node, msg=None):
644
  """Ensure that a given node is online.
645

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

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

    
657

    
658
def _CheckNodeNotDrained(lu, node):
659
  """Ensure that a given node is not drained.
660

661
  @param lu: the LU on behalf of which we make the check
662
  @param node: the node to check
663
  @raise errors.OpPrereqError: if the node is drained
664

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

    
670

    
671
def _CheckNodeVmCapable(lu, node):
672
  """Ensure that a given node is vm capable.
673

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

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

    
683

    
684
def _CheckNodeHasOS(lu, node, os_name, force_variant):
685
  """Ensure that a node supports a given OS.
686

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

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

    
701

    
702
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
703
  """Ensure that a node has the given secondary ip.
704

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

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

    
728

    
729
def _GetClusterDomainSecret():
730
  """Reads the cluster domain secret.
731

732
  """
733
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
734
                               strict=True)
735

    
736

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

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

    
748
  if instance.name in ins_l.payload:
749
    raise errors.OpPrereqError("Instance %s is running, %s" %
750
                               (instance.name, reason), errors.ECODE_STATE)
751

    
752

    
753
def _ExpandItemName(fn, name, kind):
754
  """Expand an item name.
755

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

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

    
769

    
770
def _ExpandNodeName(cfg, name):
771
  """Wrapper over L{_ExpandItemName} for nodes."""
772
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
773

    
774

    
775
def _ExpandInstanceName(cfg, name):
776
  """Wrapper over L{_ExpandItemName} for instance."""
777
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
778

    
779

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

785
  This builds the hook environment from individual variables.
786

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

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

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

    
849
  env["INSTANCE_NIC_COUNT"] = nic_count
850

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

    
859
  env["INSTANCE_DISK_COUNT"] = disk_count
860

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

    
865
  return env
866

    
867

    
868
def _NICListToTuple(lu, nics):
869
  """Build a list of nic information tuples.
870

871
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
872
  value in LUInstanceQueryData.
873

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

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

    
891

    
892
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
893
  """Builds instance related env variables for hooks from an object.
894

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

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

    
929

    
930
def _AdjustCandidatePool(lu, exceptions):
931
  """Adjust the candidate pool after node operations.
932

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

    
945

    
946
def _DecideSelfPromotion(lu, exceptions=None):
947
  """Decide whether I should promote myself as a master candidate.
948

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

    
956

    
957
def _CheckNicsBridgesExist(lu, target_nics, target_node):
958
  """Check that the brigdes needed by a list of nics exist.
959

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

    
970

    
971
def _CheckInstanceBridgesExist(lu, instance, node=None):
972
  """Check that the brigdes needed by an instance exist.
973

974
  """
975
  if node is None:
976
    node = instance.primary_node
977
  _CheckNicsBridgesExist(lu, instance.nics, node)
978

    
979

    
980
def _CheckOSVariant(os_obj, name):
981
  """Check whether an OS name conforms to the os variants specification.
982

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

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

    
996
  if variant not in os_obj.supported_variants:
997
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
998

    
999

    
1000
def _GetNodeInstancesInner(cfg, fn):
1001
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1002

    
1003

    
1004
def _GetNodeInstances(cfg, node_name):
1005
  """Returns a list of all primary and secondary instances on a node.
1006

1007
  """
1008

    
1009
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1010

    
1011

    
1012
def _GetNodePrimaryInstances(cfg, node_name):
1013
  """Returns primary instances on a node.
1014

1015
  """
1016
  return _GetNodeInstancesInner(cfg,
1017
                                lambda inst: node_name == inst.primary_node)
1018

    
1019

    
1020
def _GetNodeSecondaryInstances(cfg, node_name):
1021
  """Returns secondary instances on a node.
1022

1023
  """
1024
  return _GetNodeInstancesInner(cfg,
1025
                                lambda inst: node_name in inst.secondary_nodes)
1026

    
1027

    
1028
def _GetStorageTypeArgs(cfg, storage_type):
1029
  """Returns the arguments for a storage type.
1030

1031
  """
1032
  # Special case for file storage
1033
  if storage_type == constants.ST_FILE:
1034
    # storage.FileStorage wants a list of storage directories
1035
    return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1036

    
1037
  return []
1038

    
1039

    
1040
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1041
  faulty = []
1042

    
1043
  for dev in instance.disks:
1044
    cfg.SetDiskID(dev, node_name)
1045

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

    
1050
  for idx, bdev_status in enumerate(result.payload):
1051
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1052
      faulty.append(idx)
1053

    
1054
  return faulty
1055

    
1056

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

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

1065
  @type iallocator_slot: string
1066
  @param iallocator_slot: the name of the opcode iallocator slot
1067
  @type node_slot: string
1068
  @param node_slot: the name of the opcode target node slot
1069

1070
  """
1071
  node = getattr(lu.op, node_slot, None)
1072
  iallocator = getattr(lu.op, iallocator_slot, None)
1073

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

    
1088

    
1089
class LUClusterPostInit(LogicalUnit):
1090
  """Logical unit for running hooks after cluster initialization.
1091

1092
  """
1093
  HPATH = "cluster-init"
1094
  HTYPE = constants.HTYPE_CLUSTER
1095

    
1096
  def BuildHooksEnv(self):
1097
    """Build hooks env.
1098

1099
    """
1100
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1101
    mn = self.cfg.GetMasterNode()
1102
    return env, [], [mn]
1103

    
1104
  def Exec(self, feedback_fn):
1105
    """Nothing to do.
1106

1107
    """
1108
    return True
1109

    
1110

    
1111
class LUClusterDestroy(LogicalUnit):
1112
  """Logical unit for destroying the cluster.
1113

1114
  """
1115
  HPATH = "cluster-destroy"
1116
  HTYPE = constants.HTYPE_CLUSTER
1117

    
1118
  def BuildHooksEnv(self):
1119
    """Build hooks env.
1120

1121
    """
1122
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1123
    return env, [], []
1124

    
1125
  def CheckPrereq(self):
1126
    """Check prerequisites.
1127

1128
    This checks whether the cluster is empty.
1129

1130
    Any errors are signaled by raising errors.OpPrereqError.
1131

1132
    """
1133
    master = self.cfg.GetMasterNode()
1134

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

    
1146
  def Exec(self, feedback_fn):
1147
    """Destroys the cluster.
1148

1149
    """
1150
    master = self.cfg.GetMasterNode()
1151

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

    
1160
    result = self.rpc.call_node_stop_master(master, False)
1161
    result.Raise("Could not disable the master role")
1162

    
1163
    return master
1164

    
1165

    
1166
def _VerifyCertificate(filename):
1167
  """Verifies a certificate for LUClusterVerify.
1168

1169
  @type filename: string
1170
  @param filename: Path to PEM file
1171

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

    
1180
  (errcode, msg) = \
1181
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1182
                                constants.SSL_CERT_EXPIRATION_ERROR)
1183

    
1184
  if msg:
1185
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1186
  else:
1187
    fnamemsg = None
1188

    
1189
  if errcode is None:
1190
    return (None, fnamemsg)
1191
  elif errcode == utils.CERT_WARNING:
1192
    return (LUClusterVerify.ETYPE_WARNING, fnamemsg)
1193
  elif errcode == utils.CERT_ERROR:
1194
    return (LUClusterVerify.ETYPE_ERROR, fnamemsg)
1195

    
1196
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1197

    
1198

    
1199
class LUClusterVerify(LogicalUnit):
1200
  """Verifies the cluster status.
1201

1202
  """
1203
  HPATH = "cluster-verify"
1204
  HTYPE = constants.HTYPE_CLUSTER
1205
  REQ_BGL = False
1206

    
1207
  TCLUSTER = "cluster"
1208
  TNODE = "node"
1209
  TINSTANCE = "instance"
1210

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

    
1238
  ETYPE_FIELD = "code"
1239
  ETYPE_ERROR = "ERROR"
1240
  ETYPE_WARNING = "WARNING"
1241

    
1242
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1243

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

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

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

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

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

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

1307
    This must be called only from Exec and functions called from Exec.
1308

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

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

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

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

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

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

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

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

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

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

    
1381
    # node seems compatible, we can actually try to look into its results
1382

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

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

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

    
1404
    test = nresult.get(constants.NV_NODESETUP,
1405
                           ["Missing NODESETUP results"])
1406
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1407
             "; ".join(test))
1408

    
1409
    return True
1410

    
1411
  def _VerifyNodeTime(self, ninfo, nresult,
1412
                      nvinfo_starttime, nvinfo_endtime):
1413
    """Check the node time.
1414

1415
    @type ninfo: L{objects.Node}
1416
    @param ninfo: the node to check
1417
    @param nresult: the remote results for the node
1418
    @param nvinfo_starttime: the start time of the RPC call
1419
    @param nvinfo_endtime: the end time of the RPC call
1420

1421
    """
1422
    node = ninfo.name
1423
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1424

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

    
1432
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1433
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1434
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1435
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1436
    else:
1437
      ntime_diff = None
1438

    
1439
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1440
             "Node time diverges by at least %s from master node time",
1441
             ntime_diff)
1442

    
1443
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1444
    """Check the node time.
1445

1446
    @type ninfo: L{objects.Node}
1447
    @param ninfo: the node to check
1448
    @param nresult: the remote results for the node
1449
    @param vg_name: the configured VG name
1450

1451
    """
1452
    if vg_name is None:
1453
      return
1454

    
1455
    node = ninfo.name
1456
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1457

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

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

    
1480
  def _VerifyNodeNetwork(self, ninfo, nresult):
1481
    """Check the node time.
1482

1483
    @type ninfo: L{objects.Node}
1484
    @param ninfo: the node to check
1485
    @param nresult: the remote results for the node
1486

1487
    """
1488
    node = ninfo.name
1489
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1490

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

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

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

    
1522
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1523
                      diskstatus):
1524
    """Verify an instance.
1525

1526
    This function checks to see if the required block devices are
1527
    available on the instance's node.
1528

1529
    """
1530
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1531
    node_current = instanceconfig.primary_node
1532

    
1533
    node_vol_should = {}
1534
    instanceconfig.MapLVsByNode(node_vol_should)
1535

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

    
1546
    if instanceconfig.admin_up:
1547
      pri_img = node_image[node_current]
1548
      test = instance not in pri_img.instances and not pri_img.offline
1549
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1550
               "instance not running on its primary node %s",
1551
               node_current)
1552

    
1553
    for node, n_img in node_image.items():
1554
      if node != node_current:
1555
        test = instance in n_img.instances
1556
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1557
                 "instance should not run on node %s", node)
1558

    
1559
    diskdata = [(nname, success, status, idx)
1560
                for (nname, disks) in diskstatus.items()
1561
                for idx, (success, status) in enumerate(disks)]
1562

    
1563
    for nname, success, bdev_status, idx in diskdata:
1564
      # the 'ghost node' construction in Exec() ensures that we have a
1565
      # node here
1566
      snode = node_image[nname]
1567
      bad_snode = snode.ghost or snode.offline
1568
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1569
               self.EINSTANCEFAULTYDISK, instance,
1570
               "couldn't retrieve status for disk/%s on %s: %s",
1571
               idx, nname, bdev_status)
1572
      _ErrorIf((instanceconfig.admin_up and success and
1573
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1574
               self.EINSTANCEFAULTYDISK, instance,
1575
               "disk/%s on %s is faulty", idx, nname)
1576

    
1577
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1578
    """Verify if there are any unknown volumes in the cluster.
1579

1580
    The .os, .swap and backup volumes are ignored. All other volumes are
1581
    reported as unknown.
1582

1583
    @type reserved: L{ganeti.utils.FieldSet}
1584
    @param reserved: a FieldSet of reserved volume names
1585

1586
    """
1587
    for node, n_img in node_image.items():
1588
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1589
        # skip non-healthy nodes
1590
        continue
1591
      for volume in n_img.volumes:
1592
        test = ((node not in node_vol_should or
1593
                volume not in node_vol_should[node]) and
1594
                not reserved.Matches(volume))
1595
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1596
                      "volume %s is unknown", volume)
1597

    
1598
  def _VerifyOrphanInstances(self, instancelist, node_image):
1599
    """Verify the list of running instances.
1600

1601
    This checks what instances are running but unknown to the cluster.
1602

1603
    """
1604
    for node, n_img in node_image.items():
1605
      for o_inst in n_img.instances:
1606
        test = o_inst not in instancelist
1607
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1608
                      "instance %s on node %s should not exist", o_inst, node)
1609

    
1610
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1611
    """Verify N+1 Memory Resilience.
1612

1613
    Check that if one single node dies we can still start all the
1614
    instances it was primary for.
1615

1616
    """
1617
    cluster_info = self.cfg.GetClusterInfo()
1618
    for node, n_img in node_image.items():
1619
      # This code checks that every node which is now listed as
1620
      # secondary has enough memory to host all instances it is
1621
      # supposed to should a single other node in the cluster fail.
1622
      # FIXME: not ready for failover to an arbitrary node
1623
      # FIXME: does not support file-backed instances
1624
      # WARNING: we currently take into account down instances as well
1625
      # as up ones, considering that even if they're down someone
1626
      # might want to start them even in the event of a node failure.
1627
      if n_img.offline:
1628
        # we're skipping offline nodes from the N+1 warning, since
1629
        # most likely we don't have good memory infromation from them;
1630
        # we already list instances living on such nodes, and that's
1631
        # enough warning
1632
        continue
1633
      for prinode, instances in n_img.sbp.items():
1634
        needed_mem = 0
1635
        for instance in instances:
1636
          bep = cluster_info.FillBE(instance_cfg[instance])
1637
          if bep[constants.BE_AUTO_BALANCE]:
1638
            needed_mem += bep[constants.BE_MEMORY]
1639
        test = n_img.mfree < needed_mem
1640
        self._ErrorIf(test, self.ENODEN1, node,
1641
                      "not enough memory to accomodate instance failovers"
1642
                      " should node %s fail", prinode)
1643

    
1644
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1645
                       master_files):
1646
    """Verifies and computes the node required file checksums.
1647

1648
    @type ninfo: L{objects.Node}
1649
    @param ninfo: the node to check
1650
    @param nresult: the remote results for the node
1651
    @param file_list: required list of files
1652
    @param local_cksum: dictionary of local files and their checksums
1653
    @param master_files: list of files that only masters should have
1654

1655
    """
1656
    node = ninfo.name
1657
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1658

    
1659
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1660
    test = not isinstance(remote_cksum, dict)
1661
    _ErrorIf(test, self.ENODEFILECHECK, node,
1662
             "node hasn't returned file checksum data")
1663
    if test:
1664
      return
1665

    
1666
    for file_name in file_list:
1667
      node_is_mc = ninfo.master_candidate
1668
      must_have = (file_name not in master_files) or node_is_mc
1669
      # missing
1670
      test1 = file_name not in remote_cksum
1671
      # invalid checksum
1672
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1673
      # existing and good
1674
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1675
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1676
               "file '%s' missing", file_name)
1677
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1678
               "file '%s' has wrong checksum", file_name)
1679
      # not candidate and this is not a must-have file
1680
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1681
               "file '%s' should not exist on non master"
1682
               " candidates (and the file is outdated)", file_name)
1683
      # all good, except non-master/non-must have combination
1684
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1685
               "file '%s' should not exist"
1686
               " on non master candidates", file_name)
1687

    
1688
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1689
                      drbd_map):
1690
    """Verifies and the node DRBD status.
1691

1692
    @type ninfo: L{objects.Node}
1693
    @param ninfo: the node to check
1694
    @param nresult: the remote results for the node
1695
    @param instanceinfo: the dict of instances
1696
    @param drbd_helper: the configured DRBD usermode helper
1697
    @param drbd_map: the DRBD map as returned by
1698
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1699

1700
    """
1701
    node = ninfo.name
1702
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1703

    
1704
    if drbd_helper:
1705
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1706
      test = (helper_result == None)
1707
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1708
               "no drbd usermode helper returned")
1709
      if helper_result:
1710
        status, payload = helper_result
1711
        test = not status
1712
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1713
                 "drbd usermode helper check unsuccessful: %s", payload)
1714
        test = status and (payload != drbd_helper)
1715
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1716
                 "wrong drbd usermode helper: %s", payload)
1717

    
1718
    # compute the DRBD minors
1719
    node_drbd = {}
1720
    for minor, instance in drbd_map[node].items():
1721
      test = instance not in instanceinfo
1722
      _ErrorIf(test, self.ECLUSTERCFG, None,
1723
               "ghost instance '%s' in temporary DRBD map", instance)
1724
        # ghost instance should not be running, but otherwise we
1725
        # don't give double warnings (both ghost instance and
1726
        # unallocated minor in use)
1727
      if test:
1728
        node_drbd[minor] = (instance, False)
1729
      else:
1730
        instance = instanceinfo[instance]
1731
        node_drbd[minor] = (instance.name, instance.admin_up)
1732

    
1733
    # and now check them
1734
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1735
    test = not isinstance(used_minors, (tuple, list))
1736
    _ErrorIf(test, self.ENODEDRBD, node,
1737
             "cannot parse drbd status file: %s", str(used_minors))
1738
    if test:
1739
      # we cannot check drbd status
1740
      return
1741

    
1742
    for minor, (iname, must_exist) in node_drbd.items():
1743
      test = minor not in used_minors and must_exist
1744
      _ErrorIf(test, self.ENODEDRBD, node,
1745
               "drbd minor %d of instance %s is not active", minor, iname)
1746
    for minor in used_minors:
1747
      test = minor not in node_drbd
1748
      _ErrorIf(test, self.ENODEDRBD, node,
1749
               "unallocated drbd minor %d is in use", minor)
1750

    
1751
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1752
    """Builds the node OS structures.
1753

1754
    @type ninfo: L{objects.Node}
1755
    @param ninfo: the node to check
1756
    @param nresult: the remote results for the node
1757
    @param nimg: the node image object
1758

1759
    """
1760
    node = ninfo.name
1761
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1762

    
1763
    remote_os = nresult.get(constants.NV_OSLIST, None)
1764
    test = (not isinstance(remote_os, list) or
1765
            not compat.all(isinstance(v, list) and len(v) == 7
1766
                           for v in remote_os))
1767

    
1768
    _ErrorIf(test, self.ENODEOS, node,
1769
             "node hasn't returned valid OS data")
1770

    
1771
    nimg.os_fail = test
1772

    
1773
    if test:
1774
      return
1775

    
1776
    os_dict = {}
1777

    
1778
    for (name, os_path, status, diagnose,
1779
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1780

    
1781
      if name not in os_dict:
1782
        os_dict[name] = []
1783

    
1784
      # parameters is a list of lists instead of list of tuples due to
1785
      # JSON lacking a real tuple type, fix it:
1786
      parameters = [tuple(v) for v in parameters]
1787
      os_dict[name].append((os_path, status, diagnose,
1788
                            set(variants), set(parameters), set(api_ver)))
1789

    
1790
    nimg.oslist = os_dict
1791

    
1792
  def _VerifyNodeOS(self, ninfo, nimg, base):
1793
    """Verifies the node OS list.
1794

1795
    @type ninfo: L{objects.Node}
1796
    @param ninfo: the node to check
1797
    @param nimg: the node image object
1798
    @param base: the 'template' node we match against (e.g. from the master)
1799

1800
    """
1801
    node = ninfo.name
1802
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1803

    
1804
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1805

    
1806
    for os_name, os_data in nimg.oslist.items():
1807
      assert os_data, "Empty OS status for OS %s?!" % os_name
1808
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1809
      _ErrorIf(not f_status, self.ENODEOS, node,
1810
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1811
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1812
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1813
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1814
      # this will catched in backend too
1815
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1816
               and not f_var, self.ENODEOS, node,
1817
               "OS %s with API at least %d does not declare any variant",
1818
               os_name, constants.OS_API_V15)
1819
      # comparisons with the 'base' image
1820
      test = os_name not in base.oslist
1821
      _ErrorIf(test, self.ENODEOS, node,
1822
               "Extra OS %s not present on reference node (%s)",
1823
               os_name, base.name)
1824
      if test:
1825
        continue
1826
      assert base.oslist[os_name], "Base node has empty OS status?"
1827
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1828
      if not b_status:
1829
        # base OS is invalid, skipping
1830
        continue
1831
      for kind, a, b in [("API version", f_api, b_api),
1832
                         ("variants list", f_var, b_var),
1833
                         ("parameters", f_param, b_param)]:
1834
        _ErrorIf(a != b, self.ENODEOS, node,
1835
                 "OS %s %s differs from reference node %s: %s vs. %s",
1836
                 kind, os_name, base.name,
1837
                 utils.CommaJoin(a), utils.CommaJoin(b))
1838

    
1839
    # check any missing OSes
1840
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1841
    _ErrorIf(missing, self.ENODEOS, node,
1842
             "OSes present on reference node %s but missing on this node: %s",
1843
             base.name, utils.CommaJoin(missing))
1844

    
1845
  def _VerifyOob(self, ninfo, nresult):
1846
    """Verifies out of band functionality of a node.
1847

1848
    @type ninfo: L{objects.Node}
1849
    @param ninfo: the node to check
1850
    @param nresult: the remote results for the node
1851

1852
    """
1853
    node = ninfo.name
1854
    # We just have to verify the paths on master and/or master candidates
1855
    # as the oob helper is invoked on the master
1856
    if ((ninfo.master_candidate or ninfo.master_capable) and
1857
        constants.NV_OOB_PATHS in nresult):
1858
      for path_result in nresult[constants.NV_OOB_PATHS]:
1859
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
1860

    
1861
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1862
    """Verifies and updates the node volume data.
1863

1864
    This function will update a L{NodeImage}'s internal structures
1865
    with data from the remote call.
1866

1867
    @type ninfo: L{objects.Node}
1868
    @param ninfo: the node to check
1869
    @param nresult: the remote results for the node
1870
    @param nimg: the node image object
1871
    @param vg_name: the configured VG name
1872

1873
    """
1874
    node = ninfo.name
1875
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1876

    
1877
    nimg.lvm_fail = True
1878
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1879
    if vg_name is None:
1880
      pass
1881
    elif isinstance(lvdata, basestring):
1882
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1883
               utils.SafeEncode(lvdata))
1884
    elif not isinstance(lvdata, dict):
1885
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1886
    else:
1887
      nimg.volumes = lvdata
1888
      nimg.lvm_fail = False
1889

    
1890
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1891
    """Verifies and updates the node instance list.
1892

1893
    If the listing was successful, then updates this node's instance
1894
    list. Otherwise, it marks the RPC call as failed for the instance
1895
    list key.
1896

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

1902
    """
1903
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1904
    test = not isinstance(idata, list)
1905
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1906
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1907
    if test:
1908
      nimg.hyp_fail = True
1909
    else:
1910
      nimg.instances = idata
1911

    
1912
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1913
    """Verifies and computes a node information map
1914

1915
    @type ninfo: L{objects.Node}
1916
    @param ninfo: the node to check
1917
    @param nresult: the remote results for the node
1918
    @param nimg: the node image object
1919
    @param vg_name: the configured VG name
1920

1921
    """
1922
    node = ninfo.name
1923
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1924

    
1925
    # try to read free memory (from the hypervisor)
1926
    hv_info = nresult.get(constants.NV_HVINFO, None)
1927
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1928
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1929
    if not test:
1930
      try:
1931
        nimg.mfree = int(hv_info["memory_free"])
1932
      except (ValueError, TypeError):
1933
        _ErrorIf(True, self.ENODERPC, node,
1934
                 "node returned invalid nodeinfo, check hypervisor")
1935

    
1936
    # FIXME: devise a free space model for file based instances as well
1937
    if vg_name is not None:
1938
      test = (constants.NV_VGLIST not in nresult or
1939
              vg_name not in nresult[constants.NV_VGLIST])
1940
      _ErrorIf(test, self.ENODELVM, node,
1941
               "node didn't return data for the volume group '%s'"
1942
               " - it is either missing or broken", vg_name)
1943
      if not test:
1944
        try:
1945
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1946
        except (ValueError, TypeError):
1947
          _ErrorIf(True, self.ENODERPC, node,
1948
                   "node returned invalid LVM info, check LVM status")
1949

    
1950
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1951
    """Gets per-disk status information for all instances.
1952

1953
    @type nodelist: list of strings
1954
    @param nodelist: Node names
1955
    @type node_image: dict of (name, L{objects.Node})
1956
    @param node_image: Node objects
1957
    @type instanceinfo: dict of (name, L{objects.Instance})
1958
    @param instanceinfo: Instance objects
1959
    @rtype: {instance: {node: [(succes, payload)]}}
1960
    @return: a dictionary of per-instance dictionaries with nodes as
1961
        keys and disk information as values; the disk information is a
1962
        list of tuples (success, payload)
1963

1964
    """
1965
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1966

    
1967
    node_disks = {}
1968
    node_disks_devonly = {}
1969
    diskless_instances = set()
1970
    diskless = constants.DT_DISKLESS
1971

    
1972
    for nname in nodelist:
1973
      node_instances = list(itertools.chain(node_image[nname].pinst,
1974
                                            node_image[nname].sinst))
1975
      diskless_instances.update(inst for inst in node_instances
1976
                                if instanceinfo[inst].disk_template == diskless)
1977
      disks = [(inst, disk)
1978
               for inst in node_instances
1979
               for disk in instanceinfo[inst].disks]
1980

    
1981
      if not disks:
1982
        # No need to collect data
1983
        continue
1984

    
1985
      node_disks[nname] = disks
1986

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

    
1991
      for dev in devonly:
1992
        self.cfg.SetDiskID(dev, nname)
1993

    
1994
      node_disks_devonly[nname] = devonly
1995

    
1996
    assert len(node_disks) == len(node_disks_devonly)
1997

    
1998
    # Collect data from all nodes with disks
1999
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2000
                                                          node_disks_devonly)
2001

    
2002
    assert len(result) == len(node_disks)
2003

    
2004
    instdisk = {}
2005

    
2006
    for (nname, nres) in result.items():
2007
      disks = node_disks[nname]
2008

    
2009
      if nres.offline:
2010
        # No data from this node
2011
        data = len(disks) * [(False, "node offline")]
2012
      else:
2013
        msg = nres.fail_msg
2014
        _ErrorIf(msg, self.ENODERPC, nname,
2015
                 "while getting disk information: %s", msg)
2016
        if msg:
2017
          # No data from this node
2018
          data = len(disks) * [(False, msg)]
2019
        else:
2020
          data = []
2021
          for idx, i in enumerate(nres.payload):
2022
            if isinstance(i, (tuple, list)) and len(i) == 2:
2023
              data.append(i)
2024
            else:
2025
              logging.warning("Invalid result from node %s, entry %d: %s",
2026
                              nname, idx, i)
2027
              data.append((False, "Invalid result from the remote node"))
2028

    
2029
      for ((inst, _), status) in zip(disks, data):
2030
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2031

    
2032
    # Add empty entries for diskless instances.
2033
    for inst in diskless_instances:
2034
      assert inst not in instdisk
2035
      instdisk[inst] = {}
2036

    
2037
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2038
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2039
                      compat.all(isinstance(s, (tuple, list)) and
2040
                                 len(s) == 2 for s in statuses)
2041
                      for inst, nnames in instdisk.items()
2042
                      for nname, statuses in nnames.items())
2043
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2044

    
2045
    return instdisk
2046

    
2047
  def _VerifyHVP(self, hvp_data):
2048
    """Verifies locally the syntax of the hypervisor parameters.
2049

2050
    """
2051
    for item, hv_name, hv_params in hvp_data:
2052
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
2053
             (item, hv_name))
2054
      try:
2055
        hv_class = hypervisor.GetHypervisor(hv_name)
2056
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2057
        hv_class.CheckParameterSyntax(hv_params)
2058
      except errors.GenericError, err:
2059
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
2060

    
2061

    
2062
  def BuildHooksEnv(self):
2063
    """Build hooks env.
2064

2065
    Cluster-Verify hooks just ran in the post phase and their failure makes
2066
    the output be logged in the verify output and the verification to fail.
2067

2068
    """
2069
    all_nodes = self.cfg.GetNodeList()
2070
    env = {
2071
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2072
      }
2073
    for node in self.cfg.GetAllNodesInfo().values():
2074
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2075

    
2076
    return env, [], all_nodes
2077

    
2078
  def Exec(self, feedback_fn):
2079
    """Verify integrity of cluster, performing various test on nodes.
2080

2081
    """
2082
    # This method has too many local variables. pylint: disable-msg=R0914
2083
    self.bad = False
2084
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2085
    verbose = self.op.verbose
2086
    self._feedback_fn = feedback_fn
2087
    feedback_fn("* Verifying global settings")
2088
    for msg in self.cfg.VerifyConfig():
2089
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2090

    
2091
    # Check the cluster certificates
2092
    for cert_filename in constants.ALL_CERT_FILES:
2093
      (errcode, msg) = _VerifyCertificate(cert_filename)
2094
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2095

    
2096
    vg_name = self.cfg.GetVGName()
2097
    drbd_helper = self.cfg.GetDRBDHelper()
2098
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2099
    cluster = self.cfg.GetClusterInfo()
2100
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2101
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2102
    nodeinfo_byname = dict(zip(nodelist, nodeinfo))
2103
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2104
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2105
                        for iname in instancelist)
2106
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2107
    i_non_redundant = [] # Non redundant instances
2108
    i_non_a_balanced = [] # Non auto-balanced instances
2109
    n_offline = 0 # Count of offline nodes
2110
    n_drained = 0 # Count of nodes being drained
2111
    node_vol_should = {}
2112

    
2113
    # FIXME: verify OS list
2114
    # do local checksums
2115
    master_files = [constants.CLUSTER_CONF_FILE]
2116
    master_node = self.master_node = self.cfg.GetMasterNode()
2117
    master_ip = self.cfg.GetMasterIP()
2118

    
2119
    file_names = ssconf.SimpleStore().GetFileList()
2120
    file_names.extend(constants.ALL_CERT_FILES)
2121
    file_names.extend(master_files)
2122
    if cluster.modify_etc_hosts:
2123
      file_names.append(constants.ETC_HOSTS)
2124

    
2125
    local_checksums = utils.FingerprintFiles(file_names)
2126

    
2127
    # Compute the set of hypervisor parameters
2128
    hvp_data = []
2129
    for hv_name in hypervisors:
2130
      hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
2131
    for os_name, os_hvp in cluster.os_hvp.items():
2132
      for hv_name, hv_params in os_hvp.items():
2133
        if not hv_params:
2134
          continue
2135
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
2136
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
2137
    # TODO: collapse identical parameter values in a single one
2138
    for instance in instanceinfo.values():
2139
      if not instance.hvparams:
2140
        continue
2141
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
2142
                       cluster.FillHV(instance)))
2143
    # and verify them locally
2144
    self._VerifyHVP(hvp_data)
2145

    
2146
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2147
    node_verify_param = {
2148
      constants.NV_FILELIST: file_names,
2149
      constants.NV_NODELIST: [node.name for node in nodeinfo
2150
                              if not node.offline],
2151
      constants.NV_HYPERVISOR: hypervisors,
2152
      constants.NV_HVPARAMS: hvp_data,
2153
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2154
                                  node.secondary_ip) for node in nodeinfo
2155
                                 if not node.offline],
2156
      constants.NV_INSTANCELIST: hypervisors,
2157
      constants.NV_VERSION: None,
2158
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2159
      constants.NV_NODESETUP: None,
2160
      constants.NV_TIME: None,
2161
      constants.NV_MASTERIP: (master_node, master_ip),
2162
      constants.NV_OSLIST: None,
2163
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2164
      }
2165

    
2166
    if vg_name is not None:
2167
      node_verify_param[constants.NV_VGLIST] = None
2168
      node_verify_param[constants.NV_LVLIST] = vg_name
2169
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2170
      node_verify_param[constants.NV_DRBDLIST] = None
2171

    
2172
    if drbd_helper:
2173
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2174

    
2175
    # Build our expected cluster state
2176
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2177
                                                 name=node.name,
2178
                                                 vm_capable=node.vm_capable))
2179
                      for node in nodeinfo)
2180

    
2181
    # Gather OOB paths
2182
    oob_paths = []
2183
    for node in nodeinfo:
2184
      path = _SupportsOob(self.cfg, node)
2185
      if path and path not in oob_paths:
2186
        oob_paths.append(path)
2187

    
2188
    if oob_paths:
2189
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2190

    
2191
    for instance in instancelist:
2192
      inst_config = instanceinfo[instance]
2193

    
2194
      for nname in inst_config.all_nodes:
2195
        if nname not in node_image:
2196
          # ghost node
2197
          gnode = self.NodeImage(name=nname)
2198
          gnode.ghost = True
2199
          node_image[nname] = gnode
2200

    
2201
      inst_config.MapLVsByNode(node_vol_should)
2202

    
2203
      pnode = inst_config.primary_node
2204
      node_image[pnode].pinst.append(instance)
2205

    
2206
      for snode in inst_config.secondary_nodes:
2207
        nimg = node_image[snode]
2208
        nimg.sinst.append(instance)
2209
        if pnode not in nimg.sbp:
2210
          nimg.sbp[pnode] = []
2211
        nimg.sbp[pnode].append(instance)
2212

    
2213
    # At this point, we have the in-memory data structures complete,
2214
    # except for the runtime information, which we'll gather next
2215

    
2216
    # Due to the way our RPC system works, exact response times cannot be
2217
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2218
    # time before and after executing the request, we can at least have a time
2219
    # window.
2220
    nvinfo_starttime = time.time()
2221
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2222
                                           self.cfg.GetClusterName())
2223
    nvinfo_endtime = time.time()
2224

    
2225
    all_drbd_map = self.cfg.ComputeDRBDMap()
2226

    
2227
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2228
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2229

    
2230
    feedback_fn("* Verifying node status")
2231

    
2232
    refos_img = None
2233

    
2234
    for node_i in nodeinfo:
2235
      node = node_i.name
2236
      nimg = node_image[node]
2237

    
2238
      if node_i.offline:
2239
        if verbose:
2240
          feedback_fn("* Skipping offline node %s" % (node,))
2241
        n_offline += 1
2242
        continue
2243

    
2244
      if node == master_node:
2245
        ntype = "master"
2246
      elif node_i.master_candidate:
2247
        ntype = "master candidate"
2248
      elif node_i.drained:
2249
        ntype = "drained"
2250
        n_drained += 1
2251
      else:
2252
        ntype = "regular"
2253
      if verbose:
2254
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2255

    
2256
      msg = all_nvinfo[node].fail_msg
2257
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2258
      if msg:
2259
        nimg.rpc_fail = True
2260
        continue
2261

    
2262
      nresult = all_nvinfo[node].payload
2263

    
2264
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2265
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2266
      self._VerifyNodeNetwork(node_i, nresult)
2267
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2268
                            master_files)
2269

    
2270
      self._VerifyOob(node_i, nresult)
2271

    
2272
      if nimg.vm_capable:
2273
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2274
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2275
                             all_drbd_map)
2276

    
2277
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2278
        self._UpdateNodeInstances(node_i, nresult, nimg)
2279
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2280
        self._UpdateNodeOS(node_i, nresult, nimg)
2281
        if not nimg.os_fail:
2282
          if refos_img is None:
2283
            refos_img = nimg
2284
          self._VerifyNodeOS(node_i, nimg, refos_img)
2285

    
2286
    feedback_fn("* Verifying instance status")
2287
    for instance in instancelist:
2288
      if verbose:
2289
        feedback_fn("* Verifying instance %s" % instance)
2290
      inst_config = instanceinfo[instance]
2291
      self._VerifyInstance(instance, inst_config, node_image,
2292
                           instdisk[instance])
2293
      inst_nodes_offline = []
2294

    
2295
      pnode = inst_config.primary_node
2296
      pnode_img = node_image[pnode]
2297
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2298
               self.ENODERPC, pnode, "instance %s, connection to"
2299
               " primary node failed", instance)
2300

    
2301
      _ErrorIf(pnode_img.offline, self.EINSTANCEBADNODE, instance,
2302
               "instance lives on offline node %s", inst_config.primary_node)
2303

    
2304
      # If the instance is non-redundant we cannot survive losing its primary
2305
      # node, so we are not N+1 compliant. On the other hand we have no disk
2306
      # templates with more than one secondary so that situation is not well
2307
      # supported either.
2308
      # FIXME: does not support file-backed instances
2309
      if not inst_config.secondary_nodes:
2310
        i_non_redundant.append(instance)
2311

    
2312
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2313
               instance, "instance has multiple secondary nodes: %s",
2314
               utils.CommaJoin(inst_config.secondary_nodes),
2315
               code=self.ETYPE_WARNING)
2316

    
2317
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2318
        pnode = inst_config.primary_node
2319
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2320
        instance_groups = {}
2321

    
2322
        for node in instance_nodes:
2323
          instance_groups.setdefault(nodeinfo_byname[node].group,
2324
                                     []).append(node)
2325

    
2326
        pretty_list = [
2327
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2328
          # Sort so that we always list the primary node first.
2329
          for group, nodes in sorted(instance_groups.items(),
2330
                                     key=lambda (_, nodes): pnode in nodes,
2331
                                     reverse=True)]
2332

    
2333
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2334
                      instance, "instance has primary and secondary nodes in"
2335
                      " different groups: %s", utils.CommaJoin(pretty_list),
2336
                      code=self.ETYPE_WARNING)
2337

    
2338
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2339
        i_non_a_balanced.append(instance)
2340

    
2341
      for snode in inst_config.secondary_nodes:
2342
        s_img = node_image[snode]
2343
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2344
                 "instance %s, connection to secondary node failed", instance)
2345

    
2346
        if s_img.offline:
2347
          inst_nodes_offline.append(snode)
2348

    
2349
      # warn that the instance lives on offline nodes
2350
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2351
               "instance has offline secondary node(s) %s",
2352
               utils.CommaJoin(inst_nodes_offline))
2353
      # ... or ghost/non-vm_capable nodes
2354
      for node in inst_config.all_nodes:
2355
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2356
                 "instance lives on ghost node %s", node)
2357
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2358
                 instance, "instance lives on non-vm_capable node %s", node)
2359

    
2360
    feedback_fn("* Verifying orphan volumes")
2361
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2362
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2363

    
2364
    feedback_fn("* Verifying orphan instances")
2365
    self._VerifyOrphanInstances(instancelist, node_image)
2366

    
2367
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2368
      feedback_fn("* Verifying N+1 Memory redundancy")
2369
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2370

    
2371
    feedback_fn("* Other Notes")
2372
    if i_non_redundant:
2373
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2374
                  % len(i_non_redundant))
2375

    
2376
    if i_non_a_balanced:
2377
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2378
                  % len(i_non_a_balanced))
2379

    
2380
    if n_offline:
2381
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2382

    
2383
    if n_drained:
2384
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2385

    
2386
    return not self.bad
2387

    
2388
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2389
    """Analyze the post-hooks' result
2390

2391
    This method analyses the hook result, handles it, and sends some
2392
    nicely-formatted feedback back to the user.
2393

2394
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2395
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2396
    @param hooks_results: the results of the multi-node hooks rpc call
2397
    @param feedback_fn: function used send feedback back to the caller
2398
    @param lu_result: previous Exec result
2399
    @return: the new Exec result, based on the previous result
2400
        and hook results
2401

2402
    """
2403
    # We only really run POST phase hooks, and are only interested in
2404
    # their results
2405
    if phase == constants.HOOKS_PHASE_POST:
2406
      # Used to change hooks' output to proper indentation
2407
      feedback_fn("* Hooks Results")
2408
      assert hooks_results, "invalid result from hooks"
2409

    
2410
      for node_name in hooks_results:
2411
        res = hooks_results[node_name]
2412
        msg = res.fail_msg
2413
        test = msg and not res.offline
2414
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2415
                      "Communication failure in hooks execution: %s", msg)
2416
        if res.offline or msg:
2417
          # No need to investigate payload if node is offline or gave an error.
2418
          # override manually lu_result here as _ErrorIf only
2419
          # overrides self.bad
2420
          lu_result = 1
2421
          continue
2422
        for script, hkr, output in res.payload:
2423
          test = hkr == constants.HKR_FAIL
2424
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2425
                        "Script %s failed, output:", script)
2426
          if test:
2427
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2428
            feedback_fn("%s" % output)
2429
            lu_result = 0
2430

    
2431
      return lu_result
2432

    
2433

    
2434
class LUClusterVerifyDisks(NoHooksLU):
2435
  """Verifies the cluster disks status.
2436

2437
  """
2438
  REQ_BGL = False
2439

    
2440
  def ExpandNames(self):
2441
    self.needed_locks = {
2442
      locking.LEVEL_NODE: locking.ALL_SET,
2443
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2444
    }
2445
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2446

    
2447
  def Exec(self, feedback_fn):
2448
    """Verify integrity of cluster disks.
2449

2450
    @rtype: tuple of three items
2451
    @return: a tuple of (dict of node-to-node_error, list of instances
2452
        which need activate-disks, dict of instance: (node, volume) for
2453
        missing volumes
2454

2455
    """
2456
    result = res_nodes, res_instances, res_missing = {}, [], {}
2457

    
2458
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2459
    instances = self.cfg.GetAllInstancesInfo().values()
2460

    
2461
    nv_dict = {}
2462
    for inst in instances:
2463
      inst_lvs = {}
2464
      if not inst.admin_up:
2465
        continue
2466
      inst.MapLVsByNode(inst_lvs)
2467
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2468
      for node, vol_list in inst_lvs.iteritems():
2469
        for vol in vol_list:
2470
          nv_dict[(node, vol)] = inst
2471

    
2472
    if not nv_dict:
2473
      return result
2474

    
2475
    node_lvs = self.rpc.call_lv_list(nodes, [])
2476
    for node, node_res in node_lvs.items():
2477
      if node_res.offline:
2478
        continue
2479
      msg = node_res.fail_msg
2480
      if msg:
2481
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2482
        res_nodes[node] = msg
2483
        continue
2484

    
2485
      lvs = node_res.payload
2486
      for lv_name, (_, _, lv_online) in lvs.items():
2487
        inst = nv_dict.pop((node, lv_name), None)
2488
        if (not lv_online and inst is not None
2489
            and inst.name not in res_instances):
2490
          res_instances.append(inst.name)
2491

    
2492
    # any leftover items in nv_dict are missing LVs, let's arrange the
2493
    # data better
2494
    for key, inst in nv_dict.iteritems():
2495
      if inst.name not in res_missing:
2496
        res_missing[inst.name] = []
2497
      res_missing[inst.name].append(key)
2498

    
2499
    return result
2500

    
2501

    
2502
class LUClusterRepairDiskSizes(NoHooksLU):
2503
  """Verifies the cluster disks sizes.
2504

2505
  """
2506
  REQ_BGL = False
2507

    
2508
  def ExpandNames(self):
2509
    if self.op.instances:
2510
      self.wanted_names = []
2511
      for name in self.op.instances:
2512
        full_name = _ExpandInstanceName(self.cfg, name)
2513
        self.wanted_names.append(full_name)
2514
      self.needed_locks = {
2515
        locking.LEVEL_NODE: [],
2516
        locking.LEVEL_INSTANCE: self.wanted_names,
2517
        }
2518
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2519
    else:
2520
      self.wanted_names = None
2521
      self.needed_locks = {
2522
        locking.LEVEL_NODE: locking.ALL_SET,
2523
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2524
        }
2525
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2526

    
2527
  def DeclareLocks(self, level):
2528
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2529
      self._LockInstancesNodes(primary_only=True)
2530

    
2531
  def CheckPrereq(self):
2532
    """Check prerequisites.
2533

2534
    This only checks the optional instance list against the existing names.
2535

2536
    """
2537
    if self.wanted_names is None:
2538
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2539

    
2540
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2541
                             in self.wanted_names]
2542

    
2543
  def _EnsureChildSizes(self, disk):
2544
    """Ensure children of the disk have the needed disk size.
2545

2546
    This is valid mainly for DRBD8 and fixes an issue where the
2547
    children have smaller disk size.
2548

2549
    @param disk: an L{ganeti.objects.Disk} object
2550

2551
    """
2552
    if disk.dev_type == constants.LD_DRBD8:
2553
      assert disk.children, "Empty children for DRBD8?"
2554
      fchild = disk.children[0]
2555
      mismatch = fchild.size < disk.size
2556
      if mismatch:
2557
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2558
                     fchild.size, disk.size)
2559
        fchild.size = disk.size
2560

    
2561
      # and we recurse on this child only, not on the metadev
2562
      return self._EnsureChildSizes(fchild) or mismatch
2563
    else:
2564
      return False
2565

    
2566
  def Exec(self, feedback_fn):
2567
    """Verify the size of cluster disks.
2568

2569
    """
2570
    # TODO: check child disks too
2571
    # TODO: check differences in size between primary/secondary nodes
2572
    per_node_disks = {}
2573
    for instance in self.wanted_instances:
2574
      pnode = instance.primary_node
2575
      if pnode not in per_node_disks:
2576
        per_node_disks[pnode] = []
2577
      for idx, disk in enumerate(instance.disks):
2578
        per_node_disks[pnode].append((instance, idx, disk))
2579

    
2580
    changed = []
2581
    for node, dskl in per_node_disks.items():
2582
      newl = [v[2].Copy() for v in dskl]
2583
      for dsk in newl:
2584
        self.cfg.SetDiskID(dsk, node)
2585
      result = self.rpc.call_blockdev_getsize(node, newl)
2586
      if result.fail_msg:
2587
        self.LogWarning("Failure in blockdev_getsize call to node"
2588
                        " %s, ignoring", node)
2589
        continue
2590
      if len(result.payload) != len(dskl):
2591
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2592
                        " result.payload=%s", node, len(dskl), result.payload)
2593
        self.LogWarning("Invalid result from node %s, ignoring node results",
2594
                        node)
2595
        continue
2596
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2597
        if size is None:
2598
          self.LogWarning("Disk %d of instance %s did not return size"
2599
                          " information, ignoring", idx, instance.name)
2600
          continue
2601
        if not isinstance(size, (int, long)):
2602
          self.LogWarning("Disk %d of instance %s did not return valid"
2603
                          " size information, ignoring", idx, instance.name)
2604
          continue
2605
        size = size >> 20
2606
        if size != disk.size:
2607
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2608
                       " correcting: recorded %d, actual %d", idx,
2609
                       instance.name, disk.size, size)
2610
          disk.size = size
2611
          self.cfg.Update(instance, feedback_fn)
2612
          changed.append((instance.name, idx, size))
2613
        if self._EnsureChildSizes(disk):
2614
          self.cfg.Update(instance, feedback_fn)
2615
          changed.append((instance.name, idx, disk.size))
2616
    return changed
2617

    
2618

    
2619
class LUClusterRename(LogicalUnit):
2620
  """Rename the cluster.
2621

2622
  """
2623
  HPATH = "cluster-rename"
2624
  HTYPE = constants.HTYPE_CLUSTER
2625

    
2626
  def BuildHooksEnv(self):
2627
    """Build hooks env.
2628

2629
    """
2630
    env = {
2631
      "OP_TARGET": self.cfg.GetClusterName(),
2632
      "NEW_NAME": self.op.name,
2633
      }
2634
    mn = self.cfg.GetMasterNode()
2635
    all_nodes = self.cfg.GetNodeList()
2636
    return env, [mn], all_nodes
2637

    
2638
  def CheckPrereq(self):
2639
    """Verify that the passed name is a valid one.
2640

2641
    """
2642
    hostname = netutils.GetHostname(name=self.op.name,
2643
                                    family=self.cfg.GetPrimaryIPFamily())
2644

    
2645
    new_name = hostname.name
2646
    self.ip = new_ip = hostname.ip
2647
    old_name = self.cfg.GetClusterName()
2648
    old_ip = self.cfg.GetMasterIP()
2649
    if new_name == old_name and new_ip == old_ip:
2650
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2651
                                 " cluster has changed",
2652
                                 errors.ECODE_INVAL)
2653
    if new_ip != old_ip:
2654
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2655
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2656
                                   " reachable on the network" %
2657
                                   new_ip, errors.ECODE_NOTUNIQUE)
2658

    
2659
    self.op.name = new_name
2660

    
2661
  def Exec(self, feedback_fn):
2662
    """Rename the cluster.
2663

2664
    """
2665
    clustername = self.op.name
2666
    ip = self.ip
2667

    
2668
    # shutdown the master IP
2669
    master = self.cfg.GetMasterNode()
2670
    result = self.rpc.call_node_stop_master(master, False)
2671
    result.Raise("Could not disable the master role")
2672

    
2673
    try:
2674
      cluster = self.cfg.GetClusterInfo()
2675
      cluster.cluster_name = clustername
2676
      cluster.master_ip = ip
2677
      self.cfg.Update(cluster, feedback_fn)
2678

    
2679
      # update the known hosts file
2680
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2681
      node_list = self.cfg.GetOnlineNodeList()
2682
      try:
2683
        node_list.remove(master)
2684
      except ValueError:
2685
        pass
2686
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2687
    finally:
2688
      result = self.rpc.call_node_start_master(master, False, False)
2689
      msg = result.fail_msg
2690
      if msg:
2691
        self.LogWarning("Could not re-enable the master role on"
2692
                        " the master, please restart manually: %s", msg)
2693

    
2694
    return clustername
2695

    
2696

    
2697
class LUClusterSetParams(LogicalUnit):
2698
  """Change the parameters of the cluster.
2699

2700
  """
2701
  HPATH = "cluster-modify"
2702
  HTYPE = constants.HTYPE_CLUSTER
2703
  REQ_BGL = False
2704

    
2705
  def CheckArguments(self):
2706
    """Check parameters
2707

2708
    """
2709
    if self.op.uid_pool:
2710
      uidpool.CheckUidPool(self.op.uid_pool)
2711

    
2712
    if self.op.add_uids:
2713
      uidpool.CheckUidPool(self.op.add_uids)
2714

    
2715
    if self.op.remove_uids:
2716
      uidpool.CheckUidPool(self.op.remove_uids)
2717

    
2718
  def ExpandNames(self):
2719
    # FIXME: in the future maybe other cluster params won't require checking on
2720
    # all nodes to be modified.
2721
    self.needed_locks = {
2722
      locking.LEVEL_NODE: locking.ALL_SET,
2723
    }
2724
    self.share_locks[locking.LEVEL_NODE] = 1
2725

    
2726
  def BuildHooksEnv(self):
2727
    """Build hooks env.
2728

2729
    """
2730
    env = {
2731
      "OP_TARGET": self.cfg.GetClusterName(),
2732
      "NEW_VG_NAME": self.op.vg_name,
2733
      }
2734
    mn = self.cfg.GetMasterNode()
2735
    return env, [mn], [mn]
2736

    
2737
  def CheckPrereq(self):
2738
    """Check prerequisites.
2739

2740
    This checks whether the given params don't conflict and
2741
    if the given volume group is valid.
2742

2743
    """
2744
    if self.op.vg_name is not None and not self.op.vg_name:
2745
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2746
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2747
                                   " instances exist", errors.ECODE_INVAL)
2748

    
2749
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2750
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2751
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2752
                                   " drbd-based instances exist",
2753
                                   errors.ECODE_INVAL)
2754

    
2755
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2756

    
2757
    # if vg_name not None, checks given volume group on all nodes
2758
    if self.op.vg_name:
2759
      vglist = self.rpc.call_vg_list(node_list)
2760
      for node in node_list:
2761
        msg = vglist[node].fail_msg
2762
        if msg:
2763
          # ignoring down node
2764
          self.LogWarning("Error while gathering data on node %s"
2765
                          " (ignoring node): %s", node, msg)
2766
          continue
2767
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2768
                                              self.op.vg_name,
2769
                                              constants.MIN_VG_SIZE)
2770
        if vgstatus:
2771
          raise errors.OpPrereqError("Error on node '%s': %s" %
2772
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2773

    
2774
    if self.op.drbd_helper:
2775
      # checks given drbd helper on all nodes
2776
      helpers = self.rpc.call_drbd_helper(node_list)
2777
      for node in node_list:
2778
        ninfo = self.cfg.GetNodeInfo(node)
2779
        if ninfo.offline:
2780
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2781
          continue
2782
        msg = helpers[node].fail_msg
2783
        if msg:
2784
          raise errors.OpPrereqError("Error checking drbd helper on node"
2785
                                     " '%s': %s" % (node, msg),
2786
                                     errors.ECODE_ENVIRON)
2787
        node_helper = helpers[node].payload
2788
        if node_helper != self.op.drbd_helper:
2789
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2790
                                     (node, node_helper), errors.ECODE_ENVIRON)
2791

    
2792
    self.cluster = cluster = self.cfg.GetClusterInfo()
2793
    # validate params changes
2794
    if self.op.beparams:
2795
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2796
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2797

    
2798
    if self.op.ndparams:
2799
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2800
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2801

    
2802
    if self.op.nicparams:
2803
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2804
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2805
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2806
      nic_errors = []
2807

    
2808
      # check all instances for consistency
2809
      for instance in self.cfg.GetAllInstancesInfo().values():
2810
        for nic_idx, nic in enumerate(instance.nics):
2811
          params_copy = copy.deepcopy(nic.nicparams)
2812
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2813

    
2814
          # check parameter syntax
2815
          try:
2816
            objects.NIC.CheckParameterSyntax(params_filled)
2817
          except errors.ConfigurationError, err:
2818
            nic_errors.append("Instance %s, nic/%d: %s" %
2819
                              (instance.name, nic_idx, err))
2820

    
2821
          # if we're moving instances to routed, check that they have an ip
2822
          target_mode = params_filled[constants.NIC_MODE]
2823
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2824
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2825
                              (instance.name, nic_idx))
2826
      if nic_errors:
2827
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2828
                                   "\n".join(nic_errors))
2829

    
2830
    # hypervisor list/parameters
2831
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2832
    if self.op.hvparams:
2833
      for hv_name, hv_dict in self.op.hvparams.items():
2834
        if hv_name not in self.new_hvparams:
2835
          self.new_hvparams[hv_name] = hv_dict
2836
        else:
2837
          self.new_hvparams[hv_name].update(hv_dict)
2838

    
2839
    # os hypervisor parameters
2840
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2841
    if self.op.os_hvp:
2842
      for os_name, hvs in self.op.os_hvp.items():
2843
        if os_name not in self.new_os_hvp:
2844
          self.new_os_hvp[os_name] = hvs
2845
        else:
2846
          for hv_name, hv_dict in hvs.items():
2847
            if hv_name not in self.new_os_hvp[os_name]:
2848
              self.new_os_hvp[os_name][hv_name] = hv_dict
2849
            else:
2850
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2851

    
2852
    # os parameters
2853
    self.new_osp = objects.FillDict(cluster.osparams, {})
2854
    if self.op.osparams:
2855
      for os_name, osp in self.op.osparams.items():
2856
        if os_name not in self.new_osp:
2857
          self.new_osp[os_name] = {}
2858

    
2859
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2860
                                                  use_none=True)
2861

    
2862
        if not self.new_osp[os_name]:
2863
          # we removed all parameters
2864
          del self.new_osp[os_name]
2865
        else:
2866
          # check the parameter validity (remote check)
2867
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2868
                         os_name, self.new_osp[os_name])
2869

    
2870
    # changes to the hypervisor list
2871
    if self.op.enabled_hypervisors is not None:
2872
      self.hv_list = self.op.enabled_hypervisors
2873
      for hv in self.hv_list:
2874
        # if the hypervisor doesn't already exist in the cluster
2875
        # hvparams, we initialize it to empty, and then (in both
2876
        # cases) we make sure to fill the defaults, as we might not
2877
        # have a complete defaults list if the hypervisor wasn't
2878
        # enabled before
2879
        if hv not in new_hvp:
2880
          new_hvp[hv] = {}
2881
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2882
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2883
    else:
2884
      self.hv_list = cluster.enabled_hypervisors
2885

    
2886
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2887
      # either the enabled list has changed, or the parameters have, validate
2888
      for hv_name, hv_params in self.new_hvparams.items():
2889
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2890
            (self.op.enabled_hypervisors and
2891
             hv_name in self.op.enabled_hypervisors)):
2892
          # either this is a new hypervisor, or its parameters have changed
2893
          hv_class = hypervisor.GetHypervisor(hv_name)
2894
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2895
          hv_class.CheckParameterSyntax(hv_params)
2896
          _CheckHVParams(self, node_list, hv_name, hv_params)
2897

    
2898
    if self.op.os_hvp:
2899
      # no need to check any newly-enabled hypervisors, since the
2900
      # defaults have already been checked in the above code-block
2901
      for os_name, os_hvp in self.new_os_hvp.items():
2902
        for hv_name, hv_params in os_hvp.items():
2903
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2904
          # we need to fill in the new os_hvp on top of the actual hv_p
2905
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2906
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2907
          hv_class = hypervisor.GetHypervisor(hv_name)
2908
          hv_class.CheckParameterSyntax(new_osp)
2909
          _CheckHVParams(self, node_list, hv_name, new_osp)
2910

    
2911
    if self.op.default_iallocator:
2912
      alloc_script = utils.FindFile(self.op.default_iallocator,
2913
                                    constants.IALLOCATOR_SEARCH_PATH,
2914
                                    os.path.isfile)
2915
      if alloc_script is None:
2916
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2917
                                   " specified" % self.op.default_iallocator,
2918
                                   errors.ECODE_INVAL)
2919

    
2920
  def Exec(self, feedback_fn):
2921
    """Change the parameters of the cluster.
2922

2923
    """
2924
    if self.op.vg_name is not None:
2925
      new_volume = self.op.vg_name
2926
      if not new_volume:
2927
        new_volume = None
2928
      if new_volume != self.cfg.GetVGName():
2929
        self.cfg.SetVGName(new_volume)
2930
      else:
2931
        feedback_fn("Cluster LVM configuration already in desired"
2932
                    " state, not changing")
2933
    if self.op.drbd_helper is not None:
2934
      new_helper = self.op.drbd_helper
2935
      if not new_helper:
2936
        new_helper = None
2937
      if new_helper != self.cfg.GetDRBDHelper():
2938
        self.cfg.SetDRBDHelper(new_helper)
2939
      else:
2940
        feedback_fn("Cluster DRBD helper already in desired state,"
2941
                    " not changing")
2942
    if self.op.hvparams:
2943
      self.cluster.hvparams = self.new_hvparams
2944
    if self.op.os_hvp:
2945
      self.cluster.os_hvp = self.new_os_hvp
2946
    if self.op.enabled_hypervisors is not None:
2947
      self.cluster.hvparams = self.new_hvparams
2948
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2949
    if self.op.beparams:
2950
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2951
    if self.op.nicparams:
2952
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2953
    if self.op.osparams:
2954
      self.cluster.osparams = self.new_osp
2955
    if self.op.ndparams:
2956
      self.cluster.ndparams = self.new_ndparams
2957

    
2958
    if self.op.candidate_pool_size is not None:
2959
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2960
      # we need to update the pool size here, otherwise the save will fail
2961
      _AdjustCandidatePool(self, [])
2962

    
2963
    if self.op.maintain_node_health is not None:
2964
      self.cluster.maintain_node_health = self.op.maintain_node_health
2965

    
2966
    if self.op.prealloc_wipe_disks is not None:
2967
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2968

    
2969
    if self.op.add_uids is not None:
2970
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2971

    
2972
    if self.op.remove_uids is not None:
2973
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2974

    
2975
    if self.op.uid_pool is not None:
2976
      self.cluster.uid_pool = self.op.uid_pool
2977

    
2978
    if self.op.default_iallocator is not None:
2979
      self.cluster.default_iallocator = self.op.default_iallocator
2980

    
2981
    if self.op.reserved_lvs is not None:
2982
      self.cluster.reserved_lvs = self.op.reserved_lvs
2983

    
2984
    def helper_os(aname, mods, desc):
2985
      desc += " OS list"
2986
      lst = getattr(self.cluster, aname)
2987
      for key, val in mods:
2988
        if key == constants.DDM_ADD:
2989
          if val in lst:
2990
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2991
          else:
2992
            lst.append(val)
2993
        elif key == constants.DDM_REMOVE:
2994
          if val in lst:
2995
            lst.remove(val)
2996
          else:
2997
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
2998
        else:
2999
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3000

    
3001
    if self.op.hidden_os:
3002
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3003

    
3004
    if self.op.blacklisted_os:
3005
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3006

    
3007
    if self.op.master_netdev:
3008
      master = self.cfg.GetMasterNode()
3009
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3010
                  self.cluster.master_netdev)
3011
      result = self.rpc.call_node_stop_master(master, False)
3012
      result.Raise("Could not disable the master ip")
3013
      feedback_fn("Changing master_netdev from %s to %s" %
3014
                  (self.cluster.master_netdev, self.op.master_netdev))
3015
      self.cluster.master_netdev = self.op.master_netdev
3016

    
3017
    self.cfg.Update(self.cluster, feedback_fn)
3018

    
3019
    if self.op.master_netdev:
3020
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3021
                  self.op.master_netdev)
3022
      result = self.rpc.call_node_start_master(master, False, False)
3023
      if result.fail_msg:
3024
        self.LogWarning("Could not re-enable the master ip on"
3025
                        " the master, please restart manually: %s",
3026
                        result.fail_msg)
3027

    
3028

    
3029
def _UploadHelper(lu, nodes, fname):
3030
  """Helper for uploading a file and showing warnings.
3031

3032
  """
3033
  if os.path.exists(fname):
3034
    result = lu.rpc.call_upload_file(nodes, fname)
3035
    for to_node, to_result in result.items():
3036
      msg = to_result.fail_msg
3037
      if msg:
3038
        msg = ("Copy of file %s to node %s failed: %s" %
3039
               (fname, to_node, msg))
3040
        lu.proc.LogWarning(msg)
3041

    
3042

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

3046
  ConfigWriter takes care of distributing the config and ssconf files, but
3047
  there are more files which should be distributed to all nodes. This function
3048
  makes sure those are copied.
3049

3050
  @param lu: calling logical unit
3051
  @param additional_nodes: list of nodes not in the config to distribute to
3052
  @type additional_vm: boolean
3053
  @param additional_vm: whether the additional nodes are vm-capable or not
3054

3055
  """
3056
  # 1. Gather target nodes
3057
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3058
  dist_nodes = lu.cfg.GetOnlineNodeList()
3059
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
3060
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
3061
  if additional_nodes is not None:
3062
    dist_nodes.extend(additional_nodes)
3063
    if additional_vm:
3064
      vm_nodes.extend(additional_nodes)
3065
  if myself.name in dist_nodes:
3066
    dist_nodes.remove(myself.name)
3067
  if myself.name in vm_nodes:
3068
    vm_nodes.remove(myself.name)
3069

    
3070
  # 2. Gather files to distribute
3071
  dist_files = set([constants.ETC_HOSTS,
3072
                    constants.SSH_KNOWN_HOSTS_FILE,
3073
                    constants.RAPI_CERT_FILE,
3074
                    constants.RAPI_USERS_FILE,
3075
                    constants.CONFD_HMAC_KEY,
3076
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3077
                   ])
3078

    
3079
  vm_files = set()
3080
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3081
  for hv_name in enabled_hypervisors:
3082
    hv_class = hypervisor.GetHypervisor(hv_name)
3083
    vm_files.update(hv_class.GetAncillaryFiles())
3084

    
3085
  # 3. Perform the files upload
3086
  for fname in dist_files:
3087
    _UploadHelper(lu, dist_nodes, fname)
3088
  for fname in vm_files:
3089
    _UploadHelper(lu, vm_nodes, fname)
3090

    
3091

    
3092
class LUClusterRedistConf(NoHooksLU):
3093
  """Force the redistribution of cluster configuration.
3094

3095
  This is a very simple LU.
3096

3097
  """
3098
  REQ_BGL = False
3099

    
3100
  def ExpandNames(self):
3101
    self.needed_locks = {
3102
      locking.LEVEL_NODE: locking.ALL_SET,
3103
    }
3104
    self.share_locks[locking.LEVEL_NODE] = 1
3105

    
3106
  def Exec(self, feedback_fn):
3107
    """Redistribute the configuration.
3108

3109
    """
3110
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3111
    _RedistributeAncillaryFiles(self)
3112

    
3113

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

3117
  """
3118
  if not instance.disks or disks is not None and not disks:
3119
    return True
3120

    
3121
  disks = _ExpandCheckDisks(instance, disks)
3122

    
3123
  if not oneshot:
3124
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3125

    
3126
  node = instance.primary_node
3127

    
3128
  for dev in disks:
3129
    lu.cfg.SetDiskID(dev, node)
3130

    
3131
  # TODO: Convert to utils.Retry
3132

    
3133
  retries = 0
3134
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3135
  while True:
3136
    max_time = 0
3137
    done = True
3138
    cumul_degraded = False
3139
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3140
    msg = rstats.fail_msg
3141
    if msg:
3142
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3143
      retries += 1
3144
      if retries >= 10:
3145
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3146
                                 " aborting." % node)
3147
      time.sleep(6)
3148
      continue
3149
    rstats = rstats.payload
3150
    retries = 0
3151
    for i, mstat in enumerate(rstats):
3152
      if mstat is None:
3153
        lu.LogWarning("Can't compute data for node %s/%s",
3154
                           node, disks[i].iv_name)
3155
        continue
3156

    
3157
      cumul_degraded = (cumul_degraded or
3158
                        (mstat.is_degraded and mstat.sync_percent is None))
3159
      if mstat.sync_percent is not None:
3160
        done = False
3161
        if mstat.estimated_time is not None:
3162
          rem_time = ("%s remaining (estimated)" %
3163
                      utils.FormatSeconds(mstat.estimated_time))
3164
          max_time = mstat.estimated_time
3165
        else:
3166
          rem_time = "no time estimate"
3167
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3168
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3169

    
3170
    # if we're done but degraded, let's do a few small retries, to
3171
    # make sure we see a stable and not transient situation; therefore
3172
    # we force restart of the loop
3173
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3174
      logging.info("Degraded disks found, %d retries left", degr_retries)
3175
      degr_retries -= 1
3176
      time.sleep(1)
3177
      continue
3178

    
3179
    if done or oneshot:
3180
      break
3181

    
3182
    time.sleep(min(60, max_time))
3183

    
3184
  if done:
3185
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3186
  return not cumul_degraded
3187

    
3188

    
3189
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3190
  """Check that mirrors are not degraded.
3191

3192
  The ldisk parameter, if True, will change the test from the
3193
  is_degraded attribute (which represents overall non-ok status for
3194
  the device(s)) to the ldisk (representing the local storage status).
3195

3196
  """
3197
  lu.cfg.SetDiskID(dev, node)
3198

    
3199
  result = True
3200

    
3201
  if on_primary or dev.AssembleOnSecondary():
3202
    rstats = lu.rpc.call_blockdev_find(node, dev)
3203
    msg = rstats.fail_msg
3204
    if msg:
3205
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3206
      result = False
3207
    elif not rstats.payload:
3208
      lu.LogWarning("Can't find disk on node %s", node)
3209
      result = False
3210
    else:
3211
      if ldisk:
3212
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3213
      else:
3214
        result = result and not rstats.payload.is_degraded
3215

    
3216
  if dev.children:
3217
    for child in dev.children:
3218
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3219

    
3220
  return result
3221

    
3222

    
3223
class LUOobCommand(NoHooksLU):
3224
  """Logical unit for OOB handling.
3225

3226
  """
3227
  REG_BGL = False
3228
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3229

    
3230
  def CheckPrereq(self):
3231
    """Check prerequisites.
3232

3233
    This checks:
3234
     - the node exists in the configuration
3235
     - OOB is supported
3236

3237
    Any errors are signaled by raising errors.OpPrereqError.
3238

3239
    """
3240
    self.nodes = []
3241
    self.master_node = self.cfg.GetMasterNode()
3242

    
3243
    assert self.op.power_delay >= 0.0
3244

    
3245
    if self.op.node_names:
3246
      if self.op.command in self._SKIP_MASTER:
3247
        if self.master_node in self.op.node_names:
3248
          master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3249
          master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3250

    
3251
          if master_oob_handler:
3252
            additional_text = ("Run '%s %s %s' if you want to operate on the"
3253
                               " master regardless") % (master_oob_handler,
3254
                                                        self.op.command,
3255
                                                        self.master_node)
3256
          else:
3257
            additional_text = "The master node does not support out-of-band"
3258

    
3259
          raise errors.OpPrereqError(("Operating on the master node %s is not"
3260
                                      " allowed for %s\n%s") %
3261
                                     (self.master_node, self.op.command,
3262
                                      additional_text), errors.ECODE_INVAL)
3263
    else:
3264
      self.op.node_names = self.cfg.GetNodeList()
3265
      if self.op.command in self._SKIP_MASTER:
3266
        self.op.node_names.remove(self.master_node)
3267

    
3268
    if self.op.command in self._SKIP_MASTER:
3269
      assert self.master_node not in self.op.node_names
3270

    
3271
    for node_name in self.op.node_names:
3272
      node = self.cfg.GetNodeInfo(node_name)
3273

    
3274
      if node is None:
3275
        raise errors.OpPrereqError("Node %s not found" % node_name,
3276
                                   errors.ECODE_NOENT)
3277
      else:
3278
        self.nodes.append(node)
3279

    
3280
      if (not self.op.ignore_status and
3281
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3282
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3283
                                    " not marked offline") % node_name,
3284
                                   errors.ECODE_STATE)
3285

    
3286
  def ExpandNames(self):
3287
    """Gather locks we need.
3288

3289
    """
3290
    if self.op.node_names:
3291
      self.op.node_names = [_ExpandNodeName(self.cfg, name)
3292
                            for name in self.op.node_names]
3293
      lock_names = self.op.node_names
3294
    else:
3295
      lock_names = locking.ALL_SET
3296

    
3297
    self.needed_locks = {
3298
      locking.LEVEL_NODE: lock_names,
3299
      }
3300

    
3301
  def Exec(self, feedback_fn):
3302
    """Execute OOB and return result if we expect any.
3303

3304
    """
3305
    master_node = self.master_node
3306
    ret = []
3307

    
3308
    for idx, node in enumerate(self.nodes):
3309
      node_entry = [(constants.RS_NORMAL, node.name)]
3310
      ret.append(node_entry)
3311

    
3312
      oob_program = _SupportsOob(self.cfg, node)
3313

    
3314
      if not oob_program:
3315
        node_entry.append((constants.RS_UNAVAIL, None))
3316
        continue
3317

    
3318
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3319
                   self.op.command, oob_program, node.name)
3320
      result = self.rpc.call_run_oob(master_node, oob_program,
3321
                                     self.op.command, node.name,
3322
                                     self.op.timeout)
3323

    
3324
      if result.fail_msg:
3325
        self.LogWarning("On node '%s' out-of-band RPC failed with: %s",
3326
                        node.name, result.fail_msg)
3327
        node_entry.append((constants.RS_NODATA, None))
3328
      else:
3329
        try:
3330
          self._CheckPayload(result)
3331
        except errors.OpExecError, err:
3332
          self.LogWarning("The payload returned by '%s' is not valid: %s",
3333
                          node.name, err)
3334
          node_entry.append((constants.RS_NODATA, None))
3335
        else:
3336
          if self.op.command == constants.OOB_HEALTH:
3337
            # For health we should log important events
3338
            for item, status in result.payload:
3339
              if status in [constants.OOB_STATUS_WARNING,
3340
                            constants.OOB_STATUS_CRITICAL]:
3341
                self.LogWarning("On node '%s' item '%s' has status '%s'",
3342
                                node.name, item, status)
3343

    
3344
          if self.op.command == constants.OOB_POWER_ON:
3345
            node.powered = True
3346
          elif self.op.command == constants.OOB_POWER_OFF:
3347
            node.powered = False
3348
          elif self.op.command == constants.OOB_POWER_STATUS:
3349
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3350
            if powered != node.powered:
3351
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3352
                               " match actual power state (%s)"), node.powered,
3353
                              node.name, powered)
3354

    
3355
          # For configuration changing commands we should update the node
3356
          if self.op.command in (constants.OOB_POWER_ON,
3357
                                 constants.OOB_POWER_OFF):
3358
            self.cfg.Update(node, feedback_fn)
3359

    
3360
          node_entry.append((constants.RS_NORMAL, result.payload))
3361

    
3362
          if (self.op.command == constants.OOB_POWER_ON and
3363
              idx < len(self.nodes) - 1):
3364
            time.sleep(self.op.power_delay)
3365

    
3366
    return ret
3367

    
3368
  def _CheckPayload(self, result):
3369
    """Checks if the payload is valid.
3370

3371
    @param result: RPC result
3372
    @raises errors.OpExecError: If payload is not valid
3373

3374
    """
3375
    errs = []
3376
    if self.op.command == constants.OOB_HEALTH:
3377
      if not isinstance(result.payload, list):
3378
        errs.append("command 'health' is expected to return a list but got %s" %
3379
                    type(result.payload))
3380
      else:
3381
        for item, status in result.payload:
3382
          if status not in constants.OOB_STATUSES:
3383
            errs.append("health item '%s' has invalid status '%s'" %
3384
                        (item, status))
3385

    
3386
    if self.op.command == constants.OOB_POWER_STATUS:
3387
      if not isinstance(result.payload, dict):
3388
        errs.append("power-status is expected to return a dict but got %s" %
3389
                    type(result.payload))
3390

    
3391
    if self.op.command in [
3392
        constants.OOB_POWER_ON,
3393
        constants.OOB_POWER_OFF,
3394
        constants.OOB_POWER_CYCLE,
3395
        ]:
3396
      if result.payload is not None:
3397
        errs.append("%s is expected to not return payload but got '%s'" %
3398
                    (self.op.command, result.payload))
3399

    
3400
    if errs:
3401
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3402
                               utils.CommaJoin(errs))
3403

    
3404
class _OsQuery(_QueryBase):
3405
  FIELDS = query.OS_FIELDS
3406

    
3407
  def ExpandNames(self, lu):
3408
    # Lock all nodes in shared mode
3409
    # Temporary removal of locks, should be reverted later
3410
    # TODO: reintroduce locks when they are lighter-weight
3411
    lu.needed_locks = {}
3412
    #self.share_locks[locking.LEVEL_NODE] = 1
3413
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3414

    
3415
    # The following variables interact with _QueryBase._GetNames
3416
    if self.names:
3417
      self.wanted = self.names
3418
    else:
3419
      self.wanted = locking.ALL_SET
3420

    
3421
    self.do_locking = self.use_locking
3422

    
3423
  def DeclareLocks(self, lu, level):
3424
    pass
3425

    
3426
  @staticmethod
3427
  def _DiagnoseByOS(rlist):
3428
    """Remaps a per-node return list into an a per-os per-node dictionary
3429

3430
    @param rlist: a map with node names as keys and OS objects as values
3431

3432
    @rtype: dict
3433
    @return: a dictionary with osnames as keys and as value another
3434
        map, with nodes as keys and tuples of (path, status, diagnose,
3435
        variants, parameters, api_versions) as values, eg::
3436

3437
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3438
                                     (/srv/..., False, "invalid api")],
3439
                           "node2": [(/srv/..., True, "", [], [])]}
3440
          }
3441

3442
    """
3443
    all_os = {}
3444
    # we build here the list of nodes that didn't fail the RPC (at RPC
3445
    # level), so that nodes with a non-responding node daemon don't
3446
    # make all OSes invalid
3447
    good_nodes = [node_name for node_name in rlist
3448
                  if not rlist[node_name].fail_msg]
3449
    for node_name, nr in rlist.items():
3450
      if nr.fail_msg or not nr.payload:
3451
        continue
3452
      for (name, path, status, diagnose, variants,
3453
           params, api_versions) in nr.payload:
3454
        if name not in all_os:
3455
          # build a list of nodes for this os containing empty lists
3456
          # for each node in node_list
3457
          all_os[name] = {}
3458
          for nname in good_nodes:
3459
            all_os[name][nname] = []
3460
        # convert params from [name, help] to (name, help)
3461
        params = [tuple(v) for v in params]
3462
        all_os[name][node_name].append((path, status, diagnose,
3463
                                        variants, params, api_versions))
3464
    return all_os
3465

    
3466
  def _GetQueryData(self, lu):
3467
    """Computes the list of nodes and their attributes.
3468

3469
    """
3470
    # Locking is not used
3471
    assert not (lu.acquired_locks or self.do_locking or self.use_locking)
3472

    
3473
    valid_nodes = [node.name
3474
                   for node in lu.cfg.GetAllNodesInfo().values()
3475
                   if not node.offline and node.vm_capable]
3476
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3477
    cluster = lu.cfg.GetClusterInfo()
3478

    
3479
    data = {}
3480

    
3481
    for (os_name, os_data) in pol.items():
3482
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3483
                          hidden=(os_name in cluster.hidden_os),
3484
                          blacklisted=(os_name in cluster.blacklisted_os))
3485

    
3486
      variants = set()
3487
      parameters = set()
3488
      api_versions = set()
3489

    
3490
      for idx, osl in enumerate(os_data.values()):
3491
        info.valid = bool(info.valid and osl and osl[0][1])
3492
        if not info.valid:
3493
          break
3494

    
3495
        (node_variants, node_params, node_api) = osl[0][3:6]
3496
        if idx == 0:
3497
          # First entry
3498
          variants.update(node_variants)
3499
          parameters.update(node_params)
3500
          api_versions.update(node_api)
3501
        else:
3502
          # Filter out inconsistent values
3503
          variants.intersection_update(node_variants)
3504
          parameters.intersection_update(node_params)
3505
          api_versions.intersection_update(node_api)
3506

    
3507
      info.variants = list(variants)
3508
      info.parameters = list(parameters)
3509
      info.api_versions = list(api_versions)
3510

    
3511
      data[os_name] = info
3512

    
3513
    # Prepare data in requested order
3514
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3515
            if name in data]
3516

    
3517

    
3518
class LUOsDiagnose(NoHooksLU):
3519
  """Logical unit for OS diagnose/query.
3520

3521
  """
3522
  REQ_BGL = False
3523

    
3524
  @staticmethod
3525
  def _BuildFilter(fields, names):
3526
    """Builds a filter for querying OSes.
3527

3528
    """
3529
    name_filter = qlang.MakeSimpleFilter("name", names)
3530

    
3531
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
3532
    # respective field is not requested
3533
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
3534
                     for fname in ["hidden", "blacklisted"]
3535
                     if fname not in fields]
3536
    if "valid" not in fields:
3537
      status_filter.append([qlang.OP_TRUE, "valid"])
3538

    
3539
    if status_filter:
3540
      status_filter.insert(0, qlang.OP_AND)
3541
    else:
3542
      status_filter = None
3543

    
3544
    if name_filter and status_filter:
3545
      return [qlang.OP_AND, name_filter, status_filter]
3546
    elif name_filter:
3547
      return name_filter
3548
    else:
3549
      return status_filter
3550

    
3551
  def CheckArguments(self):
3552
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
3553
                       self.op.output_fields, False)
3554

    
3555
  def ExpandNames(self):
3556
    self.oq.ExpandNames(self)
3557

    
3558
  def Exec(self, feedback_fn):
3559
    return self.oq.OldStyleQuery(self)
3560

    
3561

    
3562
class LUNodeRemove(LogicalUnit):
3563
  """Logical unit for removing a node.
3564

3565
  """
3566
  HPATH = "node-remove"
3567
  HTYPE = constants.HTYPE_NODE
3568

    
3569
  def BuildHooksEnv(self):
3570
    """Build hooks env.
3571

3572
    This doesn't run on the target node in the pre phase as a failed
3573
    node would then be impossible to remove.
3574

3575
    """
3576
    env = {
3577
      "OP_TARGET": self.op.node_name,
3578
      "NODE_NAME": self.op.node_name,
3579
      }
3580
    all_nodes = self.cfg.GetNodeList()
3581
    try:
3582
      all_nodes.remove(self.op.node_name)
3583
    except ValueError:
3584
      logging.warning("Node %s which is about to be removed not found"
3585
                      " in the all nodes list", self.op.node_name)
3586
    return env, all_nodes, all_nodes
3587

    
3588
  def CheckPrereq(self):
3589
    """Check prerequisites.
3590

3591
    This checks:
3592
     - the node exists in the configuration
3593
     - it does not have primary or secondary instances
3594
     - it's not the master
3595

3596
    Any errors are signaled by raising errors.OpPrereqError.
3597

3598
    """
3599
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3600
    node = self.cfg.GetNodeInfo(self.op.node_name)
3601
    assert node is not None
3602

    
3603
    instance_list = self.cfg.GetInstanceList()
3604

    
3605
    masternode = self.cfg.GetMasterNode()
3606
    if node.name == masternode:
3607
      raise errors.OpPrereqError("Node is the master node,"
3608
                                 " you need to failover first.",
3609
                                 errors.ECODE_INVAL)
3610

    
3611
    for instance_name in instance_list:
3612
      instance = self.cfg.GetInstanceInfo(instance_name)
3613
      if node.name in instance.all_nodes:
3614
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3615
                                   " please remove first." % instance_name,
3616
                                   errors.ECODE_INVAL)
3617
    self.op.node_name = node.name
3618
    self.node = node
3619

    
3620
  def Exec(self, feedback_fn):
3621
    """Removes the node from the cluster.
3622

3623
    """
3624
    node = self.node
3625
    logging.info("Stopping the node daemon and removing configs from node %s",
3626
                 node.name)
3627

    
3628
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3629

    
3630
    # Promote nodes to master candidate as needed
3631
    _AdjustCandidatePool(self, exceptions=[node.name])
3632
    self.context.RemoveNode(node.name)
3633

    
3634
    # Run post hooks on the node before it's removed
3635
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3636
    try:
3637
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3638
    except:
3639
      # pylint: disable-msg=W0702
3640
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3641

    
3642
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3643
    msg = result.fail_msg
3644
    if msg:
3645
      self.LogWarning("Errors encountered on the remote node while leaving"
3646
                      " the cluster: %s", msg)
3647

    
3648
    # Remove node from our /etc/hosts
3649
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3650
      master_node = self.cfg.GetMasterNode()
3651
      result = self.rpc.call_etc_hosts_modify(master_node,
3652
                                              constants.ETC_HOSTS_REMOVE,
3653
                                              node.name, None)
3654
      result.Raise("Can't update hosts file with new host data")
3655
      _RedistributeAncillaryFiles(self)
3656

    
3657

    
3658
class _NodeQuery(_QueryBase):
3659
  FIELDS = query.NODE_FIELDS
3660

    
3661
  def ExpandNames(self, lu):
3662
    lu.needed_locks = {}
3663
    lu.share_locks[locking.LEVEL_NODE] = 1
3664

    
3665
    if self.names:
3666
      self.wanted = _GetWantedNodes(lu, self.names)
3667
    else:
3668
      self.wanted = locking.ALL_SET
3669

    
3670
    self.do_locking = (self.use_locking and
3671
                       query.NQ_LIVE in self.requested_data)
3672

    
3673
    if self.do_locking:
3674
      # if we don't request only static fields, we need to lock the nodes
3675
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3676

    
3677
  def DeclareLocks(self, lu, level):
3678
    pass
3679

    
3680
  def _GetQueryData(self, lu):
3681
    """Computes the list of nodes and their attributes.
3682

3683
    """
3684
    all_info = lu.cfg.GetAllNodesInfo()
3685

    
3686
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3687

    
3688
    # Gather data as requested
3689
    if query.NQ_LIVE in self.requested_data:
3690
      # filter out non-vm_capable nodes
3691
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3692

    
3693
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3694
                                        lu.cfg.GetHypervisorType())
3695
      live_data = dict((name, nresult.payload)
3696
                       for (name, nresult) in node_data.items()
3697
                       if not nresult.fail_msg and nresult.payload)
3698
    else:
3699
      live_data = None
3700

    
3701
    if query.NQ_INST in self.requested_data:
3702
      node_to_primary = dict([(name, set()) for name in nodenames])
3703
      node_to_secondary = dict([(name, set()) for name in nodenames])
3704

    
3705
      inst_data = lu.cfg.GetAllInstancesInfo()
3706

    
3707
      for inst in inst_data.values():
3708
        if inst.primary_node in node_to_primary:
3709
          node_to_primary[inst.primary_node].add(inst.name)
3710
        for secnode in inst.secondary_nodes:
3711
          if secnode in node_to_secondary:
3712
            node_to_secondary[secnode].add(inst.name)
3713
    else:
3714
      node_to_primary = None
3715
      node_to_secondary = None
3716

    
3717
    if query.NQ_OOB in self.requested_data:
3718
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3719
                         for name, node in all_info.iteritems())
3720
    else:
3721
      oob_support = None
3722

    
3723
    if query.NQ_GROUP in self.requested_data:
3724
      groups = lu.cfg.GetAllNodeGroupsInfo()
3725
    else:
3726
      groups = {}
3727

    
3728
    return query.NodeQueryData([all_info[name] for name in nodenames],
3729
                               live_data, lu.cfg.GetMasterNode(),
3730
                               node_to_primary, node_to_secondary, groups,
3731
                               oob_support, lu.cfg.GetClusterInfo())
3732

    
3733

    
3734
class LUNodeQuery(NoHooksLU):
3735
  """Logical unit for querying nodes.
3736

3737
  """
3738
  # pylint: disable-msg=W0142
3739
  REQ_BGL = False
3740

    
3741
  def CheckArguments(self):
3742
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
3743
                         self.op.output_fields, self.op.use_locking)
3744

    
3745
  def ExpandNames(self):
3746
    self.nq.ExpandNames(self)
3747

    
3748
  def Exec(self, feedback_fn):
3749
    return self.nq.OldStyleQuery(self)
3750

    
3751

    
3752
class LUNodeQueryvols(NoHooksLU):
3753
  """Logical unit for getting volumes on node(s).
3754

3755
  """
3756
  REQ_BGL = False
3757
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3758
  _FIELDS_STATIC = utils.FieldSet("node")
3759

    
3760
  def CheckArguments(self):
3761
    _CheckOutputFields(static=self._FIELDS_STATIC,
3762
                       dynamic=self._FIELDS_DYNAMIC,
3763
                       selected=self.op.output_fields)
3764

    
3765
  def ExpandNames(self):
3766
    self.needed_locks = {}
3767
    self.share_locks[locking.LEVEL_NODE] = 1
3768
    if not self.op.nodes:
3769
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3770
    else:
3771
      self.needed_locks[locking.LEVEL_NODE] = \
3772
        _GetWantedNodes(self, self.op.nodes)
3773

    
3774
  def Exec(self, feedback_fn):
3775
    """Computes the list of nodes and their attributes.
3776

3777
    """
3778
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3779
    volumes = self.rpc.call_node_volumes(nodenames)
3780

    
3781
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3782
             in self.cfg.GetInstanceList()]
3783

    
3784
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3785

    
3786
    output = []
3787
    for node in nodenames:
3788
      nresult = volumes[node]
3789
      if nresult.offline:
3790
        continue
3791
      msg = nresult.fail_msg
3792
      if msg:
3793
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3794
        continue
3795

    
3796
      node_vols = nresult.payload[:]
3797
      node_vols.sort(key=lambda vol: vol['dev'])
3798

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

    
3825
        output.append(node_output)
3826

    
3827
    return output
3828

    
3829

    
3830
class LUNodeQueryStorage(NoHooksLU):
3831
  """Logical unit for getting information on storage units on node(s).
3832

3833
  """
3834
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3835
  REQ_BGL = False
3836

    
3837
  def CheckArguments(self):
3838
    _CheckOutputFields(static=self._FIELDS_STATIC,
3839
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3840
                       selected=self.op.output_fields)
3841

    
3842
  def ExpandNames(self):
3843
    self.needed_locks = {}
3844
    self.share_locks[locking.LEVEL_NODE] = 1
3845

    
3846
    if self.op.nodes:
3847
      self.needed_locks[locking.LEVEL_NODE] = \
3848
        _GetWantedNodes(self, self.op.nodes)
3849
    else:
3850
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3851

    
3852
  def Exec(self, feedback_fn):
3853
    """Computes the list of nodes and their attributes.
3854

3855
    """
3856
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3857

    
3858
    # Always get name to sort by
3859
    if constants.SF_NAME in self.op.output_fields:
3860
      fields = self.op.output_fields[:]
3861
    else:
3862
      fields = [constants.SF_NAME] + self.op.output_fields
3863

    
3864
    # Never ask for node or type as it's only known to the LU
3865
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3866
      while extra in fields:
3867
        fields.remove(extra)
3868

    
3869
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3870
    name_idx = field_idx[constants.SF_NAME]
3871

    
3872
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3873
    data = self.rpc.call_storage_list(self.nodes,
3874
                                      self.op.storage_type, st_args,
3875
                                      self.op.name, fields)
3876

    
3877
    result = []
3878

    
3879
    for node in utils.NiceSort(self.nodes):
3880
      nresult = data[node]
3881
      if nresult.offline:
3882
        continue
3883

    
3884
      msg = nresult.fail_msg
3885
      if msg:
3886
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3887
        continue
3888

    
3889
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3890

    
3891
      for name in utils.NiceSort(rows.keys()):
3892
        row = rows[name]
3893

    
3894
        out = []
3895

    
3896
        for field in self.op.output_fields:
3897
          if field == constants.SF_NODE:
3898
            val = node
3899
          elif field == constants.SF_TYPE:
3900
            val = self.op.storage_type
3901
          elif field in field_idx:
3902
            val = row[field_idx[field]]
3903
          else:
3904
            raise errors.ParameterError(field)
3905

    
3906
          out.append(val)
3907

    
3908
        result.append(out)
3909

    
3910
    return result
3911

    
3912

    
3913
class _InstanceQuery(_QueryBase):
3914
  FIELDS = query.INSTANCE_FIELDS
3915

    
3916
  def ExpandNames(self, lu):
3917
    lu.needed_locks = {}
3918
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
3919
    lu.share_locks[locking.LEVEL_NODE] = 1
3920

    
3921
    if self.names:
3922
      self.wanted = _GetWantedInstances(lu, self.names)
3923
    else:
3924
      self.wanted = locking.ALL_SET
3925

    
3926
    self.do_locking = (self.use_locking and
3927
                       query.IQ_LIVE in self.requested_data)
3928
    if self.do_locking:
3929
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3930
      lu.needed_locks[locking.LEVEL_NODE] = []
3931
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3932

    
3933
  def DeclareLocks(self, lu, level):
3934
    if level == locking.LEVEL_NODE and self.do_locking:
3935
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3936

    
3937
  def _GetQueryData(self, lu):
3938
    """Computes the list of instances and their attributes.
3939

3940
    """
3941
    cluster = lu.cfg.GetClusterInfo()
3942
    all_info = lu.cfg.GetAllInstancesInfo()
3943

    
3944
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3945

    
3946
    instance_list = [all_info[name] for name in instance_names]
3947
    nodes = frozenset(itertools.chain(*(inst.all_nodes
3948
                                        for inst in instance_list)))
3949
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3950
    bad_nodes = []
3951
    offline_nodes = []
3952
    wrongnode_inst = set()
3953

    
3954
    # Gather data as requested
3955
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
3956
      live_data = {}
3957
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
3958
      for name in nodes:
3959
        result = node_data[name]
3960
        if result.offline:
3961
          # offline nodes will be in both lists
3962
          assert result.fail_msg
3963
          offline_nodes.append(name)
3964
        if result.fail_msg:
3965
          bad_nodes.append(name)
3966
        elif result.payload:
3967
          for inst in result.payload:
3968
            if all_info[inst].primary_node == name:
3969
              live_data.update(result.payload)
3970
            else:
3971
              wrongnode_inst.add(inst)
3972
        # else no instance is alive
3973
    else:
3974
      live_data = {}
3975

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

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

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

    
4001

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

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

    
4009
  def CheckArguments(self):
4010
    qcls = _GetQueryImplementation(self.op.what)
4011

    
4012
    self.impl = qcls(self.op.filter, 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 query.QueryFields(self.qcls.FIELDS, 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
    if self.op.readd and self.op.group:
4098
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4099
                                 " being readded", errors.ECODE_INVAL)
4100

    
4101
  def BuildHooksEnv(self):
4102
    """Build hooks env.
4103

4104
    This will run on all nodes before, and on all nodes + the new node after.
4105

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

    
4119
  def CheckPrereq(self):
4120
    """Check prerequisites.
4121

4122
    This checks:
4123
     - the new node is not already in the config
4124
     - it is resolvable
4125
     - its parameters (single/dual homed) matches the cluster
4126

4127
    Any errors are signaled by raising errors.OpPrereqError.
4128

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

    
4141
    secondary_ip = self.op.secondary_ip
4142
    if not netutils.IP4Address.IsValid(secondary_ip):
4143
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4144
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4145

    
4146
    node_list = cfg.GetNodeList()
4147
    if not self.op.readd and node in node_list:
4148
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4149
                                 node, errors.ECODE_EXISTS)
4150
    elif self.op.readd and node not in node_list:
4151
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4152
                                 errors.ECODE_NOENT)
4153

    
4154
    self.changed_primary_ip = False
4155

    
4156
    for existing_node_name in node_list:
4157
      existing_node = cfg.GetNodeInfo(existing_node_name)
4158

    
4159
      if self.op.readd and node == existing_node_name:
4160
        if existing_node.secondary_ip != secondary_ip:
4161
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4162
                                     " address configuration as before",
4163
                                     errors.ECODE_INVAL)
4164
        if existing_node.primary_ip != primary_ip:
4165
          self.changed_primary_ip = True
4166

    
4167
        continue
4168

    
4169
      if (existing_node.primary_ip == primary_ip or
4170
          existing_node.secondary_ip == primary_ip or
4171
          existing_node.primary_ip == secondary_ip or
4172
          existing_node.secondary_ip == secondary_ip):
4173
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4174
                                   " existing node %s" % existing_node.name,
4175
                                   errors.ECODE_NOTUNIQUE)
4176

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

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

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

    
4213
    # checks reachability
4214
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4215
      raise errors.OpPrereqError("Node not reachable by ping",
4216
                                 errors.ECODE_ENVIRON)
4217

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

    
4226
    if self.op.readd:
4227
      exceptions = [node]
4228
    else:
4229
      exceptions = []
4230

    
4231
    if self.op.master_capable:
4232
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4233
    else:
4234
      self.master_candidate = False
4235

    
4236
    if self.op.readd:
4237
      self.new_node = old_node
4238
    else:
4239
      node_group = cfg.LookupNodeGroup(self.op.group)
4240
      self.new_node = objects.Node(name=node,
4241
                                   primary_ip=primary_ip,
4242
                                   secondary_ip=secondary_ip,
4243
                                   master_candidate=self.master_candidate,
4244
                                   offline=False, drained=False,
4245
                                   group=node_group)
4246

    
4247
    if self.op.ndparams:
4248
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4249

    
4250
  def Exec(self, feedback_fn):
4251
    """Adds the new node to the cluster.
4252

4253
    """
4254
    new_node = self.new_node
4255
    node = new_node.name
4256

    
4257
    # We adding a new node so we assume it's powered
4258
    new_node.powered = True
4259

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

    
4272
    # copy the master/vm_capable flags
4273
    for attr in self._NFLAGS:
4274
      setattr(new_node, attr, getattr(self.op, attr))
4275

    
4276
    # notify the user about any possible mc promotion
4277
    if new_node.master_candidate:
4278
      self.LogInfo("Node will be a master candidate")
4279

    
4280
    if self.op.ndparams:
4281
      new_node.ndparams = self.op.ndparams
4282
    else:
4283
      new_node.ndparams = {}
4284

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

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

    
4305
    if new_node.secondary_ip != new_node.primary_ip:
4306
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4307
                               False)
4308

    
4309
    node_verify_list = [self.cfg.GetMasterNode()]
4310
    node_verify_param = {
4311
      constants.NV_NODELIST: [node],
4312
      # TODO: do a node-net-test as well?
4313
    }
4314

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

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

    
4344

    
4345
class LUNodeSetParams(LogicalUnit):
4346
  """Modifies the parameters of a node.
4347

4348
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4349
      to the node role (as _ROLE_*)
4350
  @cvar _R2F: a dictionary from node role to tuples of flags
4351
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4352

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

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

    
4380
    # Boolean value that tells us whether we might be demoting from MC
4381
    self.might_demote = (self.op.master_candidate == False or
4382
                         self.op.offline == True or
4383
                         self.op.drained == True or
4384
                         self.op.master_capable == False)
4385

    
4386
    if self.op.secondary_ip:
4387
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4388
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4389
                                   " address" % self.op.secondary_ip,
4390
                                   errors.ECODE_INVAL)
4391

    
4392
    self.lock_all = self.op.auto_promote and self.might_demote
4393
    self.lock_instances = self.op.secondary_ip is not None
4394

    
4395
  def ExpandNames(self):
4396
    if self.lock_all:
4397
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4398
    else:
4399
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4400

    
4401
    if self.lock_instances:
4402
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4403

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

    
4424
  def BuildHooksEnv(self):
4425
    """Build hooks env.
4426

4427
    This runs on the master node.
4428

4429
    """
4430
    env = {
4431
      "OP_TARGET": self.op.node_name,
4432
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4433
      "OFFLINE": str(self.op.offline),
4434
      "DRAINED": str(self.op.drained),
4435
      "MASTER_CAPABLE": str(self.op.master_capable),
4436
      "VM_CAPABLE": str(self.op.vm_capable),
4437
      }
4438
    nl = [self.cfg.GetMasterNode(),
4439
          self.op.node_name]
4440
    return env, nl, nl
4441

    
4442
  def CheckPrereq(self):
4443
    """Check prerequisites.
4444

4445
    This only checks the instance list against the existing names.
4446

4447
    """
4448
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4449

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

    
4459
    if self.op.master_candidate and not node.master_capable:
4460
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4461
                                 " it a master candidate" % node.name,
4462
                                 errors.ECODE_STATE)
4463

    
4464
    if self.op.vm_capable == False:
4465
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4466
      if ipri or isec:
4467
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4468
                                   " the vm_capable flag" % node.name,
4469
                                   errors.ECODE_STATE)
4470

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

    
4482
    self.old_flags = old_flags = (node.master_candidate,
4483
                                  node.drained, node.offline)
4484
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4485
    self.old_role = old_role = self._F2R[old_flags]
4486

    
4487
    # Check for ineffective changes
4488
    for attr in self._FLAGS:
4489
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4490
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4491
        setattr(self.op, attr, None)
4492

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

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

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

    
4515
    # If we're no longer master capable, we'll demote ourselves from MC
4516
    if self.op.master_capable == False and node.master_candidate:
4517
      self.LogInfo("Demoting from master candidate")
4518
      self.op.master_candidate = False
4519

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

    
4535
    self.new_role = new_role
4536

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

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

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

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

    
4579
    if self.op.ndparams:
4580
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4581
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4582
      self.new_ndparams = new_ndparams
4583

    
4584
  def Exec(self, feedback_fn):
4585
    """Modifies a node.
4586

4587
    """
4588
    node = self.node
4589
    old_role = self.old_role
4590
    new_role = self.new_role
4591

    
4592
    result = []
4593

    
4594
    if self.op.ndparams:
4595
      node.ndparams = self.new_ndparams
4596

    
4597
    if self.op.powered is not None:
4598
      node.powered = self.op.powered
4599

    
4600
    for attr in ["master_capable", "vm_capable"]:
4601
      val = getattr(self.op, attr)
4602
      if val is not None:
4603
        setattr(node, attr, val)
4604
        result.append((attr, str(val)))
4605

    
4606
    if new_role != old_role:
4607
      # Tell the node to demote itself, if no longer MC and not offline
4608
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4609
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4610
        if msg:
4611
          self.LogWarning("Node failed to demote itself: %s", msg)
4612

    
4613
      new_flags = self._R2F[new_role]
4614
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4615
        if of != nf:
4616
          result.append((desc, str(nf)))
4617
      (node.master_candidate, node.drained, node.offline) = new_flags
4618

    
4619
      # we locked all nodes, we adjust the CP before updating this node
4620
      if self.lock_all:
4621
        _AdjustCandidatePool(self, [node.name])
4622

    
4623
    if self.op.secondary_ip:
4624
      node.secondary_ip = self.op.secondary_ip
4625
      result.append(("secondary_ip", self.op.secondary_ip))
4626

    
4627
    # this will trigger configuration file update, if needed
4628
    self.cfg.Update(node, feedback_fn)
4629

    
4630
    # this will trigger job queue propagation or cleanup if the mc
4631
    # flag changed
4632
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4633
      self.context.ReaddNode(node)
4634

    
4635
    return result
4636

    
4637

    
4638
class LUNodePowercycle(NoHooksLU):
4639
  """Powercycles a node.
4640

4641
  """
4642
  REQ_BGL = False
4643

    
4644
  def CheckArguments(self):
4645
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4646
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4647
      raise errors.OpPrereqError("The node is the master and the force"
4648
                                 " parameter was not set",
4649
                                 errors.ECODE_INVAL)
4650

    
4651
  def ExpandNames(self):
4652
    """Locking for PowercycleNode.
4653

4654
    This is a last-resort option and shouldn't block on other
4655
    jobs. Therefore, we grab no locks.
4656

4657
    """
4658
    self.needed_locks = {}
4659

    
4660
  def Exec(self, feedback_fn):
4661
    """Reboots a node.
4662

4663
    """
4664
    result = self.rpc.call_node_powercycle(self.op.node_name,
4665
                                           self.cfg.GetHypervisorType())
4666
    result.Raise("Failed to schedule the reboot")
4667
    return result.payload
4668

    
4669

    
4670
class LUClusterQuery(NoHooksLU):
4671
  """Query cluster configuration.
4672

4673
  """
4674
  REQ_BGL = False
4675

    
4676
  def ExpandNames(self):
4677
    self.needed_locks = {}
4678

    
4679
  def Exec(self, feedback_fn):
4680
    """Return cluster config.
4681

4682
    """
4683
    cluster = self.cfg.GetClusterInfo()
4684
    os_hvp = {}
4685

    
4686
    # Filter just for enabled hypervisors
4687
    for os_name, hv_dict in cluster.os_hvp.items():
4688
      os_hvp[os_name] = {}
4689
      for hv_name, hv_params in hv_dict.items():
4690
        if hv_name in cluster.enabled_hypervisors:
4691
          os_hvp[os_name][hv_name] = hv_params
4692

    
4693
    # Convert ip_family to ip_version
4694
    primary_ip_version = constants.IP4_VERSION
4695
    if cluster.primary_ip_family == netutils.IP6Address.family:
4696
      primary_ip_version = constants.IP6_VERSION
4697

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

    
4736
    return result
4737

    
4738

    
4739
class LUClusterConfigQuery(NoHooksLU):
4740
  """Return configuration values.
4741

4742
  """
4743
  REQ_BGL = False
4744
  _FIELDS_DYNAMIC = utils.FieldSet()
4745
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4746
                                  "watcher_pause", "volume_group_name")
4747

    
4748
  def CheckArguments(self):
4749
    _CheckOutputFields(static=self._FIELDS_STATIC,
4750
                       dynamic=self._FIELDS_DYNAMIC,
4751
                       selected=self.op.output_fields)
4752

    
4753
  def ExpandNames(self):
4754
    self.needed_locks = {}
4755

    
4756
  def Exec(self, feedback_fn):
4757
    """Dump a representation of the cluster config to the standard output.
4758

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

    
4777

    
4778
class LUInstanceActivateDisks(NoHooksLU):
4779
  """Bring up an instance's disks.
4780

4781
  """
4782
  REQ_BGL = False
4783

    
4784
  def ExpandNames(self):
4785
    self._ExpandAndLockInstance()
4786
    self.needed_locks[locking.LEVEL_NODE] = []
4787
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4788

    
4789
  def DeclareLocks(self, level):
4790
    if level == locking.LEVEL_NODE:
4791
      self._LockInstancesNodes()
4792

    
4793
  def CheckPrereq(self):
4794
    """Check prerequisites.
4795

4796
    This checks that the instance is in the cluster.
4797

4798
    """
4799
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4800
    assert self.instance is not None, \
4801
      "Cannot retrieve locked instance %s" % self.op.instance_name
4802
    _CheckNodeOnline(self, self.instance.primary_node)
4803

    
4804
  def Exec(self, feedback_fn):
4805
    """Activate the disks.
4806

4807
    """
4808
    disks_ok, disks_info = \
4809
              _AssembleInstanceDisks(self, self.instance,
4810
                                     ignore_size=self.op.ignore_size)
4811
    if not disks_ok:
4812
      raise errors.OpExecError("Cannot activate block devices")
4813

    
4814
    return disks_info
4815

    
4816

    
4817
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4818
                           ignore_size=False):
4819
  """Prepare the block devices for an instance.
4820

4821
  This sets up the block devices on all nodes.
4822

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

4840
  """
4841
  device_info = []
4842
  disks_ok = True
4843
  iname = instance.name
4844
  disks = _ExpandCheckDisks(instance, disks)
4845

    
4846
  # With the two passes mechanism we try to reduce the window of
4847
  # opportunity for the race condition of switching DRBD to primary
4848
  # before handshaking occured, but we do not eliminate it
4849

    
4850
  # The proper fix would be to wait (with some limits) until the
4851
  # connection has been made and drbd transitions from WFConnection
4852
  # into any other network-connected state (Connected, SyncTarget,
4853
  # SyncSource, etc.)
4854

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

    
4871
  # FIXME: race condition on drbd migration to primary
4872

    
4873
  # 2nd pass, do only the primary node
4874
  for idx, inst_disk in enumerate(disks):
4875
    dev_path = None
4876

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

    
4894
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4895

    
4896
  # leave the disks configured for the primary node
4897
  # this is a workaround that would be fixed better by
4898
  # improving the logical/physical id handling
4899
  for disk in disks:
4900
    lu.cfg.SetDiskID(disk, instance.primary_node)
4901

    
4902
  return disks_ok, device_info
4903

    
4904

    
4905
def _StartInstanceDisks(lu, instance, force):
4906
  """Start the disks of an instance.
4907

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

    
4919

    
4920
class LUInstanceDeactivateDisks(NoHooksLU):
4921
  """Shutdown an instance's disks.
4922

4923
  """
4924
  REQ_BGL = False
4925

    
4926
  def ExpandNames(self):
4927
    self._ExpandAndLockInstance()
4928
    self.needed_locks[locking.LEVEL_NODE] = []
4929
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4930

    
4931
  def DeclareLocks(self, level):
4932
    if level == locking.LEVEL_NODE:
4933
      self._LockInstancesNodes()
4934

    
4935
  def CheckPrereq(self):
4936
    """Check prerequisites.
4937

4938
    This checks that the instance is in the cluster.
4939

4940
    """
4941
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4942
    assert self.instance is not None, \
4943
      "Cannot retrieve locked instance %s" % self.op.instance_name
4944

    
4945
  def Exec(self, feedback_fn):
4946
    """Deactivate the disks
4947

4948
    """
4949
    instance = self.instance
4950
    if self.op.force:
4951
      _ShutdownInstanceDisks(self, instance)
4952
    else:
4953
      _SafeShutdownInstanceDisks(self, instance)
4954

    
4955

    
4956
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4957
  """Shutdown block devices of an instance.
4958

4959
  This function checks if an instance is running, before calling
4960
  _ShutdownInstanceDisks.
4961

4962
  """
4963
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4964
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4965

    
4966

    
4967
def _ExpandCheckDisks(instance, disks):
4968
  """Return the instance disks selected by the disks list
4969

4970
  @type disks: list of L{objects.Disk} or None
4971
  @param disks: selected disks
4972
  @rtype: list of L{objects.Disk}
4973
  @return: selected instance disks to act on
4974

4975
  """
4976
  if disks is None:
4977
    return instance.disks
4978
  else:
4979
    if not set(disks).issubset(instance.disks):
4980
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4981
                                   " target instance")
4982
    return disks
4983

    
4984

    
4985
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4986
  """Shutdown block devices of an instance.
4987

4988
  This does the shutdown on all nodes of the instance.
4989

4990
  If the ignore_primary is false, errors on the primary node are
4991
  ignored.
4992

4993
  """
4994
  all_result = True
4995
  disks = _ExpandCheckDisks(instance, disks)
4996

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

    
5010

    
5011
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5012
  """Checks if a node has enough free memory.
5013

5014
  This function check if a given node has the needed amount of free
5015
  memory. In case the node has less memory or we cannot get the
5016
  information from the node, this function raise an OpPrereqError
5017
  exception.
5018

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

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

    
5047

    
5048
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5049
  """Checks if nodes have enough free disk space in the all VGs.
5050

5051
  This function check if all given nodes have the needed amount of
5052
  free disk. In case any node has less disk or we cannot get the
5053
  information from the node, this function raise an OpPrereqError
5054
  exception.
5055

5056
  @type lu: C{LogicalUnit}
5057
  @param lu: a logical unit from which we get configuration data
5058
  @type nodenames: C{list}
5059
  @param nodenames: the list of node names to check
5060
  @type req_sizes: C{dict}
5061
  @param req_sizes: the hash of vg and corresponding amount of disk in
5062
      MiB to check for
5063
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5064
      or we cannot check the node
5065

5066
  """
5067
  for vg, req_size in req_sizes.items():
5068
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5069

    
5070

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

5074
  This function check if all given nodes have the needed amount of
5075
  free disk. In case any node has less disk or we cannot get the
5076
  information from the node, this function raise an OpPrereqError
5077
  exception.
5078

5079
  @type lu: C{LogicalUnit}
5080
  @param lu: a logical unit from which we get configuration data
5081
  @type nodenames: C{list}
5082
  @param nodenames: the list of node names to check
5083
  @type vg: C{str}
5084
  @param vg: the volume group to check
5085
  @type requested: C{int}
5086
  @param requested: the amount of disk in MiB to check for
5087
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5088
      or we cannot check the node
5089

5090
  """
5091
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5092
  for node in nodenames:
5093
    info = nodeinfo[node]
5094
    info.Raise("Cannot get current information from node %s" % node,
5095
               prereq=True, ecode=errors.ECODE_ENVIRON)
5096
    vg_free = info.payload.get("vg_free", None)
5097
    if not isinstance(vg_free, int):
5098
      raise errors.OpPrereqError("Can't compute free disk space on node"
5099
                                 " %s for vg %s, result was '%s'" %
5100
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5101
    if requested > vg_free:
5102
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5103
                                 " vg %s: required %d MiB, available %d MiB" %
5104
                                 (node, vg, requested, vg_free),
5105
                                 errors.ECODE_NORES)
5106

    
5107

    
5108
class LUInstanceStartup(LogicalUnit):
5109
  """Starts an instance.
5110

5111
  """
5112
  HPATH = "instance-start"
5113
  HTYPE = constants.HTYPE_INSTANCE
5114
  REQ_BGL = False
5115

    
5116
  def CheckArguments(self):
5117
    # extra beparams
5118
    if self.op.beparams:
5119
      # fill the beparams dict
5120
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5121

    
5122
  def ExpandNames(self):
5123
    self._ExpandAndLockInstance()
5124

    
5125
  def BuildHooksEnv(self):
5126
    """Build hooks env.
5127

5128
    This runs on master, primary and secondary nodes of the instance.
5129

5130
    """
5131
    env = {
5132
      "FORCE": self.op.force,
5133
      }
5134
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5135
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5136
    return env, nl, nl
5137

    
5138
  def CheckPrereq(self):
5139
    """Check prerequisites.
5140

5141
    This checks that the instance is in the cluster.
5142

5143
    """
5144
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5145
    assert self.instance is not None, \
5146
      "Cannot retrieve locked instance %s" % self.op.instance_name
5147

    
5148
    # extra hvparams
5149
    if self.op.hvparams:
5150
      # check hypervisor parameter syntax (locally)
5151
      cluster = self.cfg.GetClusterInfo()
5152
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5153
      filled_hvp = cluster.FillHV(instance)
5154
      filled_hvp.update(self.op.hvparams)
5155
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5156
      hv_type.CheckParameterSyntax(filled_hvp)
5157
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5158

    
5159
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5160

    
5161
    if self.primary_offline and self.op.ignore_offline_nodes:
5162
      self.proc.LogWarning("Ignoring offline primary node")
5163

    
5164
      if self.op.hvparams or self.op.beparams:
5165
        self.proc.LogWarning("Overridden parameters are ignored")
5166
    else:
5167
      _CheckNodeOnline(self, instance.primary_node)
5168

    
5169
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5170

    
5171
      # check bridges existence
5172
      _CheckInstanceBridgesExist(self, instance)
5173

    
5174
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5175
                                                instance.name,
5176
                                                instance.hypervisor)
5177
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5178
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5179
      if not remote_info.payload: # not running already
5180
        _CheckNodeFreeMemory(self, instance.primary_node,
5181
                             "starting instance %s" % instance.name,
5182
                             bep[constants.BE_MEMORY], instance.hypervisor)
5183

    
5184
  def Exec(self, feedback_fn):
5185
    """Start the instance.
5186

5187
    """
5188
    instance = self.instance
5189
    force = self.op.force
5190

    
5191
    self.cfg.MarkInstanceUp(instance.name)
5192

    
5193
    if self.primary_offline:
5194
      assert self.op.ignore_offline_nodes
5195
      self.proc.LogInfo("Primary node offline, marked instance as started")
5196
    else:
5197
      node_current = instance.primary_node
5198

    
5199
      _StartInstanceDisks(self, instance, force)
5200

    
5201
      result = self.rpc.call_instance_start(node_current, instance,
5202
                                            self.op.hvparams, self.op.beparams)
5203
      msg = result.fail_msg
5204
      if msg:
5205
        _ShutdownInstanceDisks(self, instance)
5206
        raise errors.OpExecError("Could not start instance: %s" % msg)
5207

    
5208

    
5209
class LUInstanceReboot(LogicalUnit):
5210
  """Reboot an instance.
5211

5212
  """
5213
  HPATH = "instance-reboot"
5214
  HTYPE = constants.HTYPE_INSTANCE
5215
  REQ_BGL = False
5216

    
5217
  def ExpandNames(self):
5218
    self._ExpandAndLockInstance()
5219

    
5220
  def BuildHooksEnv(self):
5221
    """Build hooks env.
5222

5223
    This runs on master, primary and secondary nodes of the instance.
5224

5225
    """
5226
    env = {
5227
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5228
      "REBOOT_TYPE": self.op.reboot_type,
5229
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5230
      }
5231
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5232
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5233
    return env, nl, nl
5234

    
5235
  def CheckPrereq(self):
5236
    """Check prerequisites.
5237

5238
    This checks that the instance is in the cluster.
5239

5240
    """
5241
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5242
    assert self.instance is not None, \
5243
      "Cannot retrieve locked instance %s" % self.op.instance_name
5244

    
5245
    _CheckNodeOnline(self, instance.primary_node)
5246

    
5247
    # check bridges existence
5248
    _CheckInstanceBridgesExist(self, instance)
5249

    
5250
  def Exec(self, feedback_fn):
5251
    """Reboot the instance.
5252

5253
    """
5254
    instance = self.instance
5255
    ignore_secondaries = self.op.ignore_secondaries
5256
    reboot_type = self.op.reboot_type
5257

    
5258
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5259
                                              instance.name,
5260
                                              instance.hypervisor)
5261
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5262
    instance_running = bool(remote_info.payload)
5263

    
5264
    node_current = instance.primary_node
5265

    
5266
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5267
                                            constants.INSTANCE_REBOOT_HARD]:
5268
      for disk in instance.disks:
5269
        self.cfg.SetDiskID(disk, node_current)
5270
      result = self.rpc.call_instance_reboot(node_current, instance,
5271
                                             reboot_type,
5272
                                             self.op.shutdown_timeout)
5273
      result.Raise("Could not reboot instance")
5274
    else:
5275
      if instance_running:
5276
        result = self.rpc.call_instance_shutdown(node_current, instance,
5277
                                                 self.op.shutdown_timeout)
5278
        result.Raise("Could not shutdown instance for full reboot")
5279
        _ShutdownInstanceDisks(self, instance)
5280
      else:
5281
        self.LogInfo("Instance %s was already stopped, starting now",
5282
                     instance.name)
5283
      _StartInstanceDisks(self, instance, ignore_secondaries)
5284
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5285
      msg = result.fail_msg
5286
      if msg:
5287
        _ShutdownInstanceDisks(self, instance)
5288
        raise errors.OpExecError("Could not start instance for"
5289
                                 " full reboot: %s" % msg)
5290

    
5291
    self.cfg.MarkInstanceUp(instance.name)
5292

    
5293

    
5294
class LUInstanceShutdown(LogicalUnit):
5295
  """Shutdown an instance.
5296

5297
  """
5298
  HPATH = "instance-stop"
5299
  HTYPE = constants.HTYPE_INSTANCE
5300
  REQ_BGL = False
5301

    
5302
  def ExpandNames(self):
5303
    self._ExpandAndLockInstance()
5304

    
5305
  def BuildHooksEnv(self):
5306
    """Build hooks env.
5307

5308
    This runs on master, primary and secondary nodes of the instance.
5309

5310
    """
5311
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5312
    env["TIMEOUT"] = self.op.timeout
5313
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5314
    return env, nl, nl
5315

    
5316
  def CheckPrereq(self):
5317
    """Check prerequisites.
5318

5319
    This checks that the instance is in the cluster.
5320

5321
    """
5322
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5323
    assert self.instance is not None, \
5324
      "Cannot retrieve locked instance %s" % self.op.instance_name
5325

    
5326
    self.primary_offline = \
5327
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5328

    
5329
    if self.primary_offline and self.op.ignore_offline_nodes:
5330
      self.proc.LogWarning("Ignoring offline primary node")
5331
    else:
5332
      _CheckNodeOnline(self, self.instance.primary_node)
5333

    
5334
  def Exec(self, feedback_fn):
5335
    """Shutdown the instance.
5336

5337
    """
5338
    instance = self.instance
5339
    node_current = instance.primary_node
5340
    timeout = self.op.timeout
5341

    
5342
    self.cfg.MarkInstanceDown(instance.name)
5343

    
5344
    if self.primary_offline:
5345
      assert self.op.ignore_offline_nodes
5346
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5347
    else:
5348
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5349
      msg = result.fail_msg
5350
      if msg:
5351
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5352

    
5353
      _ShutdownInstanceDisks(self, instance)
5354

    
5355

    
5356
class LUInstanceReinstall(LogicalUnit):
5357
  """Reinstall an instance.
5358

5359
  """
5360
  HPATH = "instance-reinstall"
5361
  HTYPE = constants.HTYPE_INSTANCE
5362
  REQ_BGL = False
5363

    
5364
  def ExpandNames(self):
5365
    self._ExpandAndLockInstance()
5366

    
5367
  def BuildHooksEnv(self):
5368
    """Build hooks env.
5369

5370
    This runs on master, primary and secondary nodes of the instance.
5371

5372
    """
5373
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5374
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5375
    return env, nl, nl
5376

    
5377
  def CheckPrereq(self):
5378
    """Check prerequisites.
5379

5380
    This checks that the instance is in the cluster and is not running.
5381

5382
    """
5383
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5384
    assert instance is not None, \
5385
      "Cannot retrieve locked instance %s" % self.op.instance_name
5386
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5387
                     " offline, cannot reinstall")
5388
    for node in instance.secondary_nodes:
5389
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5390
                       " cannot reinstall")
5391

    
5392
    if instance.disk_template == constants.DT_DISKLESS:
5393
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5394
                                 self.op.instance_name,
5395
                                 errors.ECODE_INVAL)
5396
    _CheckInstanceDown(self, instance, "cannot reinstall")
5397

    
5398
    if self.op.os_type is not None:
5399
      # OS verification
5400
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5401
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5402
      instance_os = self.op.os_type
5403
    else:
5404
      instance_os = instance.os
5405

    
5406
    nodelist = list(instance.all_nodes)
5407

    
5408
    if self.op.osparams:
5409
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5410
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5411
      self.os_inst = i_osdict # the new dict (without defaults)
5412
    else:
5413
      self.os_inst = None
5414

    
5415
    self.instance = instance
5416

    
5417
  def Exec(self, feedback_fn):
5418
    """Reinstall the instance.
5419

5420
    """
5421
    inst = self.instance
5422

    
5423
    if self.op.os_type is not None:
5424
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5425
      inst.os = self.op.os_type
5426
      # Write to configuration
5427
      self.cfg.Update(inst, feedback_fn)
5428

    
5429
    _StartInstanceDisks(self, inst, None)
5430
    try:
5431
      feedback_fn("Running the instance OS create scripts...")
5432
      # FIXME: pass debug option from opcode to backend
5433
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5434
                                             self.op.debug_level,
5435
                                             osparams=self.os_inst)
5436
      result.Raise("Could not install OS for instance %s on node %s" %
5437
                   (inst.name, inst.primary_node))
5438
    finally:
5439
      _ShutdownInstanceDisks(self, inst)
5440

    
5441

    
5442
class LUInstanceRecreateDisks(LogicalUnit):
5443
  """Recreate an instance's missing disks.
5444

5445
  """
5446
  HPATH = "instance-recreate-disks"
5447
  HTYPE = constants.HTYPE_INSTANCE
5448
  REQ_BGL = False
5449

    
5450
  def ExpandNames(self):
5451
    self._ExpandAndLockInstance()
5452

    
5453
  def BuildHooksEnv(self):
5454
    """Build hooks env.
5455

5456
    This runs on master, primary and secondary nodes of the instance.
5457

5458
    """
5459
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5460
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5461
    return env, nl, nl
5462

    
5463
  def CheckPrereq(self):
5464
    """Check prerequisites.
5465

5466
    This checks that the instance is in the cluster and is not running.
5467

5468
    """
5469
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5470
    assert instance is not None, \
5471
      "Cannot retrieve locked instance %s" % self.op.instance_name
5472
    _CheckNodeOnline(self, instance.primary_node)
5473

    
5474
    if instance.disk_template == constants.DT_DISKLESS:
5475
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5476
                                 self.op.instance_name, errors.ECODE_INVAL)
5477
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5478

    
5479
    if not self.op.disks:
5480
      self.op.disks = range(len(instance.disks))
5481
    else:
5482
      for idx in self.op.disks:
5483
        if idx >= len(instance.disks):
5484
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5485
                                     errors.ECODE_INVAL)
5486

    
5487
    self.instance = instance
5488

    
5489
  def Exec(self, feedback_fn):
5490
    """Recreate the disks.
5491

5492
    """
5493
    to_skip = []
5494
    for idx, _ in enumerate(self.instance.disks):
5495
      if idx not in self.op.disks: # disk idx has not been passed in
5496
        to_skip.append(idx)
5497
        continue
5498

    
5499
    _CreateDisks(self, self.instance, to_skip=to_skip)
5500

    
5501

    
5502
class LUInstanceRename(LogicalUnit):
5503
  """Rename an instance.
5504

5505
  """
5506
  HPATH = "instance-rename"
5507
  HTYPE = constants.HTYPE_INSTANCE
5508

    
5509
  def CheckArguments(self):
5510
    """Check arguments.
5511

5512
    """
5513
    if self.op.ip_check and not self.op.name_check:
5514
      # TODO: make the ip check more flexible and not depend on the name check
5515
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5516
                                 errors.ECODE_INVAL)
5517

    
5518
  def BuildHooksEnv(self):
5519
    """Build hooks env.
5520

5521
    This runs on master, primary and secondary nodes of the instance.
5522

5523
    """
5524
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5525
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5526
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5527
    return env, nl, nl
5528

    
5529
  def CheckPrereq(self):
5530
    """Check prerequisites.
5531

5532
    This checks that the instance is in the cluster and is not running.
5533

5534
    """
5535
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5536
                                                self.op.instance_name)
5537
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5538
    assert instance is not None
5539
    _CheckNodeOnline(self, instance.primary_node)
5540
    _CheckInstanceDown(self, instance, "cannot rename")
5541
    self.instance = instance
5542

    
5543
    new_name = self.op.new_name
5544
    if self.op.name_check:
5545
      hostname = netutils.GetHostname(name=new_name)
5546
      self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5547
                   hostname.name)
5548
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
5549
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
5550
                                    " same as given hostname '%s'") %
5551
                                    (hostname.name, self.op.new_name),
5552
                                    errors.ECODE_INVAL)
5553
      new_name = self.op.new_name = hostname.name
5554
      if (self.op.ip_check and
5555
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5556
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5557
                                   (hostname.ip, new_name),
5558
                                   errors.ECODE_NOTUNIQUE)
5559

    
5560
    instance_list = self.cfg.GetInstanceList()
5561
    if new_name in instance_list and new_name != instance.name:
5562
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5563
                                 new_name, errors.ECODE_EXISTS)
5564

    
5565
  def Exec(self, feedback_fn):
5566
    """Rename the instance.
5567

5568
    """
5569
    inst = self.instance
5570
    old_name = inst.name
5571

    
5572
    rename_file_storage = False
5573
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
5574
        self.op.new_name != inst.name):
5575
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5576
      rename_file_storage = True
5577

    
5578
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5579
    # Change the instance lock. This is definitely safe while we hold the BGL
5580
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5581
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5582

    
5583
    # re-read the instance from the configuration after rename
5584
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5585

    
5586
    if rename_file_storage:
5587
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5588
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5589
                                                     old_file_storage_dir,
5590
                                                     new_file_storage_dir)
5591
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5592
                   " (but the instance has been renamed in Ganeti)" %
5593
                   (inst.primary_node, old_file_storage_dir,
5594
                    new_file_storage_dir))
5595

    
5596
    _StartInstanceDisks(self, inst, None)
5597
    try:
5598
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5599
                                                 old_name, self.op.debug_level)
5600
      msg = result.fail_msg
5601
      if msg:
5602
        msg = ("Could not run OS rename script for instance %s on node %s"
5603
               " (but the instance has been renamed in Ganeti): %s" %
5604
               (inst.name, inst.primary_node, msg))
5605
        self.proc.LogWarning(msg)
5606
    finally:
5607
      _ShutdownInstanceDisks(self, inst)
5608

    
5609
    return inst.name
5610

    
5611

    
5612
class LUInstanceRemove(LogicalUnit):
5613
  """Remove an instance.
5614

5615
  """
5616
  HPATH = "instance-remove"
5617
  HTYPE = constants.HTYPE_INSTANCE
5618
  REQ_BGL = False
5619

    
5620
  def ExpandNames(self):
5621
    self._ExpandAndLockInstance()
5622
    self.needed_locks[locking.LEVEL_NODE] = []
5623
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5624

    
5625
  def DeclareLocks(self, level):
5626
    if level == locking.LEVEL_NODE:
5627
      self._LockInstancesNodes()
5628

    
5629
  def BuildHooksEnv(self):
5630
    """Build hooks env.
5631

5632
    This runs on master, primary and secondary nodes of the instance.
5633

5634
    """
5635
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5636
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5637
    nl = [self.cfg.GetMasterNode()]
5638
    nl_post = list(self.instance.all_nodes) + nl
5639
    return env, nl, nl_post
5640

    
5641
  def CheckPrereq(self):
5642
    """Check prerequisites.
5643

5644
    This checks that the instance is in the cluster.
5645

5646
    """
5647
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5648
    assert self.instance is not None, \
5649
      "Cannot retrieve locked instance %s" % self.op.instance_name
5650

    
5651
  def Exec(self, feedback_fn):
5652
    """Remove the instance.
5653

5654
    """
5655
    instance = self.instance
5656
    logging.info("Shutting down instance %s on node %s",
5657
                 instance.name, instance.primary_node)
5658

    
5659
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5660
                                             self.op.shutdown_timeout)
5661
    msg = result.fail_msg
5662
    if msg:
5663
      if self.op.ignore_failures:
5664
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5665
      else:
5666
        raise errors.OpExecError("Could not shutdown instance %s on"
5667
                                 " node %s: %s" %
5668
                                 (instance.name, instance.primary_node, msg))
5669

    
5670
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5671

    
5672

    
5673
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5674
  """Utility function to remove an instance.
5675

5676
  """
5677
  logging.info("Removing block devices for instance %s", instance.name)
5678

    
5679
  if not _RemoveDisks(lu, instance):
5680
    if not ignore_failures:
5681
      raise errors.OpExecError("Can't remove instance's disks")
5682
    feedback_fn("Warning: can't remove instance's disks")
5683

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

    
5686
  lu.cfg.RemoveInstance(instance.name)
5687

    
5688
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5689
    "Instance lock removal conflict"
5690

    
5691
  # Remove lock for the instance
5692
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5693

    
5694

    
5695
class LUInstanceQuery(NoHooksLU):
5696
  """Logical unit for querying instances.
5697

5698
  """
5699
  # pylint: disable-msg=W0142
5700
  REQ_BGL = False
5701

    
5702
  def CheckArguments(self):
5703
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
5704
                             self.op.output_fields, self.op.use_locking)
5705

    
5706
  def ExpandNames(self):
5707
    self.iq.ExpandNames(self)
5708

    
5709
  def DeclareLocks(self, level):
5710
    self.iq.DeclareLocks(self, level)
5711

    
5712
  def Exec(self, feedback_fn):
5713
    return self.iq.OldStyleQuery(self)
5714

    
5715

    
5716
class LUInstanceFailover(LogicalUnit):
5717
  """Failover an instance.
5718

5719
  """
5720
  HPATH = "instance-failover"
5721
  HTYPE = constants.HTYPE_INSTANCE
5722
  REQ_BGL = False
5723

    
5724
  def CheckArguments(self):
5725
    """Check the arguments.
5726

5727
    """
5728
    self.iallocator = getattr(self.op, "iallocator", None)
5729
    self.target_node = getattr(self.op, "target_node", None)
5730

    
5731
  def ExpandNames(self):
5732
    self._ExpandAndLockInstance()
5733

    
5734
    if self.op.target_node is not None:
5735
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5736

    
5737
    self.needed_locks[locking.LEVEL_NODE] = []
5738
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5739

    
5740
  def DeclareLocks(self, level):
5741
    if level == locking.LEVEL_NODE:
5742
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
5743
      if instance.disk_template in constants.DTS_EXT_MIRROR:
5744
        if self.op.target_node is None:
5745
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5746
        else:
5747
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
5748
                                                   self.op.target_node]
5749
        del self.recalculate_locks[locking.LEVEL_NODE]
5750
      else:
5751
        self._LockInstancesNodes()
5752

    
5753
  def BuildHooksEnv(self):
5754
    """Build hooks env.
5755

5756
    This runs on master, primary and secondary nodes of the instance.
5757

5758
    """
5759
    instance = self.instance
5760
    source_node = instance.primary_node
5761
    env = {
5762
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5763
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5764
      "OLD_PRIMARY": source_node,
5765
      "NEW_PRIMARY": self.op.target_node,
5766
      }
5767

    
5768
    if instance.disk_template in constants.DTS_INT_MIRROR:
5769
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
5770
      env["NEW_SECONDARY"] = source_node
5771
    else:
5772
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
5773

    
5774
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5775
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5776
    nl_post = list(nl)
5777
    nl_post.append(source_node)
5778
    return env, nl, nl_post
5779

    
5780
  def CheckPrereq(self):
5781
    """Check prerequisites.
5782

5783
    This checks that the instance is in the cluster.
5784

5785
    """
5786
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5787
    assert self.instance is not None, \
5788
      "Cannot retrieve locked instance %s" % self.op.instance_name
5789

    
5790
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5791
    if instance.disk_template not in constants.DTS_MIRRORED:
5792
      raise errors.OpPrereqError("Instance's disk layout is not"
5793
                                 " mirrored, cannot failover.",
5794
                                 errors.ECODE_STATE)
5795

    
5796
    if instance.disk_template in constants.DTS_EXT_MIRROR:
5797
      _CheckIAllocatorOrNode(self, "iallocator", "target_node")
5798
      if self.op.iallocator:
5799
        self._RunAllocator()
5800
        # Release all unnecessary node locks
5801
        nodes_keep = [instance.primary_node, self.op.target_node]
5802
        nodes_rel = [node for node in self.acquired_locks[locking.LEVEL_NODE]
5803
                     if node not in nodes_keep]
5804
        self.context.glm.release(locking.LEVEL_NODE, nodes_rel)
5805
        self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
5806

    
5807
      # self.op.target_node is already populated, either directly or by the
5808
      # iallocator run
5809
      target_node = self.op.target_node
5810

    
5811
    else:
5812
      secondary_nodes = instance.secondary_nodes
5813
      if not secondary_nodes:
5814
        raise errors.ConfigurationError("No secondary node but using"
5815
                                        " %s disk template" %
5816
                                        instance.disk_template)
5817
      target_node = secondary_nodes[0]
5818

    
5819
      if self.op.iallocator or (self.op.target_node and
5820
                                self.op.target_node != target_node):
5821
        raise errors.OpPrereqError("Instances with disk template %s cannot"
5822
                                   " be failed over to arbitrary nodes"
5823
                                   " (neither an iallocator nor a target"
5824
                                   " node can be passed)" %
5825
                                   instance.disk_template, errors.ECODE_INVAL)
5826
    _CheckNodeOnline(self, target_node)
5827
    _CheckNodeNotDrained(self, target_node)
5828

    
5829
    # Save target_node so that we can use it in BuildHooksEnv
5830
    self.op.target_node = target_node
5831

    
5832
    if instance.admin_up:
5833
      # check memory requirements on the secondary node
5834
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5835
                           instance.name, bep[constants.BE_MEMORY],
5836
                           instance.hypervisor)
5837
    else:
5838
      self.LogInfo("Not checking memory on the secondary node as"
5839
                   " instance will not be started")
5840

    
5841
    # check bridge existance
5842
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5843

    
5844
  def Exec(self, feedback_fn):
5845
    """Failover an instance.
5846

5847
    The failover is done by shutting it down on its present node and
5848
    starting it on the secondary.
5849

5850
    """
5851
    instance = self.instance
5852
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5853

    
5854
    source_node = instance.primary_node
5855
    target_node = self.op.target_node
5856

    
5857
    if instance.admin_up:
5858
      feedback_fn("* checking disk consistency between source and target")
5859
      for dev in instance.disks:
5860
        # for drbd, these are drbd over lvm
5861
        if not _CheckDiskConsistency(self, dev, target_node, False):
5862
          if not self.op.ignore_consistency:
5863
            raise errors.OpExecError("Disk %s is degraded on target node,"
5864
                                     " aborting failover." % dev.iv_name)
5865
    else:
5866
      feedback_fn("* not checking disk consistency as instance is not running")
5867

    
5868
    feedback_fn("* shutting down instance on source node")
5869
    logging.info("Shutting down instance %s on node %s",
5870
                 instance.name, source_node)
5871

    
5872
    result = self.rpc.call_instance_shutdown(source_node, instance,
5873
                                             self.op.shutdown_timeout)
5874
    msg = result.fail_msg
5875
    if msg:
5876
      if self.op.ignore_consistency or primary_node.offline:
5877
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5878
                             " Proceeding anyway. Please make sure node"
5879
                             " %s is down. Error details: %s",
5880
                             instance.name, source_node, source_node, msg)
5881
      else:
5882
        raise errors.OpExecError("Could not shutdown instance %s on"
5883
                                 " node %s: %s" %
5884
                                 (instance.name, source_node, msg))
5885

    
5886
    feedback_fn("* deactivating the instance's disks on source node")
5887
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5888
      raise errors.OpExecError("Can't shut down the instance's disks.")
5889

    
5890
    instance.primary_node = target_node
5891
    # distribute new instance config to the other nodes
5892
    self.cfg.Update(instance, feedback_fn)
5893

    
5894
    # Only start the instance if it's marked as up
5895
    if instance.admin_up:
5896
      feedback_fn("* activating the instance's disks on target node")
5897
      logging.info("Starting instance %s on node %s",
5898
                   instance.name, target_node)
5899

    
5900
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5901
                                           ignore_secondaries=True)
5902
      if not disks_ok:
5903
        _ShutdownInstanceDisks(self, instance)
5904
        raise errors.OpExecError("Can't activate the instance's disks")
5905

    
5906
      feedback_fn("* starting the instance on the target node")
5907
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5908
      msg = result.fail_msg
5909
      if msg:
5910
        _ShutdownInstanceDisks(self, instance)
5911
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5912
                                 (instance.name, target_node, msg))
5913

    
5914
  def _RunAllocator(self):
5915
    """Run the allocator based on input opcode.
5916

5917
    """
5918
    ial = IAllocator(self.cfg, self.rpc,
5919
                     mode=constants.IALLOCATOR_MODE_RELOC,
5920
                     name=self.instance.name,
5921
                     # TODO See why hail breaks with a single node below
5922
                     relocate_from=[self.instance.primary_node,
5923
                                    self.instance.primary_node],
5924
                     )
5925

    
5926
    ial.Run(self.op.iallocator)
5927

    
5928
    if not ial.success:
5929
      raise errors.OpPrereqError("Can't compute nodes using"
5930
                                 " iallocator '%s': %s" %
5931
                                 (self.op.iallocator, ial.info),
5932
                                 errors.ECODE_NORES)
5933
    if len(ial.result) != ial.required_nodes:
5934
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
5935
                                 " of nodes (%s), required %s" %
5936
                                 (self.op.iallocator, len(ial.result),
5937
                                  ial.required_nodes), errors.ECODE_FAULT)
5938
    self.op.target_node = ial.result[0]
5939
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
5940
                 self.instance.name, self.op.iallocator,
5941
                 utils.CommaJoin(ial.result))
5942

    
5943

    
5944
class LUInstanceMigrate(LogicalUnit):
5945
  """Migrate an instance.
5946

5947
  This is migration without shutting down, compared to the failover,
5948
  which is done with shutdown.
5949

5950
  """
5951
  HPATH = "instance-migrate"
5952
  HTYPE = constants.HTYPE_INSTANCE
5953
  REQ_BGL = False
5954

    
5955
  def ExpandNames(self):
5956
    self._ExpandAndLockInstance()
5957

    
5958
    if self.op.target_node is not None:
5959
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5960

    
5961
    self.needed_locks[locking.LEVEL_NODE] = []
5962
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5963

    
5964
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5965
                                       self.op.cleanup, self.op.iallocator,
5966
                                       self.op.target_node)
5967
    self.tasklets = [self._migrater]
5968

    
5969
  def DeclareLocks(self, level):
5970
    if level == locking.LEVEL_NODE:
5971
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
5972
      if instance.disk_template in constants.DTS_EXT_MIRROR:
5973
        if self.op.target_node is None:
5974
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
5975
        else:
5976
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
5977
                                                   self.op.target_node]
5978
        del self.recalculate_locks[locking.LEVEL_NODE]
5979
      else:
5980
        self._LockInstancesNodes()
5981

    
5982
  def BuildHooksEnv(self):
5983
    """Build hooks env.
5984

5985
    This runs on master, primary and secondary nodes of the instance.
5986

5987
    """
5988
    instance = self._migrater.instance
5989
    source_node = instance.primary_node
5990
    target_node = self._migrater.target_node
5991
    env = _BuildInstanceHookEnvByObject(self, instance)
5992
    env["MIGRATE_LIVE"] = self._migrater.live
5993
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5994
    env.update({
5995
        "OLD_PRIMARY": source_node,
5996
        "NEW_PRIMARY": target_node,
5997
        })
5998

    
5999
    if instance.disk_template in constants.DTS_INT_MIRROR:
6000
      env["OLD_SECONDARY"] = target_node
6001
      env["NEW_SECONDARY"] = source_node
6002
    else:
6003
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6004

    
6005
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6006
    nl_post = list(nl)
6007
    nl_post.append(source_node)
6008
    return env, nl, nl_post
6009

    
6010

    
6011
class LUInstanceMove(LogicalUnit):
6012
  """Move an instance by data-copying.
6013

6014
  """
6015
  HPATH = "instance-move"
6016
  HTYPE = constants.HTYPE_INSTANCE
6017
  REQ_BGL = False
6018

    
6019
  def ExpandNames(self):
6020
    self._ExpandAndLockInstance()
6021
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6022
    self.op.target_node = target_node
6023
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6024
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6025

    
6026
  def DeclareLocks(self, level):
6027
    if level == locking.LEVEL_NODE:
6028
      self._LockInstancesNodes(primary_only=True)
6029

    
6030
  def BuildHooksEnv(self):
6031
    """Build hooks env.
6032

6033
    This runs on master, primary and secondary nodes of the instance.
6034

6035
    """
6036
    env = {
6037
      "TARGET_NODE": self.op.target_node,
6038
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6039
      }
6040
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6041
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
6042
                                       self.op.target_node]
6043
    return env, nl, nl
6044

    
6045
  def CheckPrereq(self):
6046
    """Check prerequisites.
6047

6048
    This checks that the instance is in the cluster.
6049

6050
    """
6051
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6052
    assert self.instance is not None, \
6053
      "Cannot retrieve locked instance %s" % self.op.instance_name
6054

    
6055
    node = self.cfg.GetNodeInfo(self.op.target_node)
6056
    assert node is not None, \
6057
      "Cannot retrieve locked node %s" % self.op.target_node
6058

    
6059
    self.target_node = target_node = node.name
6060

    
6061
    if target_node == instance.primary_node:
6062
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6063
                                 (instance.name, target_node),
6064
                                 errors.ECODE_STATE)
6065

    
6066
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6067

    
6068
    for idx, dsk in enumerate(instance.disks):
6069
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6070
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6071
                                   " cannot copy" % idx, errors.ECODE_STATE)
6072

    
6073
    _CheckNodeOnline(self, target_node)
6074
    _CheckNodeNotDrained(self, target_node)
6075
    _CheckNodeVmCapable(self, target_node)
6076

    
6077
    if instance.admin_up:
6078
      # check memory requirements on the secondary node
6079
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6080
                           instance.name, bep[constants.BE_MEMORY],
6081
                           instance.hypervisor)
6082
    else:
6083
      self.LogInfo("Not checking memory on the secondary node as"
6084
                   " instance will not be started")
6085

    
6086
    # check bridge existance
6087
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6088

    
6089
  def Exec(self, feedback_fn):
6090
    """Move an instance.
6091

6092
    The move is done by shutting it down on its present node, copying
6093
    the data over (slow) and starting it on the new node.
6094

6095
    """
6096
    instance = self.instance
6097

    
6098
    source_node = instance.primary_node
6099
    target_node = self.target_node
6100

    
6101
    self.LogInfo("Shutting down instance %s on source node %s",
6102
                 instance.name, source_node)
6103

    
6104
    result = self.rpc.call_instance_shutdown(source_node, instance,
6105
                                             self.op.shutdown_timeout)
6106
    msg = result.fail_msg
6107
    if msg:
6108
      if self.op.ignore_consistency:
6109
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6110
                             " Proceeding anyway. Please make sure node"
6111
                             " %s is down. Error details: %s",
6112
                             instance.name, source_node, source_node, msg)
6113
      else:
6114
        raise errors.OpExecError("Could not shutdown instance %s on"
6115
                                 " node %s: %s" %
6116
                                 (instance.name, source_node, msg))
6117

    
6118
    # create the target disks
6119
    try:
6120
      _CreateDisks(self, instance, target_node=target_node)
6121
    except errors.OpExecError:
6122
      self.LogWarning("Device creation failed, reverting...")
6123
      try:
6124
        _RemoveDisks(self, instance, target_node=target_node)
6125
      finally:
6126
        self.cfg.ReleaseDRBDMinors(instance.name)
6127
        raise
6128

    
6129
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6130

    
6131
    errs = []
6132
    # activate, get path, copy the data over
6133
    for idx, disk in enumerate(instance.disks):
6134
      self.LogInfo("Copying data for disk %d", idx)
6135
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6136
                                               instance.name, True, idx)
6137
      if result.fail_msg:
6138
        self.LogWarning("Can't assemble newly created disk %d: %s",
6139
                        idx, result.fail_msg)
6140
        errs.append(result.fail_msg)
6141
        break
6142
      dev_path = result.payload
6143
      result = self.rpc.call_blockdev_export(source_node, disk,
6144
                                             target_node, dev_path,
6145
                                             cluster_name)
6146
      if result.fail_msg:
6147
        self.LogWarning("Can't copy data over for disk %d: %s",
6148
                        idx, result.fail_msg)
6149
        errs.append(result.fail_msg)
6150
        break
6151

    
6152
    if errs:
6153
      self.LogWarning("Some disks failed to copy, aborting")
6154
      try:
6155
        _RemoveDisks(self, instance, target_node=target_node)
6156
      finally:
6157
        self.cfg.ReleaseDRBDMinors(instance.name)
6158
        raise errors.OpExecError("Errors during disk copy: %s" %
6159
                                 (",".join(errs),))
6160

    
6161
    instance.primary_node = target_node
6162
    self.cfg.Update(instance, feedback_fn)
6163

    
6164
    self.LogInfo("Removing the disks on the original node")
6165
    _RemoveDisks(self, instance, target_node=source_node)
6166

    
6167
    # Only start the instance if it's marked as up
6168
    if instance.admin_up:
6169
      self.LogInfo("Starting instance %s on node %s",
6170
                   instance.name, target_node)
6171

    
6172
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6173
                                           ignore_secondaries=True)
6174
      if not disks_ok:
6175
        _ShutdownInstanceDisks(self, instance)
6176
        raise errors.OpExecError("Can't activate the instance's disks")
6177

    
6178
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6179
      msg = result.fail_msg
6180
      if msg:
6181
        _ShutdownInstanceDisks(self, instance)
6182
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6183
                                 (instance.name, target_node, msg))
6184

    
6185

    
6186
class LUNodeMigrate(LogicalUnit):
6187
  """Migrate all instances from a node.
6188

6189
  """
6190
  HPATH = "node-migrate"
6191
  HTYPE = constants.HTYPE_NODE
6192
  REQ_BGL = False
6193

    
6194
  def CheckArguments(self):
6195
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6196

    
6197
  def ExpandNames(self):
6198
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6199

    
6200
    self.needed_locks = {}
6201

    
6202
    # Create tasklets for migrating instances for all instances on this node
6203
    names = []
6204
    tasklets = []
6205

    
6206
    self.lock_all_nodes = False
6207

    
6208
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6209
      logging.debug("Migrating instance %s", inst.name)
6210
      names.append(inst.name)
6211

    
6212
      tasklets.append(TLMigrateInstance(self, inst.name, False,
6213
                                        self.op.iallocator, None))
6214

    
6215
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6216
        # We need to lock all nodes, as the iallocator will choose the
6217
        # destination nodes afterwards
6218
        self.lock_all_nodes = True
6219

    
6220
    self.tasklets = tasklets
6221

    
6222
    # Declare node locks
6223
    if self.lock_all_nodes:
6224
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6225
    else:
6226
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6227
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6228

    
6229
    # Declare instance locks
6230
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6231

    
6232
  def DeclareLocks(self, level):
6233
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6234
      self._LockInstancesNodes()
6235

    
6236
  def BuildHooksEnv(self):
6237
    """Build hooks env.
6238

6239
    This runs on the master, the primary and all the secondaries.
6240

6241
    """
6242
    env = {
6243
      "NODE_NAME": self.op.node_name,
6244
      }
6245

    
6246
    nl = [self.cfg.GetMasterNode()]
6247

    
6248
    return (env, nl, nl)
6249

    
6250

    
6251
class TLMigrateInstance(Tasklet):
6252
  """Tasklet class for instance migration.
6253

6254
  @type live: boolean
6255
  @ivar live: whether the migration will be done live or non-live;
6256
      this variable is initalized only after CheckPrereq has run
6257

6258
  """
6259
  def __init__(self, lu, instance_name, cleanup,
6260
               iallocator=None, target_node=None):
6261
    """Initializes this class.
6262

6263
    """
6264
    Tasklet.__init__(self, lu)
6265

    
6266
    # Parameters
6267
    self.instance_name = instance_name
6268
    self.cleanup = cleanup
6269
    self.live = False # will be overridden later
6270
    self.iallocator = iallocator
6271
    self.target_node = target_node
6272

    
6273
  def CheckPrereq(self):
6274
    """Check prerequisites.
6275

6276
    This checks that the instance is in the cluster.
6277

6278
    """
6279
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6280
    instance = self.cfg.GetInstanceInfo(instance_name)
6281
    assert instance is not None
6282
    self.instance = instance
6283

    
6284
    if instance.disk_template not in constants.DTS_MIRRORED:
6285
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6286
                                 " migrations" % instance.disk_template,
6287
                                 errors.ECODE_STATE)
6288

    
6289
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6290
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6291

    
6292
      if self.iallocator:
6293
        self._RunAllocator()
6294

    
6295
      # self.target_node is already populated, either directly or by the
6296
      # iallocator run
6297
      target_node = self.target_node
6298

    
6299
      if len(self.lu.tasklets) == 1:
6300
        # It is safe to remove locks only when we're the only tasklet in the LU
6301
        nodes_keep = [instance.primary_node, self.target_node]
6302
        nodes_rel = [node for node in self.lu.acquired_locks[locking.LEVEL_NODE]
6303
                     if node not in nodes_keep]
6304
        self.lu.context.glm.release(locking.LEVEL_NODE, nodes_rel)
6305
        self.lu.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6306

    
6307
    else:
6308
      secondary_nodes = instance.secondary_nodes
6309
      if not secondary_nodes:
6310
        raise errors.ConfigurationError("No secondary node but using"
6311
                                        " %s disk template" %
6312
                                        instance.disk_template)
6313
      target_node = secondary_nodes[0]
6314
      if self.lu.op.iallocator or (self.lu.op.target_node and
6315
                                   self.lu.op.target_node != target_node):
6316
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6317
                                   " be migrated over to arbitrary nodes"
6318
                                   " (neither an iallocator nor a target"
6319
                                   " node can be passed)" %
6320
                                   instance.disk_template, errors.ECODE_INVAL)
6321

    
6322
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6323

    
6324
    # check memory requirements on the secondary node
6325
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6326
                         instance.name, i_be[constants.BE_MEMORY],
6327
                         instance.hypervisor)
6328

    
6329
    # check bridge existance
6330
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6331

    
6332
    if not self.cleanup:
6333
      _CheckNodeNotDrained(self.lu, target_node)
6334
      result = self.rpc.call_instance_migratable(instance.primary_node,
6335
                                                 instance)
6336
      result.Raise("Can't migrate, please use failover",
6337
                   prereq=True, ecode=errors.ECODE_STATE)
6338

    
6339

    
6340
  def _RunAllocator(self):
6341
    """Run the allocator based on input opcode.
6342

6343
    """
6344
    ial = IAllocator(self.cfg, self.rpc,
6345
                     mode=constants.IALLOCATOR_MODE_RELOC,
6346
                     name=self.instance_name,
6347
                     # TODO See why hail breaks with a single node below
6348
                     relocate_from=[self.instance.primary_node,
6349
                                    self.instance.primary_node],
6350
                     )
6351

    
6352
    ial.Run(self.iallocator)
6353

    
6354
    if not ial.success:
6355
      raise errors.OpPrereqError("Can't compute nodes using"
6356
                                 " iallocator '%s': %s" %
6357
                                 (self.iallocator, ial.info),
6358
                                 errors.ECODE_NORES)
6359
    if len(ial.result) != ial.required_nodes:
6360
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6361
                                 " of nodes (%s), required %s" %
6362
                                 (self.iallocator, len(ial.result),
6363
                                  ial.required_nodes), errors.ECODE_FAULT)
6364
    self.target_node = ial.result[0]
6365
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6366
                 self.instance_name, self.iallocator,
6367
                 utils.CommaJoin(ial.result))
6368

    
6369
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6370
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6371
                                 " parameters are accepted",
6372
                                 errors.ECODE_INVAL)
6373
    if self.lu.op.live is not None:
6374
      if self.lu.op.live:
6375
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6376
      else:
6377
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6378
      # reset the 'live' parameter to None so that repeated
6379
      # invocations of CheckPrereq do not raise an exception
6380
      self.lu.op.live = None
6381
    elif self.lu.op.mode is None:
6382
      # read the default value from the hypervisor
6383
      i_hv = self.cfg.GetClusterInfo().FillHV(self.instance, skip_globals=False)
6384
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6385

    
6386
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6387

    
6388
  def _WaitUntilSync(self):
6389
    """Poll with custom rpc for disk sync.
6390

6391
    This uses our own step-based rpc call.
6392

6393
    """
6394
    self.feedback_fn("* wait until resync is done")
6395
    all_done = False
6396
    while not all_done:
6397
      all_done = True
6398
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6399
                                            self.nodes_ip,
6400
                                            self.instance.disks)
6401
      min_percent = 100
6402
      for node, nres in result.items():
6403
        nres.Raise("Cannot resync disks on node %s" % node)
6404
        node_done, node_percent = nres.payload
6405
        all_done = all_done and node_done
6406
        if node_percent is not None:
6407
          min_percent = min(min_percent, node_percent)
6408
      if not all_done:
6409
        if min_percent < 100:
6410
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6411
        time.sleep(2)
6412

    
6413
  def _EnsureSecondary(self, node):
6414
    """Demote a node to secondary.
6415

6416
    """
6417
    self.feedback_fn("* switching node %s to secondary mode" % node)
6418

    
6419
    for dev in self.instance.disks:
6420
      self.cfg.SetDiskID(dev, node)
6421

    
6422
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6423
                                          self.instance.disks)
6424
    result.Raise("Cannot change disk to secondary on node %s" % node)
6425

    
6426
  def _GoStandalone(self):
6427
    """Disconnect from the network.
6428

6429
    """
6430
    self.feedback_fn("* changing into standalone mode")
6431
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6432
                                               self.instance.disks)
6433
    for node, nres in result.items():
6434
      nres.Raise("Cannot disconnect disks node %s" % node)
6435

    
6436
  def _GoReconnect(self, multimaster):
6437
    """Reconnect to the network.
6438

6439
    """
6440
    if multimaster:
6441
      msg = "dual-master"
6442
    else:
6443
      msg = "single-master"
6444
    self.feedback_fn("* changing disks into %s mode" % msg)
6445
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6446
                                           self.instance.disks,
6447
                                           self.instance.name, multimaster)
6448
    for node, nres in result.items():
6449
      nres.Raise("Cannot change disks config on node %s" % node)
6450

    
6451
  def _ExecCleanup(self):
6452
    """Try to cleanup after a failed migration.
6453

6454
    The cleanup is done by:
6455
      - check that the instance is running only on one node
6456
        (and update the config if needed)
6457
      - change disks on its secondary node to secondary
6458
      - wait until disks are fully synchronized
6459
      - disconnect from the network
6460
      - change disks into single-master mode
6461
      - wait again until disks are fully synchronized
6462

6463
    """
6464
    instance = self.instance
6465
    target_node = self.target_node
6466
    source_node = self.source_node
6467

    
6468
    # check running on only one node
6469
    self.feedback_fn("* checking where the instance actually runs"
6470
                     " (if this hangs, the hypervisor might be in"
6471
                     " a bad state)")
6472
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6473
    for node, result in ins_l.items():
6474
      result.Raise("Can't contact node %s" % node)
6475

    
6476
    runningon_source = instance.name in ins_l[source_node].payload
6477
    runningon_target = instance.name in ins_l[target_node].payload
6478

    
6479
    if runningon_source and runningon_target:
6480
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6481
                               " or the hypervisor is confused. You will have"
6482
                               " to ensure manually that it runs only on one"
6483
                               " and restart this operation.")
6484

    
6485
    if not (runningon_source or runningon_target):
6486
      raise errors.OpExecError("Instance does not seem to be running at all."
6487
                               " In this case, it's safer to repair by"
6488
                               " running 'gnt-instance stop' to ensure disk"
6489
                               " shutdown, and then restarting it.")
6490

    
6491
    if runningon_target:
6492
      # the migration has actually succeeded, we need to update the config
6493
      self.feedback_fn("* instance running on secondary node (%s),"
6494
                       " updating config" % target_node)
6495
      instance.primary_node = target_node
6496
      self.cfg.Update(instance, self.feedback_fn)
6497
      demoted_node = source_node
6498
    else:
6499
      self.feedback_fn("* instance confirmed to be running on its"
6500
                       " primary node (%s)" % source_node)
6501
      demoted_node = target_node
6502

    
6503
    if instance.disk_template in constants.DTS_INT_MIRROR:
6504
      self._EnsureSecondary(demoted_node)
6505
      try:
6506
        self._WaitUntilSync()
6507
      except errors.OpExecError:
6508
        # we ignore here errors, since if the device is standalone, it
6509
        # won't be able to sync
6510
        pass
6511
      self._GoStandalone()
6512
      self._GoReconnect(False)
6513
      self._WaitUntilSync()
6514

    
6515
    self.feedback_fn("* done")
6516

    
6517
  def _RevertDiskStatus(self):
6518
    """Try to revert the disk status after a failed migration.
6519

6520
    """
6521
    target_node = self.target_node
6522
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
6523
      return
6524

    
6525
    try:
6526
      self._EnsureSecondary(target_node)
6527
      self._GoStandalone()
6528
      self._GoReconnect(False)
6529
      self._WaitUntilSync()
6530
    except errors.OpExecError, err:
6531
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6532
                         " drives: error '%s'\n"
6533
                         "Please look and recover the instance status" %
6534
                         str(err))
6535

    
6536
  def _AbortMigration(self):
6537
    """Call the hypervisor code to abort a started migration.
6538

6539
    """
6540
    instance = self.instance
6541
    target_node = self.target_node
6542
    migration_info = self.migration_info
6543

    
6544
    abort_result = self.rpc.call_finalize_migration(target_node,
6545
                                                    instance,
6546
                                                    migration_info,
6547
                                                    False)
6548
    abort_msg = abort_result.fail_msg
6549
    if abort_msg:
6550
      logging.error("Aborting migration failed on target node %s: %s",
6551
                    target_node, abort_msg)
6552
      # Don't raise an exception here, as we stil have to try to revert the
6553
      # disk status, even if this step failed.
6554

    
6555
  def _ExecMigration(self):
6556
    """Migrate an instance.
6557

6558
    The migrate is done by:
6559
      - change the disks into dual-master mode
6560
      - wait until disks are fully synchronized again
6561
      - migrate the instance
6562
      - change disks on the new secondary node (the old primary) to secondary
6563
      - wait until disks are fully synchronized
6564
      - change disks into single-master mode
6565

6566
    """
6567
    instance = self.instance
6568
    target_node = self.target_node
6569
    source_node = self.source_node
6570

    
6571
    self.feedback_fn("* checking disk consistency between source and target")
6572
    for dev in instance.disks:
6573
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6574
        raise errors.OpExecError("Disk %s is degraded or not fully"
6575
                                 " synchronized on target node,"
6576
                                 " aborting migrate." % dev.iv_name)
6577

    
6578
    # First get the migration information from the remote node
6579
    result = self.rpc.call_migration_info(source_node, instance)
6580
    msg = result.fail_msg
6581
    if msg:
6582
      log_err = ("Failed fetching source migration information from %s: %s" %
6583
                 (source_node, msg))
6584
      logging.error(log_err)
6585
      raise errors.OpExecError(log_err)
6586

    
6587
    self.migration_info = migration_info = result.payload
6588

    
6589
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6590
      # Then switch the disks to master/master mode
6591
      self._EnsureSecondary(target_node)
6592
      self._GoStandalone()
6593
      self._GoReconnect(True)
6594
      self._WaitUntilSync()
6595

    
6596
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6597
    result = self.rpc.call_accept_instance(target_node,
6598
                                           instance,
6599
                                           migration_info,
6600
                                           self.nodes_ip[target_node])
6601

    
6602
    msg = result.fail_msg
6603
    if msg:
6604
      logging.error("Instance pre-migration failed, trying to revert"
6605
                    " disk status: %s", msg)
6606
      self.feedback_fn("Pre-migration failed, aborting")
6607
      self._AbortMigration()
6608
      self._RevertDiskStatus()
6609
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6610
                               (instance.name, msg))
6611

    
6612
    self.feedback_fn("* migrating instance to %s" % target_node)
6613
    time.sleep(10)
6614
    result = self.rpc.call_instance_migrate(source_node, instance,
6615
                                            self.nodes_ip[target_node],
6616
                                            self.live)
6617
    msg = result.fail_msg
6618
    if msg:
6619
      logging.error("Instance migration failed, trying to revert"
6620
                    " disk status: %s", msg)
6621
      self.feedback_fn("Migration failed, aborting")
6622
      self._AbortMigration()
6623
      self._RevertDiskStatus()
6624
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6625
                               (instance.name, msg))
6626
    time.sleep(10)
6627

    
6628
    instance.primary_node = target_node
6629
    # distribute new instance config to the other nodes
6630
    self.cfg.Update(instance, self.feedback_fn)
6631

    
6632
    result = self.rpc.call_finalize_migration(target_node,
6633
                                              instance,
6634
                                              migration_info,
6635
                                              True)
6636
    msg = result.fail_msg
6637
    if msg:
6638
      logging.error("Instance migration succeeded, but finalization failed:"
6639
                    " %s", msg)
6640
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6641
                               msg)
6642

    
6643
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6644
      self._EnsureSecondary(source_node)
6645
      self._WaitUntilSync()
6646
      self._GoStandalone()
6647
      self._GoReconnect(False)
6648
      self._WaitUntilSync()
6649

    
6650
    self.feedback_fn("* done")
6651

    
6652
  def Exec(self, feedback_fn):
6653
    """Perform the migration.
6654

6655
    """
6656
    feedback_fn("Migrating instance %s" % self.instance.name)
6657

    
6658
    self.feedback_fn = feedback_fn
6659

    
6660
    self.source_node = self.instance.primary_node
6661

    
6662
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
6663
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
6664
      self.target_node = self.instance.secondary_nodes[0]
6665
      # Otherwise self.target_node has been populated either
6666
      # directly, or through an iallocator.
6667

    
6668
    self.all_nodes = [self.source_node, self.target_node]
6669
    self.nodes_ip = {
6670
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6671
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6672
      }
6673

    
6674
    if self.cleanup:
6675
      return self._ExecCleanup()
6676
    else:
6677
      return self._ExecMigration()
6678

    
6679

    
6680
def _CreateBlockDev(lu, node, instance, device, force_create,
6681
                    info, force_open):
6682
  """Create a tree of block devices on a given node.
6683

6684
  If this device type has to be created on secondaries, create it and
6685
  all its children.
6686

6687
  If not, just recurse to children keeping the same 'force' value.
6688

6689
  @param lu: the lu on whose behalf we execute
6690
  @param node: the node on which to create the device
6691
  @type instance: L{objects.Instance}
6692
  @param instance: the instance which owns the device
6693
  @type device: L{objects.Disk}
6694
  @param device: the device to create
6695
  @type force_create: boolean
6696
  @param force_create: whether to force creation of this device; this
6697
      will be change to True whenever we find a device which has
6698
      CreateOnSecondary() attribute
6699
  @param info: the extra 'metadata' we should attach to the device
6700
      (this will be represented as a LVM tag)
6701
  @type force_open: boolean
6702
  @param force_open: this parameter will be passes to the
6703
      L{backend.BlockdevCreate} function where it specifies
6704
      whether we run on primary or not, and it affects both
6705
      the child assembly and the device own Open() execution
6706

6707
  """
6708
  if device.CreateOnSecondary():
6709
    force_create = True
6710

    
6711
  if device.children:
6712
    for child in device.children:
6713
      _CreateBlockDev(lu, node, instance, child, force_create,
6714
                      info, force_open)
6715

    
6716
  if not force_create:
6717
    return
6718

    
6719
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6720

    
6721

    
6722
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6723
  """Create a single block device on a given node.
6724

6725
  This will not recurse over children of the device, so they must be
6726
  created in advance.
6727

6728
  @param lu: the lu on whose behalf we execute
6729
  @param node: the node on which to create the device
6730
  @type instance: L{objects.Instance}
6731
  @param instance: the instance which owns the device
6732
  @type device: L{objects.Disk}
6733
  @param device: the device to create
6734
  @param info: the extra 'metadata' we should attach to the device
6735
      (this will be represented as a LVM tag)
6736
  @type force_open: boolean
6737
  @param force_open: this parameter will be passes to the
6738
      L{backend.BlockdevCreate} function where it specifies
6739
      whether we run on primary or not, and it affects both
6740
      the child assembly and the device own Open() execution
6741

6742
  """
6743
  lu.cfg.SetDiskID(device, node)
6744
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6745
                                       instance.name, force_open, info)
6746
  result.Raise("Can't create block device %s on"
6747
               " node %s for instance %s" % (device, node, instance.name))
6748
  if device.physical_id is None:
6749
    device.physical_id = result.payload
6750

    
6751

    
6752
def _GenerateUniqueNames(lu, exts):
6753
  """Generate a suitable LV name.
6754

6755
  This will generate a logical volume name for the given instance.
6756

6757
  """
6758
  results = []
6759
  for val in exts:
6760
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6761
    results.append("%s%s" % (new_id, val))
6762
  return results
6763

    
6764

    
6765
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6766
                         p_minor, s_minor):
6767
  """Generate a drbd8 device complete with its children.
6768

6769
  """
6770
  port = lu.cfg.AllocatePort()
6771
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6772
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6773
                          logical_id=(vgname, names[0]))
6774
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6775
                          logical_id=(vgname, names[1]))
6776
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6777
                          logical_id=(primary, secondary, port,
6778
                                      p_minor, s_minor,
6779
                                      shared_secret),
6780
                          children=[dev_data, dev_meta],
6781
                          iv_name=iv_name)
6782
  return drbd_dev
6783

    
6784

    
6785
def _GenerateDiskTemplate(lu, template_name,
6786
                          instance_name, primary_node,
6787
                          secondary_nodes, disk_info,
6788
                          file_storage_dir, file_driver,
6789
                          base_index, feedback_fn):
6790
  """Generate the entire disk layout for a given template type.
6791

6792
  """
6793
  #TODO: compute space requirements
6794

    
6795
  vgname = lu.cfg.GetVGName()
6796
  disk_count = len(disk_info)
6797
  disks = []
6798
  if template_name == constants.DT_DISKLESS:
6799
    pass
6800
  elif template_name == constants.DT_PLAIN:
6801
    if len(secondary_nodes) != 0:
6802
      raise errors.ProgrammerError("Wrong template configuration")
6803

    
6804
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6805
                                      for i in range(disk_count)])
6806
    for idx, disk in enumerate(disk_info):
6807
      disk_index = idx + base_index
6808
      vg = disk.get("vg", vgname)
6809
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6810
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6811
                              logical_id=(vg, names[idx]),
6812
                              iv_name="disk/%d" % disk_index,
6813
                              mode=disk["mode"])
6814
      disks.append(disk_dev)
6815
  elif template_name == constants.DT_DRBD8:
6816
    if len(secondary_nodes) != 1:
6817
      raise errors.ProgrammerError("Wrong template configuration")
6818
    remote_node = secondary_nodes[0]
6819
    minors = lu.cfg.AllocateDRBDMinor(
6820
      [primary_node, remote_node] * len(disk_info), instance_name)
6821

    
6822
    names = []
6823
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6824
                                               for i in range(disk_count)]):
6825
      names.append(lv_prefix + "_data")
6826
      names.append(lv_prefix + "_meta")
6827
    for idx, disk in enumerate(disk_info):
6828
      disk_index = idx + base_index
6829
      vg = disk.get("vg", vgname)
6830
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6831
                                      disk["size"], vg, names[idx*2:idx*2+2],
6832
                                      "disk/%d" % disk_index,
6833
                                      minors[idx*2], minors[idx*2+1])
6834
      disk_dev.mode = disk["mode"]
6835
      disks.append(disk_dev)
6836
  elif template_name == constants.DT_FILE:
6837
    if len(secondary_nodes) != 0:
6838
      raise errors.ProgrammerError("Wrong template configuration")
6839

    
6840
    opcodes.RequireFileStorage()
6841

    
6842
    for idx, disk in enumerate(disk_info):
6843
      disk_index = idx + base_index
6844
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6845
                              iv_name="disk/%d" % disk_index,
6846
                              logical_id=(file_driver,
6847
                                          "%s/disk%d" % (file_storage_dir,
6848
                                                         disk_index)),
6849
                              mode=disk["mode"])
6850
      disks.append(disk_dev)
6851
  elif template_name == constants.DT_SHARED_FILE:
6852
    if len(secondary_nodes) != 0:
6853
      raise errors.ProgrammerError("Wrong template configuration")
6854

    
6855
    opcodes.RequireSharedFileStorage()
6856

    
6857
    for idx, disk in enumerate(disk_info):
6858
      disk_index = idx + base_index
6859
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6860
                              iv_name="disk/%d" % disk_index,
6861
                              logical_id=(file_driver,
6862
                                          "%s/disk%d" % (file_storage_dir,
6863
                                                         disk_index)),
6864
                              mode=disk["mode"])
6865
      disks.append(disk_dev)
6866
  elif template_name == constants.DT_BLOCK:
6867
    if len(secondary_nodes) != 0:
6868
      raise errors.ProgrammerError("Wrong template configuration")
6869

    
6870
    for idx, disk in enumerate(disk_info):
6871
      disk_index = idx + base_index
6872
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV, size=disk["size"],
6873
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
6874
                                          disk["adopt"]),
6875
                              iv_name="disk/%d" % disk_index,
6876
                              mode=disk["mode"])
6877
      disks.append(disk_dev)
6878

    
6879
  else:
6880
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6881
  return disks
6882

    
6883

    
6884
def _GetInstanceInfoText(instance):
6885
  """Compute that text that should be added to the disk's metadata.
6886

6887
  """
6888
  return "originstname+%s" % instance.name
6889

    
6890

    
6891
def _CalcEta(time_taken, written, total_size):
6892
  """Calculates the ETA based on size written and total size.
6893

6894
  @param time_taken: The time taken so far
6895
  @param written: amount written so far
6896
  @param total_size: The total size of data to be written
6897
  @return: The remaining time in seconds
6898

6899
  """
6900
  avg_time = time_taken / float(written)
6901
  return (total_size - written) * avg_time
6902

    
6903

    
6904
def _WipeDisks(lu, instance):
6905
  """Wipes instance disks.
6906

6907
  @type lu: L{LogicalUnit}
6908
  @param lu: the logical unit on whose behalf we execute
6909
  @type instance: L{objects.Instance}
6910
  @param instance: the instance whose disks we should create
6911
  @return: the success of the wipe
6912

6913
  """
6914
  node = instance.primary_node
6915

    
6916
  for device in instance.disks:
6917
    lu.cfg.SetDiskID(device, node)
6918

    
6919
  logging.info("Pause sync of instance %s disks", instance.name)
6920
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6921

    
6922
  for idx, success in enumerate(result.payload):
6923
    if not success:
6924
      logging.warn("pause-sync of instance %s for disks %d failed",
6925
                   instance.name, idx)
6926

    
6927
  try:
6928
    for idx, device in enumerate(instance.disks):
6929
      lu.LogInfo("* Wiping disk %d", idx)
6930
      logging.info("Wiping disk %d for instance %s, node %s",
6931
                   idx, instance.name, node)
6932

    
6933
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6934
      # MAX_WIPE_CHUNK at max
6935
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6936
                            constants.MIN_WIPE_CHUNK_PERCENT)
6937

    
6938
      offset = 0
6939
      size = device.size
6940
      last_output = 0
6941
      start_time = time.time()
6942

    
6943
      while offset < size:
6944
        wipe_size = min(wipe_chunk_size, size - offset)
6945
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6946
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
6947
                     (idx, offset, wipe_size))
6948
        now = time.time()
6949
        offset += wipe_size
6950
        if now - last_output >= 60:
6951
          eta = _CalcEta(now - start_time, offset, size)
6952
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
6953
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
6954
          last_output = now
6955
  finally:
6956
    logging.info("Resume sync of instance %s disks", instance.name)
6957

    
6958
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
6959

    
6960
    for idx, success in enumerate(result.payload):
6961
      if not success:
6962
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
6963
                      " look at the status and troubleshoot the issue.", idx)
6964
        logging.warn("resume-sync of instance %s for disks %d failed",
6965
                     instance.name, idx)
6966

    
6967

    
6968
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6969
  """Create all disks for an instance.
6970

6971
  This abstracts away some work from AddInstance.
6972

6973
  @type lu: L{LogicalUnit}
6974
  @param lu: the logical unit on whose behalf we execute
6975
  @type instance: L{objects.Instance}
6976
  @param instance: the instance whose disks we should create
6977
  @type to_skip: list
6978
  @param to_skip: list of indices to skip
6979
  @type target_node: string
6980
  @param target_node: if passed, overrides the target node for creation
6981
  @rtype: boolean
6982
  @return: the success of the creation
6983

6984
  """
6985
  info = _GetInstanceInfoText(instance)
6986
  if target_node is None:
6987
    pnode = instance.primary_node
6988
    all_nodes = instance.all_nodes
6989
  else:
6990
    pnode = target_node
6991
    all_nodes = [pnode]
6992

    
6993
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
6994
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6995
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6996

    
6997
    result.Raise("Failed to create directory '%s' on"
6998
                 " node %s" % (file_storage_dir, pnode))
6999

    
7000
  # Note: this needs to be kept in sync with adding of disks in
7001
  # LUInstanceSetParams
7002
  for idx, device in enumerate(instance.disks):
7003
    if to_skip and idx in to_skip:
7004
      continue
7005
    logging.info("Creating volume %s for instance %s",
7006
                 device.iv_name, instance.name)
7007
    #HARDCODE
7008
    for node in all_nodes:
7009
      f_create = node == pnode
7010
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7011

    
7012

    
7013
def _RemoveDisks(lu, instance, target_node=None):
7014
  """Remove all disks for an instance.
7015

7016
  This abstracts away some work from `AddInstance()` and
7017
  `RemoveInstance()`. Note that in case some of the devices couldn't
7018
  be removed, the removal will continue with the other ones (compare
7019
  with `_CreateDisks()`).
7020

7021
  @type lu: L{LogicalUnit}
7022
  @param lu: the logical unit on whose behalf we execute
7023
  @type instance: L{objects.Instance}
7024
  @param instance: the instance whose disks we should remove
7025
  @type target_node: string
7026
  @param target_node: used to override the node on which to remove the disks
7027
  @rtype: boolean
7028
  @return: the success of the removal
7029

7030
  """
7031
  logging.info("Removing block devices for instance %s", instance.name)
7032

    
7033
  all_result = True
7034
  for device in instance.disks:
7035
    if target_node:
7036
      edata = [(target_node, device)]
7037
    else:
7038
      edata = device.ComputeNodeTree(instance.primary_node)
7039
    for node, disk in edata:
7040
      lu.cfg.SetDiskID(disk, node)
7041
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7042
      if msg:
7043
        lu.LogWarning("Could not remove block device %s on node %s,"
7044
                      " continuing anyway: %s", device.iv_name, node, msg)
7045
        all_result = False
7046

    
7047
  if instance.disk_template == constants.DT_FILE:
7048
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7049
    if target_node:
7050
      tgt = target_node
7051
    else:
7052
      tgt = instance.primary_node
7053
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7054
    if result.fail_msg:
7055
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7056
                    file_storage_dir, instance.primary_node, result.fail_msg)
7057
      all_result = False
7058

    
7059
  return all_result
7060

    
7061

    
7062
def _ComputeDiskSizePerVG(disk_template, disks):
7063
  """Compute disk size requirements in the volume group
7064

7065
  """
7066
  def _compute(disks, payload):
7067
    """Universal algorithm
7068

7069
    """
7070
    vgs = {}
7071
    for disk in disks:
7072
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
7073

    
7074
    return vgs
7075

    
7076
  # Required free disk space as a function of disk and swap space
7077
  req_size_dict = {
7078
    constants.DT_DISKLESS: {},
7079
    constants.DT_PLAIN: _compute(disks, 0),
7080
    # 128 MB are added for drbd metadata for each disk
7081
    constants.DT_DRBD8: _compute(disks, 128),
7082
    constants.DT_FILE: {},
7083
    constants.DT_SHARED_FILE: {},
7084
  }
7085

    
7086
  if disk_template not in req_size_dict:
7087
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7088
                                 " is unknown" %  disk_template)
7089

    
7090
  return req_size_dict[disk_template]
7091

    
7092

    
7093
def _ComputeDiskSize(disk_template, disks):
7094
  """Compute disk size requirements in the volume group
7095

7096
  """
7097
  # Required free disk space as a function of disk and swap space
7098
  req_size_dict = {
7099
    constants.DT_DISKLESS: None,
7100
    constants.DT_PLAIN: sum(d["size"] for d in disks),
7101
    # 128 MB are added for drbd metadata for each disk
7102
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
7103
    constants.DT_FILE: None,
7104
    constants.DT_SHARED_FILE: 0,
7105
    constants.DT_BLOCK: 0,
7106
  }
7107

    
7108
  if disk_template not in req_size_dict:
7109
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7110
                                 " is unknown" %  disk_template)
7111

    
7112
  return req_size_dict[disk_template]
7113

    
7114

    
7115
def _FilterVmNodes(lu, nodenames):
7116
  """Filters out non-vm_capable nodes from a list.
7117

7118
  @type lu: L{LogicalUnit}
7119
  @param lu: the logical unit for which we check
7120
  @type nodenames: list
7121
  @param nodenames: the list of nodes on which we should check
7122
  @rtype: list
7123
  @return: the list of vm-capable nodes
7124

7125
  """
7126
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7127
  return [name for name in nodenames if name not in vm_nodes]
7128

    
7129

    
7130
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7131
  """Hypervisor parameter validation.
7132

7133
  This function abstract the hypervisor parameter validation to be
7134
  used in both instance create and instance modify.
7135

7136
  @type lu: L{LogicalUnit}
7137
  @param lu: the logical unit for which we check
7138
  @type nodenames: list
7139
  @param nodenames: the list of nodes on which we should check
7140
  @type hvname: string
7141
  @param hvname: the name of the hypervisor we should use
7142
  @type hvparams: dict
7143
  @param hvparams: the parameters which we need to check
7144
  @raise errors.OpPrereqError: if the parameters are not valid
7145

7146
  """
7147
  nodenames = _FilterVmNodes(lu, nodenames)
7148
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7149
                                                  hvname,
7150
                                                  hvparams)
7151
  for node in nodenames:
7152
    info = hvinfo[node]
7153
    if info.offline:
7154
      continue
7155
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7156

    
7157

    
7158
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7159
  """OS parameters validation.
7160

7161
  @type lu: L{LogicalUnit}
7162
  @param lu: the logical unit for which we check
7163
  @type required: boolean
7164
  @param required: whether the validation should fail if the OS is not
7165
      found
7166
  @type nodenames: list
7167
  @param nodenames: the list of nodes on which we should check
7168
  @type osname: string
7169
  @param osname: the name of the hypervisor we should use
7170
  @type osparams: dict
7171
  @param osparams: the parameters which we need to check
7172
  @raise errors.OpPrereqError: if the parameters are not valid
7173

7174
  """
7175
  nodenames = _FilterVmNodes(lu, nodenames)
7176
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7177
                                   [constants.OS_VALIDATE_PARAMETERS],
7178
                                   osparams)
7179
  for node, nres in result.items():
7180
    # we don't check for offline cases since this should be run only
7181
    # against the master node and/or an instance's nodes
7182
    nres.Raise("OS Parameters validation failed on node %s" % node)
7183
    if not nres.payload:
7184
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7185
                 osname, node)
7186

    
7187

    
7188
class LUInstanceCreate(LogicalUnit):
7189
  """Create an instance.
7190

7191
  """
7192
  HPATH = "instance-add"
7193
  HTYPE = constants.HTYPE_INSTANCE
7194
  REQ_BGL = False
7195

    
7196
  def CheckArguments(self):
7197
    """Check arguments.
7198

7199
    """
7200
    # do not require name_check to ease forward/backward compatibility
7201
    # for tools
7202
    if self.op.no_install and self.op.start:
7203
      self.LogInfo("No-installation mode selected, disabling startup")
7204
      self.op.start = False
7205
    # validate/normalize the instance name
7206
    self.op.instance_name = \
7207
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7208

    
7209
    if self.op.ip_check and not self.op.name_check:
7210
      # TODO: make the ip check more flexible and not depend on the name check
7211
      raise errors.OpPrereqError("Cannot do ip check without a name check",
7212
                                 errors.ECODE_INVAL)
7213

    
7214
    # check nics' parameter names
7215
    for nic in self.op.nics:
7216
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7217

    
7218
    # check disks. parameter names and consistent adopt/no-adopt strategy
7219
    has_adopt = has_no_adopt = False
7220
    for disk in self.op.disks:
7221
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7222
      if "adopt" in disk:
7223
        has_adopt = True
7224
      else:
7225
        has_no_adopt = True
7226
    if has_adopt and has_no_adopt:
7227
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7228
                                 errors.ECODE_INVAL)
7229
    if has_adopt:
7230
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7231
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7232
                                   " '%s' disk template" %
7233
                                   self.op.disk_template,
7234
                                   errors.ECODE_INVAL)
7235
      if self.op.iallocator is not None:
7236
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7237
                                   " iallocator script", errors.ECODE_INVAL)
7238
      if self.op.mode == constants.INSTANCE_IMPORT:
7239
        raise errors.OpPrereqError("Disk adoption not allowed for"
7240
                                   " instance import", errors.ECODE_INVAL)
7241
    else:
7242
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7243
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7244
                                   " but no 'adopt' parameter given" %
7245
                                   self.op.disk_template,
7246
                                   errors.ECODE_INVAL)
7247

    
7248
    self.adopt_disks = has_adopt
7249

    
7250
    # instance name verification
7251
    if self.op.name_check:
7252
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7253
      self.op.instance_name = self.hostname1.name
7254
      # used in CheckPrereq for ip ping check
7255
      self.check_ip = self.hostname1.ip
7256
    else:
7257
      self.check_ip = None
7258

    
7259
    # file storage checks
7260
    if (self.op.file_driver and
7261
        not self.op.file_driver in constants.FILE_DRIVER):
7262
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7263
                                 self.op.file_driver, errors.ECODE_INVAL)
7264

    
7265
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7266
      raise errors.OpPrereqError("File storage directory path not absolute",
7267
                                 errors.ECODE_INVAL)
7268

    
7269
    ### Node/iallocator related checks
7270
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7271

    
7272
    if self.op.pnode is not None:
7273
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7274
        if self.op.snode is None:
7275
          raise errors.OpPrereqError("The networked disk templates need"
7276
                                     " a mirror node", errors.ECODE_INVAL)
7277
      elif self.op.snode:
7278
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7279
                        " template")
7280
        self.op.snode = None
7281

    
7282
    self._cds = _GetClusterDomainSecret()
7283

    
7284
    if self.op.mode == constants.INSTANCE_IMPORT:
7285
      # On import force_variant must be True, because if we forced it at
7286
      # initial install, our only chance when importing it back is that it
7287
      # works again!
7288
      self.op.force_variant = True
7289

    
7290
      if self.op.no_install:
7291
        self.LogInfo("No-installation mode has no effect during import")
7292

    
7293
    elif self.op.mode == constants.INSTANCE_CREATE:
7294
      if self.op.os_type is None:
7295
        raise errors.OpPrereqError("No guest OS specified",
7296
                                   errors.ECODE_INVAL)
7297
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7298
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7299
                                   " installation" % self.op.os_type,
7300
                                   errors.ECODE_STATE)
7301
      if self.op.disk_template is None:
7302
        raise errors.OpPrereqError("No disk template specified",
7303
                                   errors.ECODE_INVAL)
7304

    
7305
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7306
      # Check handshake to ensure both clusters have the same domain secret
7307
      src_handshake = self.op.source_handshake
7308
      if not src_handshake:
7309
        raise errors.OpPrereqError("Missing source handshake",
7310
                                   errors.ECODE_INVAL)
7311

    
7312
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7313
                                                           src_handshake)
7314
      if errmsg:
7315
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7316
                                   errors.ECODE_INVAL)
7317

    
7318
      # Load and check source CA
7319
      self.source_x509_ca_pem = self.op.source_x509_ca
7320
      if not self.source_x509_ca_pem:
7321
        raise errors.OpPrereqError("Missing source X509 CA",
7322
                                   errors.ECODE_INVAL)
7323

    
7324
      try:
7325
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7326
                                                    self._cds)
7327
      except OpenSSL.crypto.Error, err:
7328
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7329
                                   (err, ), errors.ECODE_INVAL)
7330

    
7331
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7332
      if errcode is not None:
7333
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7334
                                   errors.ECODE_INVAL)
7335

    
7336
      self.source_x509_ca = cert
7337

    
7338
      src_instance_name = self.op.source_instance_name
7339
      if not src_instance_name:
7340
        raise errors.OpPrereqError("Missing source instance name",
7341
                                   errors.ECODE_INVAL)
7342

    
7343
      self.source_instance_name = \
7344
          netutils.GetHostname(name=src_instance_name).name
7345

    
7346
    else:
7347
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7348
                                 self.op.mode, errors.ECODE_INVAL)
7349

    
7350
  def ExpandNames(self):
7351
    """ExpandNames for CreateInstance.
7352

7353
    Figure out the right locks for instance creation.
7354

7355
    """
7356
    self.needed_locks = {}
7357

    
7358
    instance_name = self.op.instance_name
7359
    # this is just a preventive check, but someone might still add this
7360
    # instance in the meantime, and creation will fail at lock-add time
7361
    if instance_name in self.cfg.GetInstanceList():
7362
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7363
                                 instance_name, errors.ECODE_EXISTS)
7364

    
7365
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7366

    
7367
    if self.op.iallocator:
7368
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7369
    else:
7370
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7371
      nodelist = [self.op.pnode]
7372
      if self.op.snode is not None:
7373
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7374
        nodelist.append(self.op.snode)
7375
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7376

    
7377
    # in case of import lock the source node too
7378
    if self.op.mode == constants.INSTANCE_IMPORT:
7379
      src_node = self.op.src_node
7380
      src_path = self.op.src_path
7381

    
7382
      if src_path is None:
7383
        self.op.src_path = src_path = self.op.instance_name
7384

    
7385
      if src_node is None:
7386
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7387
        self.op.src_node = None
7388
        if os.path.isabs(src_path):
7389
          raise errors.OpPrereqError("Importing an instance from an absolute"
7390
                                     " path requires a source node option.",
7391
                                     errors.ECODE_INVAL)
7392
      else:
7393
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7394
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7395
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7396
        if not os.path.isabs(src_path):
7397
          self.op.src_path = src_path = \
7398
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7399

    
7400
  def _RunAllocator(self):
7401
    """Run the allocator based on input opcode.
7402

7403
    """
7404
    nics = [n.ToDict() for n in self.nics]
7405
    ial = IAllocator(self.cfg, self.rpc,
7406
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7407
                     name=self.op.instance_name,
7408
                     disk_template=self.op.disk_template,
7409
                     tags=[],
7410
                     os=self.op.os_type,
7411
                     vcpus=self.be_full[constants.BE_VCPUS],
7412
                     mem_size=self.be_full[constants.BE_MEMORY],
7413
                     disks=self.disks,
7414
                     nics=nics,
7415
                     hypervisor=self.op.hypervisor,
7416
                     )
7417

    
7418
    ial.Run(self.op.iallocator)
7419

    
7420
    if not ial.success:
7421
      raise errors.OpPrereqError("Can't compute nodes using"
7422
                                 " iallocator '%s': %s" %
7423
                                 (self.op.iallocator, ial.info),
7424
                                 errors.ECODE_NORES)
7425
    if len(ial.result) != ial.required_nodes:
7426
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7427
                                 " of nodes (%s), required %s" %
7428
                                 (self.op.iallocator, len(ial.result),
7429
                                  ial.required_nodes), errors.ECODE_FAULT)
7430
    self.op.pnode = ial.result[0]
7431
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7432
                 self.op.instance_name, self.op.iallocator,
7433
                 utils.CommaJoin(ial.result))
7434
    if ial.required_nodes == 2:
7435
      self.op.snode = ial.result[1]
7436

    
7437
  def BuildHooksEnv(self):
7438
    """Build hooks env.
7439

7440
    This runs on master, primary and secondary nodes of the instance.
7441

7442
    """
7443
    env = {
7444
      "ADD_MODE": self.op.mode,
7445
      }
7446
    if self.op.mode == constants.INSTANCE_IMPORT:
7447
      env["SRC_NODE"] = self.op.src_node
7448
      env["SRC_PATH"] = self.op.src_path
7449
      env["SRC_IMAGES"] = self.src_images
7450

    
7451
    env.update(_BuildInstanceHookEnv(
7452
      name=self.op.instance_name,
7453
      primary_node=self.op.pnode,
7454
      secondary_nodes=self.secondaries,
7455
      status=self.op.start,
7456
      os_type=self.op.os_type,
7457
      memory=self.be_full[constants.BE_MEMORY],
7458
      vcpus=self.be_full[constants.BE_VCPUS],
7459
      nics=_NICListToTuple(self, self.nics),
7460
      disk_template=self.op.disk_template,
7461
      disks=[(d["size"], d["mode"]) for d in self.disks],
7462
      bep=self.be_full,
7463
      hvp=self.hv_full,
7464
      hypervisor_name=self.op.hypervisor,
7465
    ))
7466

    
7467
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7468
          self.secondaries)
7469
    return env, nl, nl
7470

    
7471
  def _ReadExportInfo(self):
7472
    """Reads the export information from disk.
7473

7474
    It will override the opcode source node and path with the actual
7475
    information, if these two were not specified before.
7476

7477
    @return: the export information
7478

7479
    """
7480
    assert self.op.mode == constants.INSTANCE_IMPORT
7481

    
7482
    src_node = self.op.src_node
7483
    src_path = self.op.src_path
7484

    
7485
    if src_node is None:
7486
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7487
      exp_list = self.rpc.call_export_list(locked_nodes)
7488
      found = False
7489
      for node in exp_list:
7490
        if exp_list[node].fail_msg:
7491
          continue
7492
        if src_path in exp_list[node].payload:
7493
          found = True
7494
          self.op.src_node = src_node = node
7495
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7496
                                                       src_path)
7497
          break
7498
      if not found:
7499
        raise errors.OpPrereqError("No export found for relative path %s" %
7500
                                    src_path, errors.ECODE_INVAL)
7501

    
7502
    _CheckNodeOnline(self, src_node)
7503
    result = self.rpc.call_export_info(src_node, src_path)
7504
    result.Raise("No export or invalid export found in dir %s" % src_path)
7505

    
7506
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7507
    if not export_info.has_section(constants.INISECT_EXP):
7508
      raise errors.ProgrammerError("Corrupted export config",
7509
                                   errors.ECODE_ENVIRON)
7510

    
7511
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7512
    if (int(ei_version) != constants.EXPORT_VERSION):
7513
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7514
                                 (ei_version, constants.EXPORT_VERSION),
7515
                                 errors.ECODE_ENVIRON)
7516
    return export_info
7517

    
7518
  def _ReadExportParams(self, einfo):
7519
    """Use export parameters as defaults.
7520

7521
    In case the opcode doesn't specify (as in override) some instance
7522
    parameters, then try to use them from the export information, if
7523
    that declares them.
7524

7525
    """
7526
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7527

    
7528
    if self.op.disk_template is None:
7529
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7530
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7531
                                          "disk_template")
7532
      else:
7533
        raise errors.OpPrereqError("No disk template specified and the export"
7534
                                   " is missing the disk_template information",
7535
                                   errors.ECODE_INVAL)
7536

    
7537
    if not self.op.disks:
7538
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7539
        disks = []
7540
        # TODO: import the disk iv_name too
7541
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7542
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7543
          disks.append({"size": disk_sz})
7544
        self.op.disks = disks
7545
      else:
7546
        raise errors.OpPrereqError("No disk info specified and the export"
7547
                                   " is missing the disk information",
7548
                                   errors.ECODE_INVAL)
7549

    
7550
    if (not self.op.nics and
7551
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7552
      nics = []
7553
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7554
        ndict = {}
7555
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7556
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7557
          ndict[name] = v
7558
        nics.append(ndict)
7559
      self.op.nics = nics
7560

    
7561
    if (self.op.hypervisor is None and
7562
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7563
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7564
    if einfo.has_section(constants.INISECT_HYP):
7565
      # use the export parameters but do not override the ones
7566
      # specified by the user
7567
      for name, value in einfo.items(constants.INISECT_HYP):
7568
        if name not in self.op.hvparams:
7569
          self.op.hvparams[name] = value
7570

    
7571
    if einfo.has_section(constants.INISECT_BEP):
7572
      # use the parameters, without overriding
7573
      for name, value in einfo.items(constants.INISECT_BEP):
7574
        if name not in self.op.beparams:
7575
          self.op.beparams[name] = value
7576
    else:
7577
      # try to read the parameters old style, from the main section
7578
      for name in constants.BES_PARAMETERS:
7579
        if (name not in self.op.beparams and
7580
            einfo.has_option(constants.INISECT_INS, name)):
7581
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7582

    
7583
    if einfo.has_section(constants.INISECT_OSP):
7584
      # use the parameters, without overriding
7585
      for name, value in einfo.items(constants.INISECT_OSP):
7586
        if name not in self.op.osparams:
7587
          self.op.osparams[name] = value
7588

    
7589
  def _RevertToDefaults(self, cluster):
7590
    """Revert the instance parameters to the default values.
7591

7592
    """
7593
    # hvparams
7594
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7595
    for name in self.op.hvparams.keys():
7596
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7597
        del self.op.hvparams[name]
7598
    # beparams
7599
    be_defs = cluster.SimpleFillBE({})
7600
    for name in self.op.beparams.keys():
7601
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7602
        del self.op.beparams[name]
7603
    # nic params
7604
    nic_defs = cluster.SimpleFillNIC({})
7605
    for nic in self.op.nics:
7606
      for name in constants.NICS_PARAMETERS:
7607
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7608
          del nic[name]
7609
    # osparams
7610
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7611
    for name in self.op.osparams.keys():
7612
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7613
        del self.op.osparams[name]
7614

    
7615
  def CheckPrereq(self):
7616
    """Check prerequisites.
7617

7618
    """
7619
    if self.op.mode == constants.INSTANCE_IMPORT:
7620
      export_info = self._ReadExportInfo()
7621
      self._ReadExportParams(export_info)
7622

    
7623
    if (not self.cfg.GetVGName() and
7624
        self.op.disk_template not in constants.DTS_NOT_LVM):
7625
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7626
                                 " instances", errors.ECODE_STATE)
7627

    
7628
    if self.op.hypervisor is None:
7629
      self.op.hypervisor = self.cfg.GetHypervisorType()
7630

    
7631
    cluster = self.cfg.GetClusterInfo()
7632
    enabled_hvs = cluster.enabled_hypervisors
7633
    if self.op.hypervisor not in enabled_hvs:
7634
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7635
                                 " cluster (%s)" % (self.op.hypervisor,
7636
                                  ",".join(enabled_hvs)),
7637
                                 errors.ECODE_STATE)
7638

    
7639
    # check hypervisor parameter syntax (locally)
7640
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7641
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7642
                                      self.op.hvparams)
7643
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7644
    hv_type.CheckParameterSyntax(filled_hvp)
7645
    self.hv_full = filled_hvp
7646
    # check that we don't specify global parameters on an instance
7647
    _CheckGlobalHvParams(self.op.hvparams)
7648

    
7649
    # fill and remember the beparams dict
7650
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7651
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7652

    
7653
    # build os parameters
7654
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7655

    
7656
    # now that hvp/bep are in final format, let's reset to defaults,
7657
    # if told to do so
7658
    if self.op.identify_defaults:
7659
      self._RevertToDefaults(cluster)
7660

    
7661
    # NIC buildup
7662
    self.nics = []
7663
    for idx, nic in enumerate(self.op.nics):
7664
      nic_mode_req = nic.get("mode", None)
7665
      nic_mode = nic_mode_req
7666
      if nic_mode is None:
7667
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7668

    
7669
      # in routed mode, for the first nic, the default ip is 'auto'
7670
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7671
        default_ip_mode = constants.VALUE_AUTO
7672
      else:
7673
        default_ip_mode = constants.VALUE_NONE
7674

    
7675
      # ip validity checks
7676
      ip = nic.get("ip", default_ip_mode)
7677
      if ip is None or ip.lower() == constants.VALUE_NONE:
7678
        nic_ip = None
7679
      elif ip.lower() == constants.VALUE_AUTO:
7680
        if not self.op.name_check:
7681
          raise errors.OpPrereqError("IP address set to auto but name checks"
7682
                                     " have been skipped",
7683
                                     errors.ECODE_INVAL)
7684
        nic_ip = self.hostname1.ip
7685
      else:
7686
        if not netutils.IPAddress.IsValid(ip):
7687
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7688
                                     errors.ECODE_INVAL)
7689
        nic_ip = ip
7690

    
7691
      # TODO: check the ip address for uniqueness
7692
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7693
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7694
                                   errors.ECODE_INVAL)
7695

    
7696
      # MAC address verification
7697
      mac = nic.get("mac", constants.VALUE_AUTO)
7698
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7699
        mac = utils.NormalizeAndValidateMac(mac)
7700

    
7701
        try:
7702
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7703
        except errors.ReservationError:
7704
          raise errors.OpPrereqError("MAC address %s already in use"
7705
                                     " in cluster" % mac,
7706
                                     errors.ECODE_NOTUNIQUE)
7707

    
7708
      #  Build nic parameters
7709
      link = nic.get(constants.INIC_LINK, None)
7710
      nicparams = {}
7711
      if nic_mode_req:
7712
        nicparams[constants.NIC_MODE] = nic_mode_req
7713
      if link:
7714
        nicparams[constants.NIC_LINK] = link
7715

    
7716
      check_params = cluster.SimpleFillNIC(nicparams)
7717
      objects.NIC.CheckParameterSyntax(check_params)
7718
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7719

    
7720
    # disk checks/pre-build
7721
    self.disks = []
7722
    for disk in self.op.disks:
7723
      mode = disk.get("mode", constants.DISK_RDWR)
7724
      if mode not in constants.DISK_ACCESS_SET:
7725
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7726
                                   mode, errors.ECODE_INVAL)
7727
      size = disk.get("size", None)
7728
      if size is None:
7729
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7730
      try:
7731
        size = int(size)
7732
      except (TypeError, ValueError):
7733
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7734
                                   errors.ECODE_INVAL)
7735
      vg = disk.get("vg", self.cfg.GetVGName())
7736
      new_disk = {"size": size, "mode": mode, "vg": vg}
7737
      if "adopt" in disk:
7738
        new_disk["adopt"] = disk["adopt"]
7739
      self.disks.append(new_disk)
7740

    
7741
    if self.op.mode == constants.INSTANCE_IMPORT:
7742

    
7743
      # Check that the new instance doesn't have less disks than the export
7744
      instance_disks = len(self.disks)
7745
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7746
      if instance_disks < export_disks:
7747
        raise errors.OpPrereqError("Not enough disks to import."
7748
                                   " (instance: %d, export: %d)" %
7749
                                   (instance_disks, export_disks),
7750
                                   errors.ECODE_INVAL)
7751

    
7752
      disk_images = []
7753
      for idx in range(export_disks):
7754
        option = 'disk%d_dump' % idx
7755
        if export_info.has_option(constants.INISECT_INS, option):
7756
          # FIXME: are the old os-es, disk sizes, etc. useful?
7757
          export_name = export_info.get(constants.INISECT_INS, option)
7758
          image = utils.PathJoin(self.op.src_path, export_name)
7759
          disk_images.append(image)
7760
        else:
7761
          disk_images.append(False)
7762

    
7763
      self.src_images = disk_images
7764

    
7765
      old_name = export_info.get(constants.INISECT_INS, 'name')
7766
      try:
7767
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7768
      except (TypeError, ValueError), err:
7769
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7770
                                   " an integer: %s" % str(err),
7771
                                   errors.ECODE_STATE)
7772
      if self.op.instance_name == old_name:
7773
        for idx, nic in enumerate(self.nics):
7774
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7775
            nic_mac_ini = 'nic%d_mac' % idx
7776
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7777

    
7778
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7779

    
7780
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7781
    if self.op.ip_check:
7782
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7783
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7784
                                   (self.check_ip, self.op.instance_name),
7785
                                   errors.ECODE_NOTUNIQUE)
7786

    
7787
    #### mac address generation
7788
    # By generating here the mac address both the allocator and the hooks get
7789
    # the real final mac address rather than the 'auto' or 'generate' value.
7790
    # There is a race condition between the generation and the instance object
7791
    # creation, which means that we know the mac is valid now, but we're not
7792
    # sure it will be when we actually add the instance. If things go bad
7793
    # adding the instance will abort because of a duplicate mac, and the
7794
    # creation job will fail.
7795
    for nic in self.nics:
7796
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7797
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7798

    
7799
    #### allocator run
7800

    
7801
    if self.op.iallocator is not None:
7802
      self._RunAllocator()
7803

    
7804
    #### node related checks
7805

    
7806
    # check primary node
7807
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7808
    assert self.pnode is not None, \
7809
      "Cannot retrieve locked node %s" % self.op.pnode
7810
    if pnode.offline:
7811
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7812
                                 pnode.name, errors.ECODE_STATE)
7813
    if pnode.drained:
7814
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7815
                                 pnode.name, errors.ECODE_STATE)
7816
    if not pnode.vm_capable:
7817
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7818
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7819

    
7820
    self.secondaries = []
7821

    
7822
    # mirror node verification
7823
    if self.op.disk_template in constants.DTS_INT_MIRROR:
7824
      if self.op.snode == pnode.name:
7825
        raise errors.OpPrereqError("The secondary node cannot be the"
7826
                                   " primary node.", errors.ECODE_INVAL)
7827
      _CheckNodeOnline(self, self.op.snode)
7828
      _CheckNodeNotDrained(self, self.op.snode)
7829
      _CheckNodeVmCapable(self, self.op.snode)
7830
      self.secondaries.append(self.op.snode)
7831

    
7832
    nodenames = [pnode.name] + self.secondaries
7833

    
7834
    if not self.adopt_disks:
7835
      # Check lv size requirements, if not adopting
7836
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7837
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7838

    
7839
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
7840
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7841
      if len(all_lvs) != len(self.disks):
7842
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7843
                                   errors.ECODE_INVAL)
7844
      for lv_name in all_lvs:
7845
        try:
7846
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7847
          # to ReserveLV uses the same syntax
7848
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7849
        except errors.ReservationError:
7850
          raise errors.OpPrereqError("LV named %s used by another instance" %
7851
                                     lv_name, errors.ECODE_NOTUNIQUE)
7852

    
7853
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7854
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7855

    
7856
      node_lvs = self.rpc.call_lv_list([pnode.name],
7857
                                       vg_names.payload.keys())[pnode.name]
7858
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7859
      node_lvs = node_lvs.payload
7860

    
7861
      delta = all_lvs.difference(node_lvs.keys())
7862
      if delta:
7863
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7864
                                   utils.CommaJoin(delta),
7865
                                   errors.ECODE_INVAL)
7866
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7867
      if online_lvs:
7868
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7869
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7870
                                   errors.ECODE_STATE)
7871
      # update the size of disk based on what is found
7872
      for dsk in self.disks:
7873
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7874

    
7875
    elif self.op.disk_template == constants.DT_BLOCK:
7876
      # Normalize and de-duplicate device paths
7877
      all_disks = set([os.path.abspath(i["adopt"]) for i in self.disks])
7878
      if len(all_disks) != len(self.disks):
7879
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
7880
                                   errors.ECODE_INVAL)
7881
      baddisks = [d for d in all_disks
7882
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
7883
      if baddisks:
7884
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
7885
                                   " cannot be adopted" %
7886
                                   (", ".join(baddisks),
7887
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
7888
                                   errors.ECODE_INVAL)
7889

    
7890
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
7891
                                            list(all_disks))[pnode.name]
7892
      node_disks.Raise("Cannot get block device information from node %s" %
7893
                       pnode.name)
7894
      node_disks = node_disks.payload
7895
      delta = all_disks.difference(node_disks.keys())
7896
      if delta:
7897
        raise errors.OpPrereqError("Missing block device(s): %s" %
7898
                                   utils.CommaJoin(delta),
7899
                                   errors.ECODE_INVAL)
7900
      for dsk in self.disks:
7901
        dsk["size"] = int(float(node_disks[dsk["adopt"]]))
7902

    
7903
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7904

    
7905
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7906
    # check OS parameters (remotely)
7907
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7908

    
7909
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7910

    
7911
    # memory check on primary node
7912
    if self.op.start:
7913
      _CheckNodeFreeMemory(self, self.pnode.name,
7914
                           "creating instance %s" % self.op.instance_name,
7915
                           self.be_full[constants.BE_MEMORY],
7916
                           self.op.hypervisor)
7917

    
7918
    self.dry_run_result = list(nodenames)
7919

    
7920
  def Exec(self, feedback_fn):
7921
    """Create and add the instance to the cluster.
7922

7923
    """
7924
    instance = self.op.instance_name
7925
    pnode_name = self.pnode.name
7926

    
7927
    ht_kind = self.op.hypervisor
7928
    if ht_kind in constants.HTS_REQ_PORT:
7929
      network_port = self.cfg.AllocatePort()
7930
    else:
7931
      network_port = None
7932

    
7933
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
7934
      # this is needed because os.path.join does not accept None arguments
7935
      if self.op.file_storage_dir is None:
7936
        string_file_storage_dir = ""
7937
      else:
7938
        string_file_storage_dir = self.op.file_storage_dir
7939

    
7940
      # build the full file storage dir path
7941
      if self.op.disk_template == constants.DT_SHARED_FILE:
7942
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
7943
      else:
7944
        get_fsd_fn = self.cfg.GetFileStorageDir
7945

    
7946
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
7947
                                        string_file_storage_dir, instance)
7948
    else:
7949
      file_storage_dir = ""
7950

    
7951
    disks = _GenerateDiskTemplate(self,
7952
                                  self.op.disk_template,
7953
                                  instance, pnode_name,
7954
                                  self.secondaries,
7955
                                  self.disks,
7956
                                  file_storage_dir,
7957
                                  self.op.file_driver,
7958
                                  0,
7959
                                  feedback_fn)
7960

    
7961
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7962
                            primary_node=pnode_name,
7963
                            nics=self.nics, disks=disks,
7964
                            disk_template=self.op.disk_template,
7965
                            admin_up=False,
7966
                            network_port=network_port,
7967
                            beparams=self.op.beparams,
7968
                            hvparams=self.op.hvparams,
7969
                            hypervisor=self.op.hypervisor,
7970
                            osparams=self.op.osparams,
7971
                            )
7972

    
7973
    if self.adopt_disks:
7974
      if self.op.disk_template == constants.DT_PLAIN:
7975
        # rename LVs to the newly-generated names; we need to construct
7976
        # 'fake' LV disks with the old data, plus the new unique_id
7977
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7978
        rename_to = []
7979
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7980
          rename_to.append(t_dsk.logical_id)
7981
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7982
          self.cfg.SetDiskID(t_dsk, pnode_name)
7983
        result = self.rpc.call_blockdev_rename(pnode_name,
7984
                                               zip(tmp_disks, rename_to))
7985
        result.Raise("Failed to rename adoped LVs")
7986
    else:
7987
      feedback_fn("* creating instance disks...")
7988
      try:
7989
        _CreateDisks(self, iobj)
7990
      except errors.OpExecError:
7991
        self.LogWarning("Device creation failed, reverting...")
7992
        try:
7993
          _RemoveDisks(self, iobj)
7994
        finally:
7995
          self.cfg.ReleaseDRBDMinors(instance)
7996
          raise
7997

    
7998
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7999
        feedback_fn("* wiping instance disks...")
8000
        try:
8001
          _WipeDisks(self, iobj)
8002
        except errors.OpExecError:
8003
          self.LogWarning("Device wiping failed, reverting...")
8004
          try:
8005
            _RemoveDisks(self, iobj)
8006
          finally:
8007
            self.cfg.ReleaseDRBDMinors(instance)
8008
            raise
8009

    
8010
    feedback_fn("adding instance %s to cluster config" % instance)
8011

    
8012
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8013

    
8014
    # Declare that we don't want to remove the instance lock anymore, as we've
8015
    # added the instance to the config
8016
    del self.remove_locks[locking.LEVEL_INSTANCE]
8017
    # Unlock all the nodes
8018
    if self.op.mode == constants.INSTANCE_IMPORT:
8019
      nodes_keep = [self.op.src_node]
8020
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
8021
                       if node != self.op.src_node]
8022
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
8023
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
8024
    else:
8025
      self.context.glm.release(locking.LEVEL_NODE)
8026
      del self.acquired_locks[locking.LEVEL_NODE]
8027

    
8028
    if self.op.wait_for_sync:
8029
      disk_abort = not _WaitForSync(self, iobj)
8030
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8031
      # make sure the disks are not degraded (still sync-ing is ok)
8032
      time.sleep(15)
8033
      feedback_fn("* checking mirrors status")
8034
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8035
    else:
8036
      disk_abort = False
8037

    
8038
    if disk_abort:
8039
      _RemoveDisks(self, iobj)
8040
      self.cfg.RemoveInstance(iobj.name)
8041
      # Make sure the instance lock gets removed
8042
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8043
      raise errors.OpExecError("There are some degraded disks for"
8044
                               " this instance")
8045

    
8046
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8047
      if self.op.mode == constants.INSTANCE_CREATE:
8048
        if not self.op.no_install:
8049
          feedback_fn("* running the instance OS create scripts...")
8050
          # FIXME: pass debug option from opcode to backend
8051
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8052
                                                 self.op.debug_level)
8053
          result.Raise("Could not add os for instance %s"
8054
                       " on node %s" % (instance, pnode_name))
8055

    
8056
      elif self.op.mode == constants.INSTANCE_IMPORT:
8057
        feedback_fn("* running the instance OS import scripts...")
8058

    
8059
        transfers = []
8060

    
8061
        for idx, image in enumerate(self.src_images):
8062
          if not image:
8063
            continue
8064

    
8065
          # FIXME: pass debug option from opcode to backend
8066
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8067
                                             constants.IEIO_FILE, (image, ),
8068
                                             constants.IEIO_SCRIPT,
8069
                                             (iobj.disks[idx], idx),
8070
                                             None)
8071
          transfers.append(dt)
8072

    
8073
        import_result = \
8074
          masterd.instance.TransferInstanceData(self, feedback_fn,
8075
                                                self.op.src_node, pnode_name,
8076
                                                self.pnode.secondary_ip,
8077
                                                iobj, transfers)
8078
        if not compat.all(import_result):
8079
          self.LogWarning("Some disks for instance %s on node %s were not"
8080
                          " imported successfully" % (instance, pnode_name))
8081

    
8082
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8083
        feedback_fn("* preparing remote import...")
8084
        # The source cluster will stop the instance before attempting to make a
8085
        # connection. In some cases stopping an instance can take a long time,
8086
        # hence the shutdown timeout is added to the connection timeout.
8087
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8088
                           self.op.source_shutdown_timeout)
8089
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8090

    
8091
        assert iobj.primary_node == self.pnode.name
8092
        disk_results = \
8093
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8094
                                        self.source_x509_ca,
8095
                                        self._cds, timeouts)
8096
        if not compat.all(disk_results):
8097
          # TODO: Should the instance still be started, even if some disks
8098
          # failed to import (valid for local imports, too)?
8099
          self.LogWarning("Some disks for instance %s on node %s were not"
8100
                          " imported successfully" % (instance, pnode_name))
8101

    
8102
        # Run rename script on newly imported instance
8103
        assert iobj.name == instance
8104
        feedback_fn("Running rename script for %s" % instance)
8105
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8106
                                                   self.source_instance_name,
8107
                                                   self.op.debug_level)
8108
        if result.fail_msg:
8109
          self.LogWarning("Failed to run rename script for %s on node"
8110
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8111

    
8112
      else:
8113
        # also checked in the prereq part
8114
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8115
                                     % self.op.mode)
8116

    
8117
    if self.op.start:
8118
      iobj.admin_up = True
8119
      self.cfg.Update(iobj, feedback_fn)
8120
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8121
      feedback_fn("* starting instance...")
8122
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8123
      result.Raise("Could not start instance")
8124

    
8125
    return list(iobj.all_nodes)
8126

    
8127

    
8128
class LUInstanceConsole(NoHooksLU):
8129
  """Connect to an instance's console.
8130

8131
  This is somewhat special in that it returns the command line that
8132
  you need to run on the master node in order to connect to the
8133
  console.
8134

8135
  """
8136
  REQ_BGL = False
8137

    
8138
  def ExpandNames(self):
8139
    self._ExpandAndLockInstance()
8140

    
8141
  def CheckPrereq(self):
8142
    """Check prerequisites.
8143

8144
    This checks that the instance is in the cluster.
8145

8146
    """
8147
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8148
    assert self.instance is not None, \
8149
      "Cannot retrieve locked instance %s" % self.op.instance_name
8150
    _CheckNodeOnline(self, self.instance.primary_node)
8151

    
8152
  def Exec(self, feedback_fn):
8153
    """Connect to the console of an instance
8154

8155
    """
8156
    instance = self.instance
8157
    node = instance.primary_node
8158

    
8159
    node_insts = self.rpc.call_instance_list([node],
8160
                                             [instance.hypervisor])[node]
8161
    node_insts.Raise("Can't get node information from %s" % node)
8162

    
8163
    if instance.name not in node_insts.payload:
8164
      if instance.admin_up:
8165
        state = constants.INSTST_ERRORDOWN
8166
      else:
8167
        state = constants.INSTST_ADMINDOWN
8168
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8169
                               (instance.name, state))
8170

    
8171
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8172

    
8173
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8174

    
8175

    
8176
def _GetInstanceConsole(cluster, instance):
8177
  """Returns console information for an instance.
8178

8179
  @type cluster: L{objects.Cluster}
8180
  @type instance: L{objects.Instance}
8181
  @rtype: dict
8182

8183
  """
8184
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8185
  # beparams and hvparams are passed separately, to avoid editing the
8186
  # instance and then saving the defaults in the instance itself.
8187
  hvparams = cluster.FillHV(instance)
8188
  beparams = cluster.FillBE(instance)
8189
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8190

    
8191
  assert console.instance == instance.name
8192
  assert console.Validate()
8193

    
8194
  return console.ToDict()
8195

    
8196

    
8197
class LUInstanceReplaceDisks(LogicalUnit):
8198
  """Replace the disks of an instance.
8199

8200
  """
8201
  HPATH = "mirrors-replace"
8202
  HTYPE = constants.HTYPE_INSTANCE
8203
  REQ_BGL = False
8204

    
8205
  def CheckArguments(self):
8206
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8207
                                  self.op.iallocator)
8208

    
8209
  def ExpandNames(self):
8210
    self._ExpandAndLockInstance()
8211

    
8212
    if self.op.iallocator is not None:
8213
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8214

    
8215
    elif self.op.remote_node is not None:
8216
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8217
      self.op.remote_node = remote_node
8218

    
8219
      # Warning: do not remove the locking of the new secondary here
8220
      # unless DRBD8.AddChildren is changed to work in parallel;
8221
      # currently it doesn't since parallel invocations of
8222
      # FindUnusedMinor will conflict
8223
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
8224
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8225

    
8226
    else:
8227
      self.needed_locks[locking.LEVEL_NODE] = []
8228
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8229

    
8230
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8231
                                   self.op.iallocator, self.op.remote_node,
8232
                                   self.op.disks, False, self.op.early_release)
8233

    
8234
    self.tasklets = [self.replacer]
8235

    
8236
  def DeclareLocks(self, level):
8237
    # If we're not already locking all nodes in the set we have to declare the
8238
    # instance's primary/secondary nodes.
8239
    if (level == locking.LEVEL_NODE and
8240
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
8241
      self._LockInstancesNodes()
8242

    
8243
  def BuildHooksEnv(self):
8244
    """Build hooks env.
8245

8246
    This runs on the master, the primary and all the secondaries.
8247

8248
    """
8249
    instance = self.replacer.instance
8250
    env = {
8251
      "MODE": self.op.mode,
8252
      "NEW_SECONDARY": self.op.remote_node,
8253
      "OLD_SECONDARY": instance.secondary_nodes[0],
8254
      }
8255
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8256
    nl = [
8257
      self.cfg.GetMasterNode(),
8258
      instance.primary_node,
8259
      ]
8260
    if self.op.remote_node is not None:
8261
      nl.append(self.op.remote_node)
8262
    return env, nl, nl
8263

    
8264

    
8265
class TLReplaceDisks(Tasklet):
8266
  """Replaces disks for an instance.
8267

8268
  Note: Locking is not within the scope of this class.
8269

8270
  """
8271
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8272
               disks, delay_iallocator, early_release):
8273
    """Initializes this class.
8274

8275
    """
8276
    Tasklet.__init__(self, lu)
8277

    
8278
    # Parameters
8279
    self.instance_name = instance_name
8280
    self.mode = mode
8281
    self.iallocator_name = iallocator_name
8282
    self.remote_node = remote_node
8283
    self.disks = disks
8284
    self.delay_iallocator = delay_iallocator
8285
    self.early_release = early_release
8286

    
8287
    # Runtime data
8288
    self.instance = None
8289
    self.new_node = None
8290
    self.target_node = None
8291
    self.other_node = None
8292
    self.remote_node_info = None
8293
    self.node_secondary_ip = None
8294

    
8295
  @staticmethod
8296
  def CheckArguments(mode, remote_node, iallocator):
8297
    """Helper function for users of this class.
8298

8299
    """
8300
    # check for valid parameter combination
8301
    if mode == constants.REPLACE_DISK_CHG:
8302
      if remote_node is None and iallocator is None:
8303
        raise errors.OpPrereqError("When changing the secondary either an"
8304
                                   " iallocator script must be used or the"
8305
                                   " new node given", errors.ECODE_INVAL)
8306

    
8307
      if remote_node is not None and iallocator is not None:
8308
        raise errors.OpPrereqError("Give either the iallocator or the new"
8309
                                   " secondary, not both", errors.ECODE_INVAL)
8310

    
8311
    elif remote_node is not None or iallocator is not None:
8312
      # Not replacing the secondary
8313
      raise errors.OpPrereqError("The iallocator and new node options can"
8314
                                 " only be used when changing the"
8315
                                 " secondary node", errors.ECODE_INVAL)
8316

    
8317
  @staticmethod
8318
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8319
    """Compute a new secondary node using an IAllocator.
8320

8321
    """
8322
    ial = IAllocator(lu.cfg, lu.rpc,
8323
                     mode=constants.IALLOCATOR_MODE_RELOC,
8324
                     name=instance_name,
8325
                     relocate_from=relocate_from)
8326

    
8327
    ial.Run(iallocator_name)
8328

    
8329
    if not ial.success:
8330
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8331
                                 " %s" % (iallocator_name, ial.info),
8332
                                 errors.ECODE_NORES)
8333

    
8334
    if len(ial.result) != ial.required_nodes:
8335
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8336
                                 " of nodes (%s), required %s" %
8337
                                 (iallocator_name,
8338
                                  len(ial.result), ial.required_nodes),
8339
                                 errors.ECODE_FAULT)
8340

    
8341
    remote_node_name = ial.result[0]
8342

    
8343
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8344
               instance_name, remote_node_name)
8345

    
8346
    return remote_node_name
8347

    
8348
  def _FindFaultyDisks(self, node_name):
8349
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8350
                                    node_name, True)
8351

    
8352
  def _CheckDisksActivated(self, instance):
8353
    """Checks if the instance disks are activated.
8354

8355
    @param instance: The instance to check disks
8356
    @return: True if they are activated, False otherwise
8357

8358
    """
8359
    nodes = instance.all_nodes
8360

    
8361
    for idx, dev in enumerate(instance.disks):
8362
      for node in nodes:
8363
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
8364
        self.cfg.SetDiskID(dev, node)
8365

    
8366
        result = self.rpc.call_blockdev_find(node, dev)
8367

    
8368
        if result.offline:
8369
          continue
8370
        elif result.fail_msg or not result.payload:
8371
          return False
8372

    
8373
    return True
8374

    
8375

    
8376
  def CheckPrereq(self):
8377
    """Check prerequisites.
8378

8379
    This checks that the instance is in the cluster.
8380

8381
    """
8382
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8383
    assert instance is not None, \
8384
      "Cannot retrieve locked instance %s" % self.instance_name
8385

    
8386
    if instance.disk_template != constants.DT_DRBD8:
8387
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8388
                                 " instances", errors.ECODE_INVAL)
8389

    
8390
    if len(instance.secondary_nodes) != 1:
8391
      raise errors.OpPrereqError("The instance has a strange layout,"
8392
                                 " expected one secondary but found %d" %
8393
                                 len(instance.secondary_nodes),
8394
                                 errors.ECODE_FAULT)
8395

    
8396
    if not self.delay_iallocator:
8397
      self._CheckPrereq2()
8398

    
8399
  def _CheckPrereq2(self):
8400
    """Check prerequisites, second part.
8401

8402
    This function should always be part of CheckPrereq. It was separated and is
8403
    now called from Exec because during node evacuation iallocator was only
8404
    called with an unmodified cluster model, not taking planned changes into
8405
    account.
8406

8407
    """
8408
    instance = self.instance
8409
    secondary_node = instance.secondary_nodes[0]
8410

    
8411
    if self.iallocator_name is None:
8412
      remote_node = self.remote_node
8413
    else:
8414
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8415
                                       instance.name, instance.secondary_nodes)
8416

    
8417
    if remote_node is not None:
8418
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8419
      assert self.remote_node_info is not None, \
8420
        "Cannot retrieve locked node %s" % remote_node
8421
    else:
8422
      self.remote_node_info = None
8423

    
8424
    if remote_node == self.instance.primary_node:
8425
      raise errors.OpPrereqError("The specified node is the primary node of"
8426
                                 " the instance.", errors.ECODE_INVAL)
8427

    
8428
    if remote_node == secondary_node:
8429
      raise errors.OpPrereqError("The specified node is already the"
8430
                                 " secondary node of the instance.",
8431
                                 errors.ECODE_INVAL)
8432

    
8433
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8434
                                    constants.REPLACE_DISK_CHG):
8435
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8436
                                 errors.ECODE_INVAL)
8437

    
8438
    if self.mode == constants.REPLACE_DISK_AUTO:
8439
      if not self._CheckDisksActivated(instance):
8440
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
8441
                                   " first" % self.instance_name,
8442
                                   errors.ECODE_STATE)
8443
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8444
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8445

    
8446
      if faulty_primary and faulty_secondary:
8447
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8448
                                   " one node and can not be repaired"
8449
                                   " automatically" % self.instance_name,
8450
                                   errors.ECODE_STATE)
8451

    
8452
      if faulty_primary:
8453
        self.disks = faulty_primary
8454
        self.target_node = instance.primary_node
8455
        self.other_node = secondary_node
8456
        check_nodes = [self.target_node, self.other_node]
8457
      elif faulty_secondary:
8458
        self.disks = faulty_secondary
8459
        self.target_node = secondary_node
8460
        self.other_node = instance.primary_node
8461
        check_nodes = [self.target_node, self.other_node]
8462
      else:
8463
        self.disks = []
8464
        check_nodes = []
8465

    
8466
    else:
8467
      # Non-automatic modes
8468
      if self.mode == constants.REPLACE_DISK_PRI:
8469
        self.target_node = instance.primary_node
8470
        self.other_node = secondary_node
8471
        check_nodes = [self.target_node, self.other_node]
8472

    
8473
      elif self.mode == constants.REPLACE_DISK_SEC:
8474
        self.target_node = secondary_node
8475
        self.other_node = instance.primary_node
8476
        check_nodes = [self.target_node, self.other_node]
8477

    
8478
      elif self.mode == constants.REPLACE_DISK_CHG:
8479
        self.new_node = remote_node
8480
        self.other_node = instance.primary_node
8481
        self.target_node = secondary_node
8482
        check_nodes = [self.new_node, self.other_node]
8483

    
8484
        _CheckNodeNotDrained(self.lu, remote_node)
8485
        _CheckNodeVmCapable(self.lu, remote_node)
8486

    
8487
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8488
        assert old_node_info is not None
8489
        if old_node_info.offline and not self.early_release:
8490
          # doesn't make sense to delay the release
8491
          self.early_release = True
8492
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8493
                          " early-release mode", secondary_node)
8494

    
8495
      else:
8496
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8497
                                     self.mode)
8498

    
8499
      # If not specified all disks should be replaced
8500
      if not self.disks:
8501
        self.disks = range(len(self.instance.disks))
8502

    
8503
    for node in check_nodes:
8504
      _CheckNodeOnline(self.lu, node)
8505

    
8506
    # Check whether disks are valid
8507
    for disk_idx in self.disks:
8508
      instance.FindDisk(disk_idx)
8509

    
8510
    # Get secondary node IP addresses
8511
    node_2nd_ip = {}
8512

    
8513
    for node_name in [self.target_node, self.other_node, self.new_node]:
8514
      if node_name is not None:
8515
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8516

    
8517
    self.node_secondary_ip = node_2nd_ip
8518

    
8519
  def Exec(self, feedback_fn):
8520
    """Execute disk replacement.
8521

8522
    This dispatches the disk replacement to the appropriate handler.
8523

8524
    """
8525
    if self.delay_iallocator:
8526
      self._CheckPrereq2()
8527

    
8528
    if not self.disks:
8529
      feedback_fn("No disks need replacement")
8530
      return
8531

    
8532
    feedback_fn("Replacing disk(s) %s for %s" %
8533
                (utils.CommaJoin(self.disks), self.instance.name))
8534

    
8535
    activate_disks = (not self.instance.admin_up)
8536

    
8537
    # Activate the instance disks if we're replacing them on a down instance
8538
    if activate_disks:
8539
      _StartInstanceDisks(self.lu, self.instance, True)
8540

    
8541
    try:
8542
      # Should we replace the secondary node?
8543
      if self.new_node is not None:
8544
        fn = self._ExecDrbd8Secondary
8545
      else:
8546
        fn = self._ExecDrbd8DiskOnly
8547

    
8548
      return fn(feedback_fn)
8549

    
8550
    finally:
8551
      # Deactivate the instance disks if we're replacing them on a
8552
      # down instance
8553
      if activate_disks:
8554
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8555

    
8556
  def _CheckVolumeGroup(self, nodes):
8557
    self.lu.LogInfo("Checking volume groups")
8558

    
8559
    vgname = self.cfg.GetVGName()
8560

    
8561
    # Make sure volume group exists on all involved nodes
8562
    results = self.rpc.call_vg_list(nodes)
8563
    if not results:
8564
      raise errors.OpExecError("Can't list volume groups on the nodes")
8565

    
8566
    for node in nodes:
8567
      res = results[node]
8568
      res.Raise("Error checking node %s" % node)
8569
      if vgname not in res.payload:
8570
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8571
                                 (vgname, node))
8572

    
8573
  def _CheckDisksExistence(self, nodes):
8574
    # Check disk existence
8575
    for idx, dev in enumerate(self.instance.disks):
8576
      if idx not in self.disks:
8577
        continue
8578

    
8579
      for node in nodes:
8580
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8581
        self.cfg.SetDiskID(dev, node)
8582

    
8583
        result = self.rpc.call_blockdev_find(node, dev)
8584

    
8585
        msg = result.fail_msg
8586
        if msg or not result.payload:
8587
          if not msg:
8588
            msg = "disk not found"
8589
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8590
                                   (idx, node, msg))
8591

    
8592
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8593
    for idx, dev in enumerate(self.instance.disks):
8594
      if idx not in self.disks:
8595
        continue
8596

    
8597
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8598
                      (idx, node_name))
8599

    
8600
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8601
                                   ldisk=ldisk):
8602
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8603
                                 " replace disks for instance %s" %
8604
                                 (node_name, self.instance.name))
8605

    
8606
  def _CreateNewStorage(self, node_name):
8607
    vgname = self.cfg.GetVGName()
8608
    iv_names = {}
8609

    
8610
    for idx, dev in enumerate(self.instance.disks):
8611
      if idx not in self.disks:
8612
        continue
8613

    
8614
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8615

    
8616
      self.cfg.SetDiskID(dev, node_name)
8617

    
8618
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8619
      names = _GenerateUniqueNames(self.lu, lv_names)
8620

    
8621
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8622
                             logical_id=(vgname, names[0]))
8623
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8624
                             logical_id=(vgname, names[1]))
8625

    
8626
      new_lvs = [lv_data, lv_meta]
8627
      old_lvs = dev.children
8628
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8629

    
8630
      # we pass force_create=True to force the LVM creation
8631
      for new_lv in new_lvs:
8632
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8633
                        _GetInstanceInfoText(self.instance), False)
8634

    
8635
    return iv_names
8636

    
8637
  def _CheckDevices(self, node_name, iv_names):
8638
    for name, (dev, _, _) in iv_names.iteritems():
8639
      self.cfg.SetDiskID(dev, node_name)
8640

    
8641
      result = self.rpc.call_blockdev_find(node_name, dev)
8642

    
8643
      msg = result.fail_msg
8644
      if msg or not result.payload:
8645
        if not msg:
8646
          msg = "disk not found"
8647
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8648
                                 (name, msg))
8649

    
8650
      if result.payload.is_degraded:
8651
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8652

    
8653
  def _RemoveOldStorage(self, node_name, iv_names):
8654
    for name, (_, old_lvs, _) in iv_names.iteritems():
8655
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8656

    
8657
      for lv in old_lvs:
8658
        self.cfg.SetDiskID(lv, node_name)
8659

    
8660
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8661
        if msg:
8662
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8663
                             hint="remove unused LVs manually")
8664

    
8665
  def _ReleaseNodeLock(self, node_name):
8666
    """Releases the lock for a given node."""
8667
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8668

    
8669
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8670
    """Replace a disk on the primary or secondary for DRBD 8.
8671

8672
    The algorithm for replace is quite complicated:
8673

8674
      1. for each disk to be replaced:
8675

8676
        1. create new LVs on the target node with unique names
8677
        1. detach old LVs from the drbd device
8678
        1. rename old LVs to name_replaced.<time_t>
8679
        1. rename new LVs to old LVs
8680
        1. attach the new LVs (with the old names now) to the drbd device
8681

8682
      1. wait for sync across all devices
8683

8684
      1. for each modified disk:
8685

8686
        1. remove old LVs (which have the name name_replaces.<time_t>)
8687

8688
    Failures are not very well handled.
8689

8690
    """
8691
    steps_total = 6
8692

    
8693
    # Step: check device activation
8694
    self.lu.LogStep(1, steps_total, "Check device existence")
8695
    self._CheckDisksExistence([self.other_node, self.target_node])
8696
    self._CheckVolumeGroup([self.target_node, self.other_node])
8697

    
8698
    # Step: check other node consistency
8699
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8700
    self._CheckDisksConsistency(self.other_node,
8701
                                self.other_node == self.instance.primary_node,
8702
                                False)
8703

    
8704
    # Step: create new storage
8705
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8706
    iv_names = self._CreateNewStorage(self.target_node)
8707

    
8708
    # Step: for each lv, detach+rename*2+attach
8709
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8710
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8711
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8712

    
8713
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8714
                                                     old_lvs)
8715
      result.Raise("Can't detach drbd from local storage on node"
8716
                   " %s for device %s" % (self.target_node, dev.iv_name))
8717
      #dev.children = []
8718
      #cfg.Update(instance)
8719

    
8720
      # ok, we created the new LVs, so now we know we have the needed
8721
      # storage; as such, we proceed on the target node to rename
8722
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8723
      # using the assumption that logical_id == physical_id (which in
8724
      # turn is the unique_id on that node)
8725

    
8726
      # FIXME(iustin): use a better name for the replaced LVs
8727
      temp_suffix = int(time.time())
8728
      ren_fn = lambda d, suff: (d.physical_id[0],
8729
                                d.physical_id[1] + "_replaced-%s" % suff)
8730

    
8731
      # Build the rename list based on what LVs exist on the node
8732
      rename_old_to_new = []
8733
      for to_ren in old_lvs:
8734
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8735
        if not result.fail_msg and result.payload:
8736
          # device exists
8737
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8738

    
8739
      self.lu.LogInfo("Renaming the old LVs on the target node")
8740
      result = self.rpc.call_blockdev_rename(self.target_node,
8741
                                             rename_old_to_new)
8742
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8743

    
8744
      # Now we rename the new LVs to the old LVs
8745
      self.lu.LogInfo("Renaming the new LVs on the target node")
8746
      rename_new_to_old = [(new, old.physical_id)
8747
                           for old, new in zip(old_lvs, new_lvs)]
8748
      result = self.rpc.call_blockdev_rename(self.target_node,
8749
                                             rename_new_to_old)
8750
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8751

    
8752
      for old, new in zip(old_lvs, new_lvs):
8753
        new.logical_id = old.logical_id
8754
        self.cfg.SetDiskID(new, self.target_node)
8755

    
8756
      for disk in old_lvs:
8757
        disk.logical_id = ren_fn(disk, temp_suffix)
8758
        self.cfg.SetDiskID(disk, self.target_node)
8759

    
8760
      # Now that the new lvs have the old name, we can add them to the device
8761
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8762
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8763
                                                  new_lvs)
8764
      msg = result.fail_msg
8765
      if msg:
8766
        for new_lv in new_lvs:
8767
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8768
                                               new_lv).fail_msg
8769
          if msg2:
8770
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8771
                               hint=("cleanup manually the unused logical"
8772
                                     "volumes"))
8773
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8774

    
8775
      dev.children = new_lvs
8776

    
8777
      self.cfg.Update(self.instance, feedback_fn)
8778

    
8779
    cstep = 5
8780
    if self.early_release:
8781
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8782
      cstep += 1
8783
      self._RemoveOldStorage(self.target_node, iv_names)
8784
      # WARNING: we release both node locks here, do not do other RPCs
8785
      # than WaitForSync to the primary node
8786
      self._ReleaseNodeLock([self.target_node, self.other_node])
8787

    
8788
    # Wait for sync
8789
    # This can fail as the old devices are degraded and _WaitForSync
8790
    # does a combined result over all disks, so we don't check its return value
8791
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8792
    cstep += 1
8793
    _WaitForSync(self.lu, self.instance)
8794

    
8795
    # Check all devices manually
8796
    self._CheckDevices(self.instance.primary_node, iv_names)
8797

    
8798
    # Step: remove old storage
8799
    if not self.early_release:
8800
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8801
      cstep += 1
8802
      self._RemoveOldStorage(self.target_node, iv_names)
8803

    
8804
  def _ExecDrbd8Secondary(self, feedback_fn):
8805
    """Replace the secondary node for DRBD 8.
8806

8807
    The algorithm for replace is quite complicated:
8808
      - for all disks of the instance:
8809
        - create new LVs on the new node with same names
8810
        - shutdown the drbd device on the old secondary
8811
        - disconnect the drbd network on the primary
8812
        - create the drbd device on the new secondary
8813
        - network attach the drbd on the primary, using an artifice:
8814
          the drbd code for Attach() will connect to the network if it
8815
          finds a device which is connected to the good local disks but
8816
          not network enabled
8817
      - wait for sync across all devices
8818
      - remove all disks from the old secondary
8819

8820
    Failures are not very well handled.
8821

8822
    """
8823
    steps_total = 6
8824

    
8825
    # Step: check device activation
8826
    self.lu.LogStep(1, steps_total, "Check device existence")
8827
    self._CheckDisksExistence([self.instance.primary_node])
8828
    self._CheckVolumeGroup([self.instance.primary_node])
8829

    
8830
    # Step: check other node consistency
8831
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8832
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8833

    
8834
    # Step: create new storage
8835
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8836
    for idx, dev in enumerate(self.instance.disks):
8837
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8838
                      (self.new_node, idx))
8839
      # we pass force_create=True to force LVM creation
8840
      for new_lv in dev.children:
8841
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8842
                        _GetInstanceInfoText(self.instance), False)
8843

    
8844
    # Step 4: dbrd minors and drbd setups changes
8845
    # after this, we must manually remove the drbd minors on both the
8846
    # error and the success paths
8847
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8848
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8849
                                         for dev in self.instance.disks],
8850
                                        self.instance.name)
8851
    logging.debug("Allocated minors %r", minors)
8852

    
8853
    iv_names = {}
8854
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8855
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8856
                      (self.new_node, idx))
8857
      # create new devices on new_node; note that we create two IDs:
8858
      # one without port, so the drbd will be activated without
8859
      # networking information on the new node at this stage, and one
8860
      # with network, for the latter activation in step 4
8861
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8862
      if self.instance.primary_node == o_node1:
8863
        p_minor = o_minor1
8864
      else:
8865
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8866
        p_minor = o_minor2
8867

    
8868
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8869
                      p_minor, new_minor, o_secret)
8870
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8871
                    p_minor, new_minor, o_secret)
8872

    
8873
      iv_names[idx] = (dev, dev.children, new_net_id)
8874
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8875
                    new_net_id)
8876
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8877
                              logical_id=new_alone_id,
8878
                              children=dev.children,
8879
                              size=dev.size)
8880
      try:
8881
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8882
                              _GetInstanceInfoText(self.instance), False)
8883
      except errors.GenericError:
8884
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8885
        raise
8886

    
8887
    # We have new devices, shutdown the drbd on the old secondary
8888
    for idx, dev in enumerate(self.instance.disks):
8889
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8890
      self.cfg.SetDiskID(dev, self.target_node)
8891
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8892
      if msg:
8893
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8894
                           "node: %s" % (idx, msg),
8895
                           hint=("Please cleanup this device manually as"
8896
                                 " soon as possible"))
8897

    
8898
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8899
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8900
                                               self.node_secondary_ip,
8901
                                               self.instance.disks)\
8902
                                              [self.instance.primary_node]
8903

    
8904
    msg = result.fail_msg
8905
    if msg:
8906
      # detaches didn't succeed (unlikely)
8907
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8908
      raise errors.OpExecError("Can't detach the disks from the network on"
8909
                               " old node: %s" % (msg,))
8910

    
8911
    # if we managed to detach at least one, we update all the disks of
8912
    # the instance to point to the new secondary
8913
    self.lu.LogInfo("Updating instance configuration")
8914
    for dev, _, new_logical_id in iv_names.itervalues():
8915
      dev.logical_id = new_logical_id
8916
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8917

    
8918
    self.cfg.Update(self.instance, feedback_fn)
8919

    
8920
    # and now perform the drbd attach
8921
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8922
                    " (standalone => connected)")
8923
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8924
                                            self.new_node],
8925
                                           self.node_secondary_ip,
8926
                                           self.instance.disks,
8927
                                           self.instance.name,
8928
                                           False)
8929
    for to_node, to_result in result.items():
8930
      msg = to_result.fail_msg
8931
      if msg:
8932
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8933
                           to_node, msg,
8934
                           hint=("please do a gnt-instance info to see the"
8935
                                 " status of disks"))
8936
    cstep = 5
8937
    if self.early_release:
8938
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8939
      cstep += 1
8940
      self._RemoveOldStorage(self.target_node, iv_names)
8941
      # WARNING: we release all node locks here, do not do other RPCs
8942
      # than WaitForSync to the primary node
8943
      self._ReleaseNodeLock([self.instance.primary_node,
8944
                             self.target_node,
8945
                             self.new_node])
8946

    
8947
    # Wait for sync
8948
    # This can fail as the old devices are degraded and _WaitForSync
8949
    # does a combined result over all disks, so we don't check its return value
8950
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8951
    cstep += 1
8952
    _WaitForSync(self.lu, self.instance)
8953

    
8954
    # Check all devices manually
8955
    self._CheckDevices(self.instance.primary_node, iv_names)
8956

    
8957
    # Step: remove old storage
8958
    if not self.early_release:
8959
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8960
      self._RemoveOldStorage(self.target_node, iv_names)
8961

    
8962

    
8963
class LURepairNodeStorage(NoHooksLU):
8964
  """Repairs the volume group on a node.
8965

8966
  """
8967
  REQ_BGL = False
8968

    
8969
  def CheckArguments(self):
8970
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8971

    
8972
    storage_type = self.op.storage_type
8973

    
8974
    if (constants.SO_FIX_CONSISTENCY not in
8975
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8976
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8977
                                 " repaired" % storage_type,
8978
                                 errors.ECODE_INVAL)
8979

    
8980
  def ExpandNames(self):
8981
    self.needed_locks = {
8982
      locking.LEVEL_NODE: [self.op.node_name],
8983
      }
8984

    
8985
  def _CheckFaultyDisks(self, instance, node_name):
8986
    """Ensure faulty disks abort the opcode or at least warn."""
8987
    try:
8988
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8989
                                  node_name, True):
8990
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8991
                                   " node '%s'" % (instance.name, node_name),
8992
                                   errors.ECODE_STATE)
8993
    except errors.OpPrereqError, err:
8994
      if self.op.ignore_consistency:
8995
        self.proc.LogWarning(str(err.args[0]))
8996
      else:
8997
        raise
8998

    
8999
  def CheckPrereq(self):
9000
    """Check prerequisites.
9001

9002
    """
9003
    # Check whether any instance on this node has faulty disks
9004
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9005
      if not inst.admin_up:
9006
        continue
9007
      check_nodes = set(inst.all_nodes)
9008
      check_nodes.discard(self.op.node_name)
9009
      for inst_node_name in check_nodes:
9010
        self._CheckFaultyDisks(inst, inst_node_name)
9011

    
9012
  def Exec(self, feedback_fn):
9013
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9014
                (self.op.name, self.op.node_name))
9015

    
9016
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9017
    result = self.rpc.call_storage_execute(self.op.node_name,
9018
                                           self.op.storage_type, st_args,
9019
                                           self.op.name,
9020
                                           constants.SO_FIX_CONSISTENCY)
9021
    result.Raise("Failed to repair storage unit '%s' on %s" %
9022
                 (self.op.name, self.op.node_name))
9023

    
9024

    
9025
class LUNodeEvacStrategy(NoHooksLU):
9026
  """Computes the node evacuation strategy.
9027

9028
  """
9029
  REQ_BGL = False
9030

    
9031
  def CheckArguments(self):
9032
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9033

    
9034
  def ExpandNames(self):
9035
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9036
    self.needed_locks = locks = {}
9037
    if self.op.remote_node is None:
9038
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9039
    else:
9040
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9041
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9042

    
9043
  def Exec(self, feedback_fn):
9044
    if self.op.remote_node is not None:
9045
      instances = []
9046
      for node in self.op.nodes:
9047
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9048
      result = []
9049
      for i in instances:
9050
        if i.primary_node == self.op.remote_node:
9051
          raise errors.OpPrereqError("Node %s is the primary node of"
9052
                                     " instance %s, cannot use it as"
9053
                                     " secondary" %
9054
                                     (self.op.remote_node, i.name),
9055
                                     errors.ECODE_INVAL)
9056
        result.append([i.name, self.op.remote_node])
9057
    else:
9058
      ial = IAllocator(self.cfg, self.rpc,
9059
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9060
                       evac_nodes=self.op.nodes)
9061
      ial.Run(self.op.iallocator, validate=True)
9062
      if not ial.success:
9063
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9064
                                 errors.ECODE_NORES)
9065
      result = ial.result
9066
    return result
9067

    
9068

    
9069
class LUInstanceGrowDisk(LogicalUnit):
9070
  """Grow a disk of an instance.
9071

9072
  """
9073
  HPATH = "disk-grow"
9074
  HTYPE = constants.HTYPE_INSTANCE
9075
  REQ_BGL = False
9076

    
9077
  def ExpandNames(self):
9078
    self._ExpandAndLockInstance()
9079
    self.needed_locks[locking.LEVEL_NODE] = []
9080
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9081

    
9082
  def DeclareLocks(self, level):
9083
    if level == locking.LEVEL_NODE:
9084
      self._LockInstancesNodes()
9085

    
9086
  def BuildHooksEnv(self):
9087
    """Build hooks env.
9088

9089
    This runs on the master, the primary and all the secondaries.
9090

9091
    """
9092
    env = {
9093
      "DISK": self.op.disk,
9094
      "AMOUNT": self.op.amount,
9095
      }
9096
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9097
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9098
    return env, nl, nl
9099

    
9100
  def CheckPrereq(self):
9101
    """Check prerequisites.
9102

9103
    This checks that the instance is in the cluster.
9104

9105
    """
9106
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9107
    assert instance is not None, \
9108
      "Cannot retrieve locked instance %s" % self.op.instance_name
9109
    nodenames = list(instance.all_nodes)
9110
    for node in nodenames:
9111
      _CheckNodeOnline(self, node)
9112

    
9113
    self.instance = instance
9114

    
9115
    if instance.disk_template not in constants.DTS_GROWABLE:
9116
      raise errors.OpPrereqError("Instance's disk layout does not support"
9117
                                 " growing.", errors.ECODE_INVAL)
9118

    
9119
    self.disk = instance.FindDisk(self.op.disk)
9120

    
9121
    if instance.disk_template not in (constants.DT_FILE,
9122
                                      constants.DT_SHARED_FILE):
9123
      # TODO: check the free disk space for file, when that feature will be
9124
      # supported
9125
      _CheckNodesFreeDiskPerVG(self, nodenames,
9126
                               self.disk.ComputeGrowth(self.op.amount))
9127

    
9128
  def Exec(self, feedback_fn):
9129
    """Execute disk grow.
9130

9131
    """
9132
    instance = self.instance
9133
    disk = self.disk
9134

    
9135
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9136
    if not disks_ok:
9137
      raise errors.OpExecError("Cannot activate block device to grow")
9138

    
9139
    for node in instance.all_nodes:
9140
      self.cfg.SetDiskID(disk, node)
9141
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
9142
      result.Raise("Grow request failed to node %s" % node)
9143

    
9144
      # TODO: Rewrite code to work properly
9145
      # DRBD goes into sync mode for a short amount of time after executing the
9146
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9147
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9148
      # time is a work-around.
9149
      time.sleep(5)
9150

    
9151
    disk.RecordGrow(self.op.amount)
9152
    self.cfg.Update(instance, feedback_fn)
9153
    if self.op.wait_for_sync:
9154
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9155
      if disk_abort:
9156
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
9157
                             " status.\nPlease check the instance.")
9158
      if not instance.admin_up:
9159
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9160
    elif not instance.admin_up:
9161
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9162
                           " not supposed to be running because no wait for"
9163
                           " sync mode was requested.")
9164

    
9165

    
9166
class LUInstanceQueryData(NoHooksLU):
9167
  """Query runtime instance data.
9168

9169
  """
9170
  REQ_BGL = False
9171

    
9172
  def ExpandNames(self):
9173
    self.needed_locks = {}
9174
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9175

    
9176
    if self.op.instances:
9177
      self.wanted_names = []
9178
      for name in self.op.instances:
9179
        full_name = _ExpandInstanceName(self.cfg, name)
9180
        self.wanted_names.append(full_name)
9181
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9182
    else:
9183
      self.wanted_names = None
9184
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9185

    
9186
    self.needed_locks[locking.LEVEL_NODE] = []
9187
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9188

    
9189
  def DeclareLocks(self, level):
9190
    if level == locking.LEVEL_NODE:
9191
      self._LockInstancesNodes()
9192

    
9193
  def CheckPrereq(self):
9194
    """Check prerequisites.
9195

9196
    This only checks the optional instance list against the existing names.
9197

9198
    """
9199
    if self.wanted_names is None:
9200
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
9201

    
9202
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
9203
                             in self.wanted_names]
9204

    
9205
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9206
    """Returns the status of a block device
9207

9208
    """
9209
    if self.op.static or not node:
9210
      return None
9211

    
9212
    self.cfg.SetDiskID(dev, node)
9213

    
9214
    result = self.rpc.call_blockdev_find(node, dev)
9215
    if result.offline:
9216
      return None
9217

    
9218
    result.Raise("Can't compute disk status for %s" % instance_name)
9219

    
9220
    status = result.payload
9221
    if status is None:
9222
      return None
9223

    
9224
    return (status.dev_path, status.major, status.minor,
9225
            status.sync_percent, status.estimated_time,
9226
            status.is_degraded, status.ldisk_status)
9227

    
9228
  def _ComputeDiskStatus(self, instance, snode, dev):
9229
    """Compute block device status.
9230

9231
    """
9232
    if dev.dev_type in constants.LDS_DRBD:
9233
      # we change the snode then (otherwise we use the one passed in)
9234
      if dev.logical_id[0] == instance.primary_node:
9235
        snode = dev.logical_id[1]
9236
      else:
9237
        snode = dev.logical_id[0]
9238

    
9239
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9240
                                              instance.name, dev)
9241
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9242

    
9243
    if dev.children:
9244
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9245
                      for child in dev.children]
9246
    else:
9247
      dev_children = []
9248

    
9249
    data = {
9250
      "iv_name": dev.iv_name,
9251
      "dev_type": dev.dev_type,
9252
      "logical_id": dev.logical_id,
9253
      "physical_id": dev.physical_id,
9254
      "pstatus": dev_pstatus,
9255
      "sstatus": dev_sstatus,
9256
      "children": dev_children,
9257
      "mode": dev.mode,
9258
      "size": dev.size,
9259
      }
9260

    
9261
    return data
9262

    
9263
  def Exec(self, feedback_fn):
9264
    """Gather and return data"""
9265
    result = {}
9266

    
9267
    cluster = self.cfg.GetClusterInfo()
9268

    
9269
    for instance in self.wanted_instances:
9270
      if not self.op.static:
9271
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9272
                                                  instance.name,
9273
                                                  instance.hypervisor)
9274
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9275
        remote_info = remote_info.payload
9276
        if remote_info and "state" in remote_info:
9277
          remote_state = "up"
9278
        else:
9279
          remote_state = "down"
9280
      else:
9281
        remote_state = None
9282
      if instance.admin_up:
9283
        config_state = "up"
9284
      else:
9285
        config_state = "down"
9286

    
9287
      disks = [self._ComputeDiskStatus(instance, None, device)
9288
               for device in instance.disks]
9289

    
9290
      idict = {
9291
        "name": instance.name,
9292
        "config_state": config_state,
9293
        "run_state": remote_state,
9294
        "pnode": instance.primary_node,
9295
        "snodes": instance.secondary_nodes,
9296
        "os": instance.os,
9297
        # this happens to be the same format used for hooks
9298
        "nics": _NICListToTuple(self, instance.nics),
9299
        "disk_template": instance.disk_template,
9300
        "disks": disks,
9301
        "hypervisor": instance.hypervisor,
9302
        "network_port": instance.network_port,
9303
        "hv_instance": instance.hvparams,
9304
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9305
        "be_instance": instance.beparams,
9306
        "be_actual": cluster.FillBE(instance),
9307
        "os_instance": instance.osparams,
9308
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9309
        "serial_no": instance.serial_no,
9310
        "mtime": instance.mtime,
9311
        "ctime": instance.ctime,
9312
        "uuid": instance.uuid,
9313
        }
9314

    
9315
      result[instance.name] = idict
9316

    
9317
    return result
9318

    
9319

    
9320
class LUInstanceSetParams(LogicalUnit):
9321
  """Modifies an instances's parameters.
9322

9323
  """
9324
  HPATH = "instance-modify"
9325
  HTYPE = constants.HTYPE_INSTANCE
9326
  REQ_BGL = False
9327

    
9328
  def CheckArguments(self):
9329
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9330
            self.op.hvparams or self.op.beparams or self.op.os_name):
9331
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9332

    
9333
    if self.op.hvparams:
9334
      _CheckGlobalHvParams(self.op.hvparams)
9335

    
9336
    # Disk validation
9337
    disk_addremove = 0
9338
    for disk_op, disk_dict in self.op.disks:
9339
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9340
      if disk_op == constants.DDM_REMOVE:
9341
        disk_addremove += 1
9342
        continue
9343
      elif disk_op == constants.DDM_ADD:
9344
        disk_addremove += 1
9345
      else:
9346
        if not isinstance(disk_op, int):
9347
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9348
        if not isinstance(disk_dict, dict):
9349
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9350
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9351

    
9352
      if disk_op == constants.DDM_ADD:
9353
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
9354
        if mode not in constants.DISK_ACCESS_SET:
9355
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9356
                                     errors.ECODE_INVAL)
9357
        size = disk_dict.get('size', None)
9358
        if size is None:
9359
          raise errors.OpPrereqError("Required disk parameter size missing",
9360
                                     errors.ECODE_INVAL)
9361
        try:
9362
          size = int(size)
9363
        except (TypeError, ValueError), err:
9364
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9365
                                     str(err), errors.ECODE_INVAL)
9366
        disk_dict['size'] = size
9367
      else:
9368
        # modification of disk
9369
        if 'size' in disk_dict:
9370
          raise errors.OpPrereqError("Disk size change not possible, use"
9371
                                     " grow-disk", errors.ECODE_INVAL)
9372

    
9373
    if disk_addremove > 1:
9374
      raise errors.OpPrereqError("Only one disk add or remove operation"
9375
                                 " supported at a time", errors.ECODE_INVAL)
9376

    
9377
    if self.op.disks and self.op.disk_template is not None:
9378
      raise errors.OpPrereqError("Disk template conversion and other disk"
9379
                                 " changes not supported at the same time",
9380
                                 errors.ECODE_INVAL)
9381

    
9382
    if (self.op.disk_template and
9383
        self.op.disk_template in constants.DTS_INT_MIRROR and
9384
        self.op.remote_node is None):
9385
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9386
                                 " one requires specifying a secondary node",
9387
                                 errors.ECODE_INVAL)
9388

    
9389
    # NIC validation
9390
    nic_addremove = 0
9391
    for nic_op, nic_dict in self.op.nics:
9392
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9393
      if nic_op == constants.DDM_REMOVE:
9394
        nic_addremove += 1
9395
        continue
9396
      elif nic_op == constants.DDM_ADD:
9397
        nic_addremove += 1
9398
      else:
9399
        if not isinstance(nic_op, int):
9400
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9401
        if not isinstance(nic_dict, dict):
9402
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9403
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9404

    
9405
      # nic_dict should be a dict
9406
      nic_ip = nic_dict.get('ip', None)
9407
      if nic_ip is not None:
9408
        if nic_ip.lower() == constants.VALUE_NONE:
9409
          nic_dict['ip'] = None
9410
        else:
9411
          if not netutils.IPAddress.IsValid(nic_ip):
9412
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9413
                                       errors.ECODE_INVAL)
9414

    
9415
      nic_bridge = nic_dict.get('bridge', None)
9416
      nic_link = nic_dict.get('link', None)
9417
      if nic_bridge and nic_link:
9418
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9419
                                   " at the same time", errors.ECODE_INVAL)
9420
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9421
        nic_dict['bridge'] = None
9422
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9423
        nic_dict['link'] = None
9424

    
9425
      if nic_op == constants.DDM_ADD:
9426
        nic_mac = nic_dict.get('mac', None)
9427
        if nic_mac is None:
9428
          nic_dict['mac'] = constants.VALUE_AUTO
9429

    
9430
      if 'mac' in nic_dict:
9431
        nic_mac = nic_dict['mac']
9432
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9433
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9434

    
9435
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9436
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9437
                                     " modifying an existing nic",
9438
                                     errors.ECODE_INVAL)
9439

    
9440
    if nic_addremove > 1:
9441
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9442
                                 " supported at a time", errors.ECODE_INVAL)
9443

    
9444
  def ExpandNames(self):
9445
    self._ExpandAndLockInstance()
9446
    self.needed_locks[locking.LEVEL_NODE] = []
9447
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9448

    
9449
  def DeclareLocks(self, level):
9450
    if level == locking.LEVEL_NODE:
9451
      self._LockInstancesNodes()
9452
      if self.op.disk_template and self.op.remote_node:
9453
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9454
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9455

    
9456
  def BuildHooksEnv(self):
9457
    """Build hooks env.
9458

9459
    This runs on the master, primary and secondaries.
9460

9461
    """
9462
    args = dict()
9463
    if constants.BE_MEMORY in self.be_new:
9464
      args['memory'] = self.be_new[constants.BE_MEMORY]
9465
    if constants.BE_VCPUS in self.be_new:
9466
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9467
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9468
    # information at all.
9469
    if self.op.nics:
9470
      args['nics'] = []
9471
      nic_override = dict(self.op.nics)
9472
      for idx, nic in enumerate(self.instance.nics):
9473
        if idx in nic_override:
9474
          this_nic_override = nic_override[idx]
9475
        else:
9476
          this_nic_override = {}
9477
        if 'ip' in this_nic_override:
9478
          ip = this_nic_override['ip']
9479
        else:
9480
          ip = nic.ip
9481
        if 'mac' in this_nic_override:
9482
          mac = this_nic_override['mac']
9483
        else:
9484
          mac = nic.mac
9485
        if idx in self.nic_pnew:
9486
          nicparams = self.nic_pnew[idx]
9487
        else:
9488
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9489
        mode = nicparams[constants.NIC_MODE]
9490
        link = nicparams[constants.NIC_LINK]
9491
        args['nics'].append((ip, mac, mode, link))
9492
      if constants.DDM_ADD in nic_override:
9493
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9494
        mac = nic_override[constants.DDM_ADD]['mac']
9495
        nicparams = self.nic_pnew[constants.DDM_ADD]
9496
        mode = nicparams[constants.NIC_MODE]
9497
        link = nicparams[constants.NIC_LINK]
9498
        args['nics'].append((ip, mac, mode, link))
9499
      elif constants.DDM_REMOVE in nic_override:
9500
        del args['nics'][-1]
9501

    
9502
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9503
    if self.op.disk_template:
9504
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9505
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9506
    return env, nl, nl
9507

    
9508
  def CheckPrereq(self):
9509
    """Check prerequisites.
9510

9511
    This only checks the instance list against the existing names.
9512

9513
    """
9514
    # checking the new params on the primary/secondary nodes
9515

    
9516
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9517
    cluster = self.cluster = self.cfg.GetClusterInfo()
9518
    assert self.instance is not None, \
9519
      "Cannot retrieve locked instance %s" % self.op.instance_name
9520
    pnode = instance.primary_node
9521
    nodelist = list(instance.all_nodes)
9522

    
9523
    # OS change
9524
    if self.op.os_name and not self.op.force:
9525
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9526
                      self.op.force_variant)
9527
      instance_os = self.op.os_name
9528
    else:
9529
      instance_os = instance.os
9530

    
9531
    if self.op.disk_template:
9532
      if instance.disk_template == self.op.disk_template:
9533
        raise errors.OpPrereqError("Instance already has disk template %s" %
9534
                                   instance.disk_template, errors.ECODE_INVAL)
9535

    
9536
      if (instance.disk_template,
9537
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9538
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9539
                                   " %s to %s" % (instance.disk_template,
9540
                                                  self.op.disk_template),
9541
                                   errors.ECODE_INVAL)
9542
      _CheckInstanceDown(self, instance, "cannot change disk template")
9543
      if self.op.disk_template in constants.DTS_INT_MIRROR:
9544
        if self.op.remote_node == pnode:
9545
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9546
                                     " as the primary node of the instance" %
9547
                                     self.op.remote_node, errors.ECODE_STATE)
9548
        _CheckNodeOnline(self, self.op.remote_node)
9549
        _CheckNodeNotDrained(self, self.op.remote_node)
9550
        # FIXME: here we assume that the old instance type is DT_PLAIN
9551
        assert instance.disk_template == constants.DT_PLAIN
9552
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9553
                 for d in instance.disks]
9554
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9555
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9556

    
9557
    # hvparams processing
9558
    if self.op.hvparams:
9559
      hv_type = instance.hypervisor
9560
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9561
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9562
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9563

    
9564
      # local check
9565
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9566
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9567
      self.hv_new = hv_new # the new actual values
9568
      self.hv_inst = i_hvdict # the new dict (without defaults)
9569
    else:
9570
      self.hv_new = self.hv_inst = {}
9571

    
9572
    # beparams processing
9573
    if self.op.beparams:
9574
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9575
                                   use_none=True)
9576
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9577
      be_new = cluster.SimpleFillBE(i_bedict)
9578
      self.be_new = be_new # the new actual values
9579
      self.be_inst = i_bedict # the new dict (without defaults)
9580
    else:
9581
      self.be_new = self.be_inst = {}
9582

    
9583
    # osparams processing
9584
    if self.op.osparams:
9585
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9586
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9587
      self.os_inst = i_osdict # the new dict (without defaults)
9588
    else:
9589
      self.os_inst = {}
9590

    
9591
    self.warn = []
9592

    
9593
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9594
      mem_check_list = [pnode]
9595
      if be_new[constants.BE_AUTO_BALANCE]:
9596
        # either we changed auto_balance to yes or it was from before
9597
        mem_check_list.extend(instance.secondary_nodes)
9598
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9599
                                                  instance.hypervisor)
9600
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9601
                                         instance.hypervisor)
9602
      pninfo = nodeinfo[pnode]
9603
      msg = pninfo.fail_msg
9604
      if msg:
9605
        # Assume the primary node is unreachable and go ahead
9606
        self.warn.append("Can't get info from primary node %s: %s" %
9607
                         (pnode,  msg))
9608
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9609
        self.warn.append("Node data from primary node %s doesn't contain"
9610
                         " free memory information" % pnode)
9611
      elif instance_info.fail_msg:
9612
        self.warn.append("Can't get instance runtime information: %s" %
9613
                        instance_info.fail_msg)
9614
      else:
9615
        if instance_info.payload:
9616
          current_mem = int(instance_info.payload['memory'])
9617
        else:
9618
          # Assume instance not running
9619
          # (there is a slight race condition here, but it's not very probable,
9620
          # and we have no other way to check)
9621
          current_mem = 0
9622
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9623
                    pninfo.payload['memory_free'])
9624
        if miss_mem > 0:
9625
          raise errors.OpPrereqError("This change will prevent the instance"
9626
                                     " from starting, due to %d MB of memory"
9627
                                     " missing on its primary node" % miss_mem,
9628
                                     errors.ECODE_NORES)
9629

    
9630
      if be_new[constants.BE_AUTO_BALANCE]:
9631
        for node, nres in nodeinfo.items():
9632
          if node not in instance.secondary_nodes:
9633
            continue
9634
          msg = nres.fail_msg
9635
          if msg:
9636
            self.warn.append("Can't get info from secondary node %s: %s" %
9637
                             (node, msg))
9638
          elif not isinstance(nres.payload.get('memory_free', None), int):
9639
            self.warn.append("Secondary node %s didn't return free"
9640
                             " memory information" % node)
9641
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9642
            self.warn.append("Not enough memory to failover instance to"
9643
                             " secondary node %s" % node)
9644

    
9645
    # NIC processing
9646
    self.nic_pnew = {}
9647
    self.nic_pinst = {}
9648
    for nic_op, nic_dict in self.op.nics:
9649
      if nic_op == constants.DDM_REMOVE:
9650
        if not instance.nics:
9651
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9652
                                     errors.ECODE_INVAL)
9653
        continue
9654
      if nic_op != constants.DDM_ADD:
9655
        # an existing nic
9656
        if not instance.nics:
9657
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9658
                                     " no NICs" % nic_op,
9659
                                     errors.ECODE_INVAL)
9660
        if nic_op < 0 or nic_op >= len(instance.nics):
9661
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9662
                                     " are 0 to %d" %
9663
                                     (nic_op, len(instance.nics) - 1),
9664
                                     errors.ECODE_INVAL)
9665
        old_nic_params = instance.nics[nic_op].nicparams
9666
        old_nic_ip = instance.nics[nic_op].ip
9667
      else:
9668
        old_nic_params = {}
9669
        old_nic_ip = None
9670

    
9671
      update_params_dict = dict([(key, nic_dict[key])
9672
                                 for key in constants.NICS_PARAMETERS
9673
                                 if key in nic_dict])
9674

    
9675
      if 'bridge' in nic_dict:
9676
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9677

    
9678
      new_nic_params = _GetUpdatedParams(old_nic_params,
9679
                                         update_params_dict)
9680
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9681
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9682
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9683
      self.nic_pinst[nic_op] = new_nic_params
9684
      self.nic_pnew[nic_op] = new_filled_nic_params
9685
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9686

    
9687
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9688
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9689
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9690
        if msg:
9691
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9692
          if self.op.force:
9693
            self.warn.append(msg)
9694
          else:
9695
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9696
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9697
        if 'ip' in nic_dict:
9698
          nic_ip = nic_dict['ip']
9699
        else:
9700
          nic_ip = old_nic_ip
9701
        if nic_ip is None:
9702
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9703
                                     ' on a routed nic', errors.ECODE_INVAL)
9704
      if 'mac' in nic_dict:
9705
        nic_mac = nic_dict['mac']
9706
        if nic_mac is None:
9707
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9708
                                     errors.ECODE_INVAL)
9709
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9710
          # otherwise generate the mac
9711
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9712
        else:
9713
          # or validate/reserve the current one
9714
          try:
9715
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9716
          except errors.ReservationError:
9717
            raise errors.OpPrereqError("MAC address %s already in use"
9718
                                       " in cluster" % nic_mac,
9719
                                       errors.ECODE_NOTUNIQUE)
9720

    
9721
    # DISK processing
9722
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9723
      raise errors.OpPrereqError("Disk operations not supported for"
9724
                                 " diskless instances",
9725
                                 errors.ECODE_INVAL)
9726
    for disk_op, _ in self.op.disks:
9727
      if disk_op == constants.DDM_REMOVE:
9728
        if len(instance.disks) == 1:
9729
          raise errors.OpPrereqError("Cannot remove the last disk of"
9730
                                     " an instance", errors.ECODE_INVAL)
9731
        _CheckInstanceDown(self, instance, "cannot remove disks")
9732

    
9733
      if (disk_op == constants.DDM_ADD and
9734
          len(instance.disks) >= constants.MAX_DISKS):
9735
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9736
                                   " add more" % constants.MAX_DISKS,
9737
                                   errors.ECODE_STATE)
9738
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9739
        # an existing disk
9740
        if disk_op < 0 or disk_op >= len(instance.disks):
9741
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9742
                                     " are 0 to %d" %
9743
                                     (disk_op, len(instance.disks)),
9744
                                     errors.ECODE_INVAL)
9745

    
9746
    return
9747

    
9748
  def _ConvertPlainToDrbd(self, feedback_fn):
9749
    """Converts an instance from plain to drbd.
9750

9751
    """
9752
    feedback_fn("Converting template to drbd")
9753
    instance = self.instance
9754
    pnode = instance.primary_node
9755
    snode = self.op.remote_node
9756

    
9757
    # create a fake disk info for _GenerateDiskTemplate
9758
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9759
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9760
                                      instance.name, pnode, [snode],
9761
                                      disk_info, None, None, 0, feedback_fn)
9762
    info = _GetInstanceInfoText(instance)
9763
    feedback_fn("Creating aditional volumes...")
9764
    # first, create the missing data and meta devices
9765
    for disk in new_disks:
9766
      # unfortunately this is... not too nice
9767
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9768
                            info, True)
9769
      for child in disk.children:
9770
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9771
    # at this stage, all new LVs have been created, we can rename the
9772
    # old ones
9773
    feedback_fn("Renaming original volumes...")
9774
    rename_list = [(o, n.children[0].logical_id)
9775
                   for (o, n) in zip(instance.disks, new_disks)]
9776
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9777
    result.Raise("Failed to rename original LVs")
9778

    
9779
    feedback_fn("Initializing DRBD devices...")
9780
    # all child devices are in place, we can now create the DRBD devices
9781
    for disk in new_disks:
9782
      for node in [pnode, snode]:
9783
        f_create = node == pnode
9784
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9785

    
9786
    # at this point, the instance has been modified
9787
    instance.disk_template = constants.DT_DRBD8
9788
    instance.disks = new_disks
9789
    self.cfg.Update(instance, feedback_fn)
9790

    
9791
    # disks are created, waiting for sync
9792
    disk_abort = not _WaitForSync(self, instance)
9793
    if disk_abort:
9794
      raise errors.OpExecError("There are some degraded disks for"
9795
                               " this instance, please cleanup manually")
9796

    
9797
  def _ConvertDrbdToPlain(self, feedback_fn):
9798
    """Converts an instance from drbd to plain.
9799

9800
    """
9801
    instance = self.instance
9802
    assert len(instance.secondary_nodes) == 1
9803
    pnode = instance.primary_node
9804
    snode = instance.secondary_nodes[0]
9805
    feedback_fn("Converting template to plain")
9806

    
9807
    old_disks = instance.disks
9808
    new_disks = [d.children[0] for d in old_disks]
9809

    
9810
    # copy over size and mode
9811
    for parent, child in zip(old_disks, new_disks):
9812
      child.size = parent.size
9813
      child.mode = parent.mode
9814

    
9815
    # update instance structure
9816
    instance.disks = new_disks
9817
    instance.disk_template = constants.DT_PLAIN
9818
    self.cfg.Update(instance, feedback_fn)
9819

    
9820
    feedback_fn("Removing volumes on the secondary node...")
9821
    for disk in old_disks:
9822
      self.cfg.SetDiskID(disk, snode)
9823
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9824
      if msg:
9825
        self.LogWarning("Could not remove block device %s on node %s,"
9826
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9827

    
9828
    feedback_fn("Removing unneeded volumes on the primary node...")
9829
    for idx, disk in enumerate(old_disks):
9830
      meta = disk.children[1]
9831
      self.cfg.SetDiskID(meta, pnode)
9832
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9833
      if msg:
9834
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9835
                        " continuing anyway: %s", idx, pnode, msg)
9836

    
9837
  def Exec(self, feedback_fn):
9838
    """Modifies an instance.
9839

9840
    All parameters take effect only at the next restart of the instance.
9841

9842
    """
9843
    # Process here the warnings from CheckPrereq, as we don't have a
9844
    # feedback_fn there.
9845
    for warn in self.warn:
9846
      feedback_fn("WARNING: %s" % warn)
9847

    
9848
    result = []
9849
    instance = self.instance
9850
    # disk changes
9851
    for disk_op, disk_dict in self.op.disks:
9852
      if disk_op == constants.DDM_REMOVE:
9853
        # remove the last disk
9854
        device = instance.disks.pop()
9855
        device_idx = len(instance.disks)
9856
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9857
          self.cfg.SetDiskID(disk, node)
9858
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9859
          if msg:
9860
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9861
                            " continuing anyway", device_idx, node, msg)
9862
        result.append(("disk/%d" % device_idx, "remove"))
9863
      elif disk_op == constants.DDM_ADD:
9864
        # add a new disk
9865
        if instance.disk_template in (constants.DT_FILE,
9866
                                        constants.DT_SHARED_FILE):
9867
          file_driver, file_path = instance.disks[0].logical_id
9868
          file_path = os.path.dirname(file_path)
9869
        else:
9870
          file_driver = file_path = None
9871
        disk_idx_base = len(instance.disks)
9872
        new_disk = _GenerateDiskTemplate(self,
9873
                                         instance.disk_template,
9874
                                         instance.name, instance.primary_node,
9875
                                         instance.secondary_nodes,
9876
                                         [disk_dict],
9877
                                         file_path,
9878
                                         file_driver,
9879
                                         disk_idx_base, feedback_fn)[0]
9880
        instance.disks.append(new_disk)
9881
        info = _GetInstanceInfoText(instance)
9882

    
9883
        logging.info("Creating volume %s for instance %s",
9884
                     new_disk.iv_name, instance.name)
9885
        # Note: this needs to be kept in sync with _CreateDisks
9886
        #HARDCODE
9887
        for node in instance.all_nodes:
9888
          f_create = node == instance.primary_node
9889
          try:
9890
            _CreateBlockDev(self, node, instance, new_disk,
9891
                            f_create, info, f_create)
9892
          except errors.OpExecError, err:
9893
            self.LogWarning("Failed to create volume %s (%s) on"
9894
                            " node %s: %s",
9895
                            new_disk.iv_name, new_disk, node, err)
9896
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9897
                       (new_disk.size, new_disk.mode)))
9898
      else:
9899
        # change a given disk
9900
        instance.disks[disk_op].mode = disk_dict['mode']
9901
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9902

    
9903
    if self.op.disk_template:
9904
      r_shut = _ShutdownInstanceDisks(self, instance)
9905
      if not r_shut:
9906
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
9907
                                 " proceed with disk template conversion")
9908
      mode = (instance.disk_template, self.op.disk_template)
9909
      try:
9910
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9911
      except:
9912
        self.cfg.ReleaseDRBDMinors(instance.name)
9913
        raise
9914
      result.append(("disk_template", self.op.disk_template))
9915

    
9916
    # NIC changes
9917
    for nic_op, nic_dict in self.op.nics:
9918
      if nic_op == constants.DDM_REMOVE:
9919
        # remove the last nic
9920
        del instance.nics[-1]
9921
        result.append(("nic.%d" % len(instance.nics), "remove"))
9922
      elif nic_op == constants.DDM_ADD:
9923
        # mac and bridge should be set, by now
9924
        mac = nic_dict['mac']
9925
        ip = nic_dict.get('ip', None)
9926
        nicparams = self.nic_pinst[constants.DDM_ADD]
9927
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9928
        instance.nics.append(new_nic)
9929
        result.append(("nic.%d" % (len(instance.nics) - 1),
9930
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9931
                       (new_nic.mac, new_nic.ip,
9932
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9933
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9934
                       )))
9935
      else:
9936
        for key in 'mac', 'ip':
9937
          if key in nic_dict:
9938
            setattr(instance.nics[nic_op], key, nic_dict[key])
9939
        if nic_op in self.nic_pinst:
9940
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9941
        for key, val in nic_dict.iteritems():
9942
          result.append(("nic.%s/%d" % (key, nic_op), val))
9943

    
9944
    # hvparams changes
9945
    if self.op.hvparams:
9946
      instance.hvparams = self.hv_inst
9947
      for key, val in self.op.hvparams.iteritems():
9948
        result.append(("hv/%s" % key, val))
9949

    
9950
    # beparams changes
9951
    if self.op.beparams:
9952
      instance.beparams = self.be_inst
9953
      for key, val in self.op.beparams.iteritems():
9954
        result.append(("be/%s" % key, val))
9955

    
9956
    # OS change
9957
    if self.op.os_name:
9958
      instance.os = self.op.os_name
9959

    
9960
    # osparams changes
9961
    if self.op.osparams:
9962
      instance.osparams = self.os_inst
9963
      for key, val in self.op.osparams.iteritems():
9964
        result.append(("os/%s" % key, val))
9965

    
9966
    self.cfg.Update(instance, feedback_fn)
9967

    
9968
    return result
9969

    
9970
  _DISK_CONVERSIONS = {
9971
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9972
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9973
    }
9974

    
9975

    
9976
class LUBackupQuery(NoHooksLU):
9977
  """Query the exports list
9978

9979
  """
9980
  REQ_BGL = False
9981

    
9982
  def ExpandNames(self):
9983
    self.needed_locks = {}
9984
    self.share_locks[locking.LEVEL_NODE] = 1
9985
    if not self.op.nodes:
9986
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9987
    else:
9988
      self.needed_locks[locking.LEVEL_NODE] = \
9989
        _GetWantedNodes(self, self.op.nodes)
9990

    
9991
  def Exec(self, feedback_fn):
9992
    """Compute the list of all the exported system images.
9993

9994
    @rtype: dict
9995
    @return: a dictionary with the structure node->(export-list)
9996
        where export-list is a list of the instances exported on
9997
        that node.
9998

9999
    """
10000
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
10001
    rpcresult = self.rpc.call_export_list(self.nodes)
10002
    result = {}
10003
    for node in rpcresult:
10004
      if rpcresult[node].fail_msg:
10005
        result[node] = False
10006
      else:
10007
        result[node] = rpcresult[node].payload
10008

    
10009
    return result
10010

    
10011

    
10012
class LUBackupPrepare(NoHooksLU):
10013
  """Prepares an instance for an export and returns useful information.
10014

10015
  """
10016
  REQ_BGL = False
10017

    
10018
  def ExpandNames(self):
10019
    self._ExpandAndLockInstance()
10020

    
10021
  def CheckPrereq(self):
10022
    """Check prerequisites.
10023

10024
    """
10025
    instance_name = self.op.instance_name
10026

    
10027
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10028
    assert self.instance is not None, \
10029
          "Cannot retrieve locked instance %s" % self.op.instance_name
10030
    _CheckNodeOnline(self, self.instance.primary_node)
10031

    
10032
    self._cds = _GetClusterDomainSecret()
10033

    
10034
  def Exec(self, feedback_fn):
10035
    """Prepares an instance for an export.
10036

10037
    """
10038
    instance = self.instance
10039

    
10040
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10041
      salt = utils.GenerateSecret(8)
10042

    
10043
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10044
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10045
                                              constants.RIE_CERT_VALIDITY)
10046
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10047

    
10048
      (name, cert_pem) = result.payload
10049

    
10050
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10051
                                             cert_pem)
10052

    
10053
      return {
10054
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10055
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10056
                          salt),
10057
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10058
        }
10059

    
10060
    return None
10061

    
10062

    
10063
class LUBackupExport(LogicalUnit):
10064
  """Export an instance to an image in the cluster.
10065

10066
  """
10067
  HPATH = "instance-export"
10068
  HTYPE = constants.HTYPE_INSTANCE
10069
  REQ_BGL = False
10070

    
10071
  def CheckArguments(self):
10072
    """Check the arguments.
10073

10074
    """
10075
    self.x509_key_name = self.op.x509_key_name
10076
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10077

    
10078
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10079
      if not self.x509_key_name:
10080
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10081
                                   errors.ECODE_INVAL)
10082

    
10083
      if not self.dest_x509_ca_pem:
10084
        raise errors.OpPrereqError("Missing destination X509 CA",
10085
                                   errors.ECODE_INVAL)
10086

    
10087
  def ExpandNames(self):
10088
    self._ExpandAndLockInstance()
10089

    
10090
    # Lock all nodes for local exports
10091
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10092
      # FIXME: lock only instance primary and destination node
10093
      #
10094
      # Sad but true, for now we have do lock all nodes, as we don't know where
10095
      # the previous export might be, and in this LU we search for it and
10096
      # remove it from its current node. In the future we could fix this by:
10097
      #  - making a tasklet to search (share-lock all), then create the
10098
      #    new one, then one to remove, after
10099
      #  - removing the removal operation altogether
10100
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10101

    
10102
  def DeclareLocks(self, level):
10103
    """Last minute lock declaration."""
10104
    # All nodes are locked anyway, so nothing to do here.
10105

    
10106
  def BuildHooksEnv(self):
10107
    """Build hooks env.
10108

10109
    This will run on the master, primary node and target node.
10110

10111
    """
10112
    env = {
10113
      "EXPORT_MODE": self.op.mode,
10114
      "EXPORT_NODE": self.op.target_node,
10115
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10116
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10117
      # TODO: Generic function for boolean env variables
10118
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10119
      }
10120

    
10121
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10122

    
10123
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10124

    
10125
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10126
      nl.append(self.op.target_node)
10127

    
10128
    return env, nl, nl
10129

    
10130
  def CheckPrereq(self):
10131
    """Check prerequisites.
10132

10133
    This checks that the instance and node names are valid.
10134

10135
    """
10136
    instance_name = self.op.instance_name
10137

    
10138
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10139
    assert self.instance is not None, \
10140
          "Cannot retrieve locked instance %s" % self.op.instance_name
10141
    _CheckNodeOnline(self, self.instance.primary_node)
10142

    
10143
    if (self.op.remove_instance and self.instance.admin_up and
10144
        not self.op.shutdown):
10145
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10146
                                 " down before")
10147

    
10148
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10149
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10150
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10151
      assert self.dst_node is not None
10152

    
10153
      _CheckNodeOnline(self, self.dst_node.name)
10154
      _CheckNodeNotDrained(self, self.dst_node.name)
10155

    
10156
      self._cds = None
10157
      self.dest_disk_info = None
10158
      self.dest_x509_ca = None
10159

    
10160
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10161
      self.dst_node = None
10162

    
10163
      if len(self.op.target_node) != len(self.instance.disks):
10164
        raise errors.OpPrereqError(("Received destination information for %s"
10165
                                    " disks, but instance %s has %s disks") %
10166
                                   (len(self.op.target_node), instance_name,
10167
                                    len(self.instance.disks)),
10168
                                   errors.ECODE_INVAL)
10169

    
10170
      cds = _GetClusterDomainSecret()
10171

    
10172
      # Check X509 key name
10173
      try:
10174
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10175
      except (TypeError, ValueError), err:
10176
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10177

    
10178
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10179
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10180
                                   errors.ECODE_INVAL)
10181

    
10182
      # Load and verify CA
10183
      try:
10184
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10185
      except OpenSSL.crypto.Error, err:
10186
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10187
                                   (err, ), errors.ECODE_INVAL)
10188

    
10189
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10190
      if errcode is not None:
10191
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10192
                                   (msg, ), errors.ECODE_INVAL)
10193

    
10194
      self.dest_x509_ca = cert
10195

    
10196
      # Verify target information
10197
      disk_info = []
10198
      for idx, disk_data in enumerate(self.op.target_node):
10199
        try:
10200
          (host, port, magic) = \
10201
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10202
        except errors.GenericError, err:
10203
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10204
                                     (idx, err), errors.ECODE_INVAL)
10205

    
10206
        disk_info.append((host, port, magic))
10207

    
10208
      assert len(disk_info) == len(self.op.target_node)
10209
      self.dest_disk_info = disk_info
10210

    
10211
    else:
10212
      raise errors.ProgrammerError("Unhandled export mode %r" %
10213
                                   self.op.mode)
10214

    
10215
    # instance disk type verification
10216
    # TODO: Implement export support for file-based disks
10217
    for disk in self.instance.disks:
10218
      if disk.dev_type == constants.LD_FILE:
10219
        raise errors.OpPrereqError("Export not supported for instances with"
10220
                                   " file-based disks", errors.ECODE_INVAL)
10221

    
10222
  def _CleanupExports(self, feedback_fn):
10223
    """Removes exports of current instance from all other nodes.
10224

10225
    If an instance in a cluster with nodes A..D was exported to node C, its
10226
    exports will be removed from the nodes A, B and D.
10227

10228
    """
10229
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10230

    
10231
    nodelist = self.cfg.GetNodeList()
10232
    nodelist.remove(self.dst_node.name)
10233

    
10234
    # on one-node clusters nodelist will be empty after the removal
10235
    # if we proceed the backup would be removed because OpBackupQuery
10236
    # substitutes an empty list with the full cluster node list.
10237
    iname = self.instance.name
10238
    if nodelist:
10239
      feedback_fn("Removing old exports for instance %s" % iname)
10240
      exportlist = self.rpc.call_export_list(nodelist)
10241
      for node in exportlist:
10242
        if exportlist[node].fail_msg:
10243
          continue
10244
        if iname in exportlist[node].payload:
10245
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10246
          if msg:
10247
            self.LogWarning("Could not remove older export for instance %s"
10248
                            " on node %s: %s", iname, node, msg)
10249

    
10250
  def Exec(self, feedback_fn):
10251
    """Export an instance to an image in the cluster.
10252

10253
    """
10254
    assert self.op.mode in constants.EXPORT_MODES
10255

    
10256
    instance = self.instance
10257
    src_node = instance.primary_node
10258

    
10259
    if self.op.shutdown:
10260
      # shutdown the instance, but not the disks
10261
      feedback_fn("Shutting down instance %s" % instance.name)
10262
      result = self.rpc.call_instance_shutdown(src_node, instance,
10263
                                               self.op.shutdown_timeout)
10264
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10265
      result.Raise("Could not shutdown instance %s on"
10266
                   " node %s" % (instance.name, src_node))
10267

    
10268
    # set the disks ID correctly since call_instance_start needs the
10269
    # correct drbd minor to create the symlinks
10270
    for disk in instance.disks:
10271
      self.cfg.SetDiskID(disk, src_node)
10272

    
10273
    activate_disks = (not instance.admin_up)
10274

    
10275
    if activate_disks:
10276
      # Activate the instance disks if we'exporting a stopped instance
10277
      feedback_fn("Activating disks for %s" % instance.name)
10278
      _StartInstanceDisks(self, instance, None)
10279

    
10280
    try:
10281
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10282
                                                     instance)
10283

    
10284
      helper.CreateSnapshots()
10285
      try:
10286
        if (self.op.shutdown and instance.admin_up and
10287
            not self.op.remove_instance):
10288
          assert not activate_disks
10289
          feedback_fn("Starting instance %s" % instance.name)
10290
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10291
          msg = result.fail_msg
10292
          if msg:
10293
            feedback_fn("Failed to start instance: %s" % msg)
10294
            _ShutdownInstanceDisks(self, instance)
10295
            raise errors.OpExecError("Could not start instance: %s" % msg)
10296

    
10297
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10298
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10299
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10300
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10301
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10302

    
10303
          (key_name, _, _) = self.x509_key_name
10304

    
10305
          dest_ca_pem = \
10306
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10307
                                            self.dest_x509_ca)
10308

    
10309
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10310
                                                     key_name, dest_ca_pem,
10311
                                                     timeouts)
10312
      finally:
10313
        helper.Cleanup()
10314

    
10315
      # Check for backwards compatibility
10316
      assert len(dresults) == len(instance.disks)
10317
      assert compat.all(isinstance(i, bool) for i in dresults), \
10318
             "Not all results are boolean: %r" % dresults
10319

    
10320
    finally:
10321
      if activate_disks:
10322
        feedback_fn("Deactivating disks for %s" % instance.name)
10323
        _ShutdownInstanceDisks(self, instance)
10324

    
10325
    if not (compat.all(dresults) and fin_resu):
10326
      failures = []
10327
      if not fin_resu:
10328
        failures.append("export finalization")
10329
      if not compat.all(dresults):
10330
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10331
                               if not dsk)
10332
        failures.append("disk export: disk(s) %s" % fdsk)
10333

    
10334
      raise errors.OpExecError("Export failed, errors in %s" %
10335
                               utils.CommaJoin(failures))
10336

    
10337
    # At this point, the export was successful, we can cleanup/finish
10338

    
10339
    # Remove instance if requested
10340
    if self.op.remove_instance:
10341
      feedback_fn("Removing instance %s" % instance.name)
10342
      _RemoveInstance(self, feedback_fn, instance,
10343
                      self.op.ignore_remove_failures)
10344

    
10345
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10346
      self._CleanupExports(feedback_fn)
10347

    
10348
    return fin_resu, dresults
10349

    
10350

    
10351
class LUBackupRemove(NoHooksLU):
10352
  """Remove exports related to the named instance.
10353

10354
  """
10355
  REQ_BGL = False
10356

    
10357
  def ExpandNames(self):
10358
    self.needed_locks = {}
10359
    # We need all nodes to be locked in order for RemoveExport to work, but we
10360
    # don't need to lock the instance itself, as nothing will happen to it (and
10361
    # we can remove exports also for a removed instance)
10362
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10363

    
10364
  def Exec(self, feedback_fn):
10365
    """Remove any export.
10366

10367
    """
10368
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10369
    # If the instance was not found we'll try with the name that was passed in.
10370
    # This will only work if it was an FQDN, though.
10371
    fqdn_warn = False
10372
    if not instance_name:
10373
      fqdn_warn = True
10374
      instance_name = self.op.instance_name
10375

    
10376
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10377
    exportlist = self.rpc.call_export_list(locked_nodes)
10378
    found = False
10379
    for node in exportlist:
10380
      msg = exportlist[node].fail_msg
10381
      if msg:
10382
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10383
        continue
10384
      if instance_name in exportlist[node].payload:
10385
        found = True
10386
        result = self.rpc.call_export_remove(node, instance_name)
10387
        msg = result.fail_msg
10388
        if msg:
10389
          logging.error("Could not remove export for instance %s"
10390
                        " on node %s: %s", instance_name, node, msg)
10391

    
10392
    if fqdn_warn and not found:
10393
      feedback_fn("Export not found. If trying to remove an export belonging"
10394
                  " to a deleted instance please use its Fully Qualified"
10395
                  " Domain Name.")
10396

    
10397

    
10398
class LUGroupAdd(LogicalUnit):
10399
  """Logical unit for creating node groups.
10400

10401
  """
10402
  HPATH = "group-add"
10403
  HTYPE = constants.HTYPE_GROUP
10404
  REQ_BGL = False
10405

    
10406
  def ExpandNames(self):
10407
    # We need the new group's UUID here so that we can create and acquire the
10408
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10409
    # that it should not check whether the UUID exists in the configuration.
10410
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10411
    self.needed_locks = {}
10412
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10413

    
10414
  def CheckPrereq(self):
10415
    """Check prerequisites.
10416

10417
    This checks that the given group name is not an existing node group
10418
    already.
10419

10420
    """
10421
    try:
10422
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10423
    except errors.OpPrereqError:
10424
      pass
10425
    else:
10426
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10427
                                 " node group (UUID: %s)" %
10428
                                 (self.op.group_name, existing_uuid),
10429
                                 errors.ECODE_EXISTS)
10430

    
10431
    if self.op.ndparams:
10432
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10433

    
10434
  def BuildHooksEnv(self):
10435
    """Build hooks env.
10436

10437
    """
10438
    env = {
10439
      "GROUP_NAME": self.op.group_name,
10440
      }
10441
    mn = self.cfg.GetMasterNode()
10442
    return env, [mn], [mn]
10443

    
10444
  def Exec(self, feedback_fn):
10445
    """Add the node group to the cluster.
10446

10447
    """
10448
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
10449
                                  uuid=self.group_uuid,
10450
                                  alloc_policy=self.op.alloc_policy,
10451
                                  ndparams=self.op.ndparams)
10452

    
10453
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10454
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10455

    
10456

    
10457
class LUGroupAssignNodes(NoHooksLU):
10458
  """Logical unit for assigning nodes to groups.
10459

10460
  """
10461
  REQ_BGL = False
10462

    
10463
  def ExpandNames(self):
10464
    # These raise errors.OpPrereqError on their own:
10465
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10466
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10467

    
10468
    # We want to lock all the affected nodes and groups. We have readily
10469
    # available the list of nodes, and the *destination* group. To gather the
10470
    # list of "source" groups, we need to fetch node information.
10471
    self.node_data = self.cfg.GetAllNodesInfo()
10472
    affected_groups = set(self.node_data[node].group for node in self.op.nodes)
10473
    affected_groups.add(self.group_uuid)
10474

    
10475
    self.needed_locks = {
10476
      locking.LEVEL_NODEGROUP: list(affected_groups),
10477
      locking.LEVEL_NODE: self.op.nodes,
10478
      }
10479

    
10480
  def CheckPrereq(self):
10481
    """Check prerequisites.
10482

10483
    """
10484
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10485
    instance_data = self.cfg.GetAllInstancesInfo()
10486

    
10487
    if self.group is None:
10488
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10489
                               (self.op.group_name, self.group_uuid))
10490

    
10491
    (new_splits, previous_splits) = \
10492
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10493
                                             for node in self.op.nodes],
10494
                                            self.node_data, instance_data)
10495

    
10496
    if new_splits:
10497
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10498

    
10499
      if not self.op.force:
10500
        raise errors.OpExecError("The following instances get split by this"
10501
                                 " change and --force was not given: %s" %
10502
                                 fmt_new_splits)
10503
      else:
10504
        self.LogWarning("This operation will split the following instances: %s",
10505
                        fmt_new_splits)
10506

    
10507
        if previous_splits:
10508
          self.LogWarning("In addition, these already-split instances continue"
10509
                          " to be spit across groups: %s",
10510
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10511

    
10512
  def Exec(self, feedback_fn):
10513
    """Assign nodes to a new group.
10514

10515
    """
10516
    for node in self.op.nodes:
10517
      self.node_data[node].group = self.group_uuid
10518

    
10519
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10520

    
10521
  @staticmethod
10522
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10523
    """Check for split instances after a node assignment.
10524

10525
    This method considers a series of node assignments as an atomic operation,
10526
    and returns information about split instances after applying the set of
10527
    changes.
10528

10529
    In particular, it returns information about newly split instances, and
10530
    instances that were already split, and remain so after the change.
10531

10532
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
10533
    considered.
10534

10535
    @type changes: list of (node_name, new_group_uuid) pairs.
10536
    @param changes: list of node assignments to consider.
10537
    @param node_data: a dict with data for all nodes
10538
    @param instance_data: a dict with all instances to consider
10539
    @rtype: a two-tuple
10540
    @return: a list of instances that were previously okay and result split as a
10541
      consequence of this change, and a list of instances that were previously
10542
      split and this change does not fix.
10543

10544
    """
10545
    changed_nodes = dict((node, group) for node, group in changes
10546
                         if node_data[node].group != group)
10547

    
10548
    all_split_instances = set()
10549
    previously_split_instances = set()
10550

    
10551
    def InstanceNodes(instance):
10552
      return [instance.primary_node] + list(instance.secondary_nodes)
10553

    
10554
    for inst in instance_data.values():
10555
      if inst.disk_template not in constants.DTS_INT_MIRROR:
10556
        continue
10557

    
10558
      instance_nodes = InstanceNodes(inst)
10559

    
10560
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10561
        previously_split_instances.add(inst.name)
10562

    
10563
      if len(set(changed_nodes.get(node, node_data[node].group)
10564
                 for node in instance_nodes)) > 1:
10565
        all_split_instances.add(inst.name)
10566

    
10567
    return (list(all_split_instances - previously_split_instances),
10568
            list(previously_split_instances & all_split_instances))
10569

    
10570

    
10571
class _GroupQuery(_QueryBase):
10572
  FIELDS = query.GROUP_FIELDS
10573

    
10574
  def ExpandNames(self, lu):
10575
    lu.needed_locks = {}
10576

    
10577
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10578
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10579

    
10580
    if not self.names:
10581
      self.wanted = [name_to_uuid[name]
10582
                     for name in utils.NiceSort(name_to_uuid.keys())]
10583
    else:
10584
      # Accept names to be either names or UUIDs.
10585
      missing = []
10586
      self.wanted = []
10587
      all_uuid = frozenset(self._all_groups.keys())
10588

    
10589
      for name in self.names:
10590
        if name in all_uuid:
10591
          self.wanted.append(name)
10592
        elif name in name_to_uuid:
10593
          self.wanted.append(name_to_uuid[name])
10594
        else:
10595
          missing.append(name)
10596

    
10597
      if missing:
10598
        raise errors.OpPrereqError("Some groups do not exist: %s" % missing,
10599
                                   errors.ECODE_NOENT)
10600

    
10601
  def DeclareLocks(self, lu, level):
10602
    pass
10603

    
10604
  def _GetQueryData(self, lu):
10605
    """Computes the list of node groups and their attributes.
10606

10607
    """
10608
    do_nodes = query.GQ_NODE in self.requested_data
10609
    do_instances = query.GQ_INST in self.requested_data
10610

    
10611
    group_to_nodes = None
10612
    group_to_instances = None
10613

    
10614
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10615
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10616
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10617
    # instance->node. Hence, we will need to process nodes even if we only need
10618
    # instance information.
10619
    if do_nodes or do_instances:
10620
      all_nodes = lu.cfg.GetAllNodesInfo()
10621
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10622
      node_to_group = {}
10623

    
10624
      for node in all_nodes.values():
10625
        if node.group in group_to_nodes:
10626
          group_to_nodes[node.group].append(node.name)
10627
          node_to_group[node.name] = node.group
10628

    
10629
      if do_instances:
10630
        all_instances = lu.cfg.GetAllInstancesInfo()
10631
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10632

    
10633
        for instance in all_instances.values():
10634
          node = instance.primary_node
10635
          if node in node_to_group:
10636
            group_to_instances[node_to_group[node]].append(instance.name)
10637

    
10638
        if not do_nodes:
10639
          # Do not pass on node information if it was not requested.
10640
          group_to_nodes = None
10641

    
10642
    return query.GroupQueryData([self._all_groups[uuid]
10643
                                 for uuid in self.wanted],
10644
                                group_to_nodes, group_to_instances)
10645

    
10646

    
10647
class LUGroupQuery(NoHooksLU):
10648
  """Logical unit for querying node groups.
10649

10650
  """
10651
  REQ_BGL = False
10652

    
10653
  def CheckArguments(self):
10654
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
10655
                          self.op.output_fields, False)
10656

    
10657
  def ExpandNames(self):
10658
    self.gq.ExpandNames(self)
10659

    
10660
  def Exec(self, feedback_fn):
10661
    return self.gq.OldStyleQuery(self)
10662

    
10663

    
10664
class LUGroupSetParams(LogicalUnit):
10665
  """Modifies the parameters of a node group.
10666

10667
  """
10668
  HPATH = "group-modify"
10669
  HTYPE = constants.HTYPE_GROUP
10670
  REQ_BGL = False
10671

    
10672
  def CheckArguments(self):
10673
    all_changes = [
10674
      self.op.ndparams,
10675
      self.op.alloc_policy,
10676
      ]
10677

    
10678
    if all_changes.count(None) == len(all_changes):
10679
      raise errors.OpPrereqError("Please pass at least one modification",
10680
                                 errors.ECODE_INVAL)
10681

    
10682
  def ExpandNames(self):
10683
    # This raises errors.OpPrereqError on its own:
10684
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10685

    
10686
    self.needed_locks = {
10687
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10688
      }
10689

    
10690
  def CheckPrereq(self):
10691
    """Check prerequisites.
10692

10693
    """
10694
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10695

    
10696
    if self.group is None:
10697
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10698
                               (self.op.group_name, self.group_uuid))
10699

    
10700
    if self.op.ndparams:
10701
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10702
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10703
      self.new_ndparams = new_ndparams
10704

    
10705
  def BuildHooksEnv(self):
10706
    """Build hooks env.
10707

10708
    """
10709
    env = {
10710
      "GROUP_NAME": self.op.group_name,
10711
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10712
      }
10713
    mn = self.cfg.GetMasterNode()
10714
    return env, [mn], [mn]
10715

    
10716
  def Exec(self, feedback_fn):
10717
    """Modifies the node group.
10718

10719
    """
10720
    result = []
10721

    
10722
    if self.op.ndparams:
10723
      self.group.ndparams = self.new_ndparams
10724
      result.append(("ndparams", str(self.group.ndparams)))
10725

    
10726
    if self.op.alloc_policy:
10727
      self.group.alloc_policy = self.op.alloc_policy
10728

    
10729
    self.cfg.Update(self.group, feedback_fn)
10730
    return result
10731

    
10732

    
10733

    
10734
class LUGroupRemove(LogicalUnit):
10735
  HPATH = "group-remove"
10736
  HTYPE = constants.HTYPE_GROUP
10737
  REQ_BGL = False
10738

    
10739
  def ExpandNames(self):
10740
    # This will raises errors.OpPrereqError on its own:
10741
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10742
    self.needed_locks = {
10743
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10744
      }
10745

    
10746
  def CheckPrereq(self):
10747
    """Check prerequisites.
10748

10749
    This checks that the given group name exists as a node group, that is
10750
    empty (i.e., contains no nodes), and that is not the last group of the
10751
    cluster.
10752

10753
    """
10754
    # Verify that the group is empty.
10755
    group_nodes = [node.name
10756
                   for node in self.cfg.GetAllNodesInfo().values()
10757
                   if node.group == self.group_uuid]
10758

    
10759
    if group_nodes:
10760
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10761
                                 " nodes: %s" %
10762
                                 (self.op.group_name,
10763
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10764
                                 errors.ECODE_STATE)
10765

    
10766
    # Verify the cluster would not be left group-less.
10767
    if len(self.cfg.GetNodeGroupList()) == 1:
10768
      raise errors.OpPrereqError("Group '%s' is the only group,"
10769
                                 " cannot be removed" %
10770
                                 self.op.group_name,
10771
                                 errors.ECODE_STATE)
10772

    
10773
  def BuildHooksEnv(self):
10774
    """Build hooks env.
10775

10776
    """
10777
    env = {
10778
      "GROUP_NAME": self.op.group_name,
10779
      }
10780
    mn = self.cfg.GetMasterNode()
10781
    return env, [mn], [mn]
10782

    
10783
  def Exec(self, feedback_fn):
10784
    """Remove the node group.
10785

10786
    """
10787
    try:
10788
      self.cfg.RemoveNodeGroup(self.group_uuid)
10789
    except errors.ConfigurationError:
10790
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10791
                               (self.op.group_name, self.group_uuid))
10792

    
10793
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10794

    
10795

    
10796
class LUGroupRename(LogicalUnit):
10797
  HPATH = "group-rename"
10798
  HTYPE = constants.HTYPE_GROUP
10799
  REQ_BGL = False
10800

    
10801
  def ExpandNames(self):
10802
    # This raises errors.OpPrereqError on its own:
10803
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10804

    
10805
    self.needed_locks = {
10806
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10807
      }
10808

    
10809
  def CheckPrereq(self):
10810
    """Check prerequisites.
10811

10812
    Ensures requested new name is not yet used.
10813

10814
    """
10815
    try:
10816
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
10817
    except errors.OpPrereqError:
10818
      pass
10819
    else:
10820
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
10821
                                 " node group (UUID: %s)" %
10822
                                 (self.op.new_name, new_name_uuid),
10823
                                 errors.ECODE_EXISTS)
10824

    
10825
  def BuildHooksEnv(self):
10826
    """Build hooks env.
10827

10828
    """
10829
    env = {
10830
      "OLD_NAME": self.op.group_name,
10831
      "NEW_NAME": self.op.new_name,
10832
      }
10833

    
10834
    mn = self.cfg.GetMasterNode()
10835
    all_nodes = self.cfg.GetAllNodesInfo()
10836
    run_nodes = [mn]
10837
    all_nodes.pop(mn, None)
10838

    
10839
    for node in all_nodes.values():
10840
      if node.group == self.group_uuid:
10841
        run_nodes.append(node.name)
10842

    
10843
    return env, run_nodes, run_nodes
10844

    
10845
  def Exec(self, feedback_fn):
10846
    """Rename the node group.
10847

10848
    """
10849
    group = self.cfg.GetNodeGroup(self.group_uuid)
10850

    
10851
    if group is None:
10852
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10853
                               (self.op.group_name, self.group_uuid))
10854

    
10855
    group.name = self.op.new_name
10856
    self.cfg.Update(group, feedback_fn)
10857

    
10858
    return self.op.new_name
10859

    
10860

    
10861
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10862
  """Generic tags LU.
10863

10864
  This is an abstract class which is the parent of all the other tags LUs.
10865

10866
  """
10867

    
10868
  def ExpandNames(self):
10869
    self.needed_locks = {}
10870
    if self.op.kind == constants.TAG_NODE:
10871
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10872
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10873
    elif self.op.kind == constants.TAG_INSTANCE:
10874
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10875
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10876

    
10877
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10878
    # not possible to acquire the BGL based on opcode parameters)
10879

    
10880
  def CheckPrereq(self):
10881
    """Check prerequisites.
10882

10883
    """
10884
    if self.op.kind == constants.TAG_CLUSTER:
10885
      self.target = self.cfg.GetClusterInfo()
10886
    elif self.op.kind == constants.TAG_NODE:
10887
      self.target = self.cfg.GetNodeInfo(self.op.name)
10888
    elif self.op.kind == constants.TAG_INSTANCE:
10889
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10890
    else:
10891
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10892
                                 str(self.op.kind), errors.ECODE_INVAL)
10893

    
10894

    
10895
class LUTagsGet(TagsLU):
10896
  """Returns the tags of a given object.
10897

10898
  """
10899
  REQ_BGL = False
10900

    
10901
  def ExpandNames(self):
10902
    TagsLU.ExpandNames(self)
10903

    
10904
    # Share locks as this is only a read operation
10905
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10906

    
10907
  def Exec(self, feedback_fn):
10908
    """Returns the tag list.
10909

10910
    """
10911
    return list(self.target.GetTags())
10912

    
10913

    
10914
class LUTagsSearch(NoHooksLU):
10915
  """Searches the tags for a given pattern.
10916

10917
  """
10918
  REQ_BGL = False
10919

    
10920
  def ExpandNames(self):
10921
    self.needed_locks = {}
10922

    
10923
  def CheckPrereq(self):
10924
    """Check prerequisites.
10925

10926
    This checks the pattern passed for validity by compiling it.
10927

10928
    """
10929
    try:
10930
      self.re = re.compile(self.op.pattern)
10931
    except re.error, err:
10932
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10933
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10934

    
10935
  def Exec(self, feedback_fn):
10936
    """Returns the tag list.
10937

10938
    """
10939
    cfg = self.cfg
10940
    tgts = [("/cluster", cfg.GetClusterInfo())]
10941
    ilist = cfg.GetAllInstancesInfo().values()
10942
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10943
    nlist = cfg.GetAllNodesInfo().values()
10944
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10945
    results = []
10946
    for path, target in tgts:
10947
      for tag in target.GetTags():
10948
        if self.re.search(tag):
10949
          results.append((path, tag))
10950
    return results
10951

    
10952

    
10953
class LUTagsSet(TagsLU):
10954
  """Sets a tag on a given object.
10955

10956
  """
10957
  REQ_BGL = False
10958

    
10959
  def CheckPrereq(self):
10960
    """Check prerequisites.
10961

10962
    This checks the type and length of the tag name and value.
10963

10964
    """
10965
    TagsLU.CheckPrereq(self)
10966
    for tag in self.op.tags:
10967
      objects.TaggableObject.ValidateTag(tag)
10968

    
10969
  def Exec(self, feedback_fn):
10970
    """Sets the tag.
10971

10972
    """
10973
    try:
10974
      for tag in self.op.tags:
10975
        self.target.AddTag(tag)
10976
    except errors.TagError, err:
10977
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10978
    self.cfg.Update(self.target, feedback_fn)
10979

    
10980

    
10981
class LUTagsDel(TagsLU):
10982
  """Delete a list of tags from a given object.
10983

10984
  """
10985
  REQ_BGL = False
10986

    
10987
  def CheckPrereq(self):
10988
    """Check prerequisites.
10989

10990
    This checks that we have the given tag.
10991

10992
    """
10993
    TagsLU.CheckPrereq(self)
10994
    for tag in self.op.tags:
10995
      objects.TaggableObject.ValidateTag(tag)
10996
    del_tags = frozenset(self.op.tags)
10997
    cur_tags = self.target.GetTags()
10998

    
10999
    diff_tags = del_tags - cur_tags
11000
    if diff_tags:
11001
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11002
      raise errors.OpPrereqError("Tag(s) %s not found" %
11003
                                 (utils.CommaJoin(diff_names), ),
11004
                                 errors.ECODE_NOENT)
11005

    
11006
  def Exec(self, feedback_fn):
11007
    """Remove the tag from the object.
11008

11009
    """
11010
    for tag in self.op.tags:
11011
      self.target.RemoveTag(tag)
11012
    self.cfg.Update(self.target, feedback_fn)
11013

    
11014

    
11015
class LUTestDelay(NoHooksLU):
11016
  """Sleep for a specified amount of time.
11017

11018
  This LU sleeps on the master and/or nodes for a specified amount of
11019
  time.
11020

11021
  """
11022
  REQ_BGL = False
11023

    
11024
  def ExpandNames(self):
11025
    """Expand names and set required locks.
11026

11027
    This expands the node list, if any.
11028

11029
    """
11030
    self.needed_locks = {}
11031
    if self.op.on_nodes:
11032
      # _GetWantedNodes can be used here, but is not always appropriate to use
11033
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11034
      # more information.
11035
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11036
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11037

    
11038
  def _TestDelay(self):
11039
    """Do the actual sleep.
11040

11041
    """
11042
    if self.op.on_master:
11043
      if not utils.TestDelay(self.op.duration):
11044
        raise errors.OpExecError("Error during master delay test")
11045
    if self.op.on_nodes:
11046
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11047
      for node, node_result in result.items():
11048
        node_result.Raise("Failure during rpc call to node %s" % node)
11049

    
11050
  def Exec(self, feedback_fn):
11051
    """Execute the test delay opcode, with the wanted repetitions.
11052

11053
    """
11054
    if self.op.repeat == 0:
11055
      self._TestDelay()
11056
    else:
11057
      top_value = self.op.repeat - 1
11058
      for i in range(self.op.repeat):
11059
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11060
        self._TestDelay()
11061

    
11062

    
11063
class LUTestJqueue(NoHooksLU):
11064
  """Utility LU to test some aspects of the job queue.
11065

11066
  """
11067
  REQ_BGL = False
11068

    
11069
  # Must be lower than default timeout for WaitForJobChange to see whether it
11070
  # notices changed jobs
11071
  _CLIENT_CONNECT_TIMEOUT = 20.0
11072
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11073

    
11074
  @classmethod
11075
  def _NotifyUsingSocket(cls, cb, errcls):
11076
    """Opens a Unix socket and waits for another program to connect.
11077

11078
    @type cb: callable
11079
    @param cb: Callback to send socket name to client
11080
    @type errcls: class
11081
    @param errcls: Exception class to use for errors
11082

11083
    """
11084
    # Using a temporary directory as there's no easy way to create temporary
11085
    # sockets without writing a custom loop around tempfile.mktemp and
11086
    # socket.bind
11087
    tmpdir = tempfile.mkdtemp()
11088
    try:
11089
      tmpsock = utils.PathJoin(tmpdir, "sock")
11090

    
11091
      logging.debug("Creating temporary socket at %s", tmpsock)
11092
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11093
      try:
11094
        sock.bind(tmpsock)
11095
        sock.listen(1)
11096

    
11097
        # Send details to client
11098
        cb(tmpsock)
11099

    
11100
        # Wait for client to connect before continuing
11101
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11102
        try:
11103
          (conn, _) = sock.accept()
11104
        except socket.error, err:
11105
          raise errcls("Client didn't connect in time (%s)" % err)
11106
      finally:
11107
        sock.close()
11108
    finally:
11109
      # Remove as soon as client is connected
11110
      shutil.rmtree(tmpdir)
11111

    
11112
    # Wait for client to close
11113
    try:
11114
      try:
11115
        # pylint: disable-msg=E1101
11116
        # Instance of '_socketobject' has no ... member
11117
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11118
        conn.recv(1)
11119
      except socket.error, err:
11120
        raise errcls("Client failed to confirm notification (%s)" % err)
11121
    finally:
11122
      conn.close()
11123

    
11124
  def _SendNotification(self, test, arg, sockname):
11125
    """Sends a notification to the client.
11126

11127
    @type test: string
11128
    @param test: Test name
11129
    @param arg: Test argument (depends on test)
11130
    @type sockname: string
11131
    @param sockname: Socket path
11132

11133
    """
11134
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11135

    
11136
  def _Notify(self, prereq, test, arg):
11137
    """Notifies the client of a test.
11138

11139
    @type prereq: bool
11140
    @param prereq: Whether this is a prereq-phase test
11141
    @type test: string
11142
    @param test: Test name
11143
    @param arg: Test argument (depends on test)
11144

11145
    """
11146
    if prereq:
11147
      errcls = errors.OpPrereqError
11148
    else:
11149
      errcls = errors.OpExecError
11150

    
11151
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11152
                                                  test, arg),
11153
                                   errcls)
11154

    
11155
  def CheckArguments(self):
11156
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11157
    self.expandnames_calls = 0
11158

    
11159
  def ExpandNames(self):
11160
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11161
    if checkargs_calls < 1:
11162
      raise errors.ProgrammerError("CheckArguments was not called")
11163

    
11164
    self.expandnames_calls += 1
11165

    
11166
    if self.op.notify_waitlock:
11167
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11168

    
11169
    self.LogInfo("Expanding names")
11170

    
11171
    # Get lock on master node (just to get a lock, not for a particular reason)
11172
    self.needed_locks = {
11173
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11174
      }
11175

    
11176
  def Exec(self, feedback_fn):
11177
    if self.expandnames_calls < 1:
11178
      raise errors.ProgrammerError("ExpandNames was not called")
11179

    
11180
    if self.op.notify_exec:
11181
      self._Notify(False, constants.JQT_EXEC, None)
11182

    
11183
    self.LogInfo("Executing")
11184

    
11185
    if self.op.log_messages:
11186
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11187
      for idx, msg in enumerate(self.op.log_messages):
11188
        self.LogInfo("Sending log message %s", idx + 1)
11189
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11190
        # Report how many test messages have been sent
11191
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11192

    
11193
    if self.op.fail:
11194
      raise errors.OpExecError("Opcode failure was requested")
11195

    
11196
    return True
11197

    
11198

    
11199
class IAllocator(object):
11200
  """IAllocator framework.
11201

11202
  An IAllocator instance has three sets of attributes:
11203
    - cfg that is needed to query the cluster
11204
    - input data (all members of the _KEYS class attribute are required)
11205
    - four buffer attributes (in|out_data|text), that represent the
11206
      input (to the external script) in text and data structure format,
11207
      and the output from it, again in two formats
11208
    - the result variables from the script (success, info, nodes) for
11209
      easy usage
11210

11211
  """
11212
  # pylint: disable-msg=R0902
11213
  # lots of instance attributes
11214
  _ALLO_KEYS = [
11215
    "name", "mem_size", "disks", "disk_template",
11216
    "os", "tags", "nics", "vcpus", "hypervisor",
11217
    ]
11218
  _RELO_KEYS = [
11219
    "name", "relocate_from",
11220
    ]
11221
  _EVAC_KEYS = [
11222
    "evac_nodes",
11223
    ]
11224

    
11225
  def __init__(self, cfg, rpc, mode, **kwargs):
11226
    self.cfg = cfg
11227
    self.rpc = rpc
11228
    # init buffer variables
11229
    self.in_text = self.out_text = self.in_data = self.out_data = None
11230
    # init all input fields so that pylint is happy
11231
    self.mode = mode
11232
    self.mem_size = self.disks = self.disk_template = None
11233
    self.os = self.tags = self.nics = self.vcpus = None
11234
    self.hypervisor = None
11235
    self.relocate_from = None
11236
    self.name = None
11237
    self.evac_nodes = None
11238
    # computed fields
11239
    self.required_nodes = None
11240
    # init result fields
11241
    self.success = self.info = self.result = None
11242
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11243
      keyset = self._ALLO_KEYS
11244
      fn = self._AddNewInstance
11245
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11246
      keyset = self._RELO_KEYS
11247
      fn = self._AddRelocateInstance
11248
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11249
      keyset = self._EVAC_KEYS
11250
      fn = self._AddEvacuateNodes
11251
    else:
11252
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11253
                                   " IAllocator" % self.mode)
11254
    for key in kwargs:
11255
      if key not in keyset:
11256
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11257
                                     " IAllocator" % key)
11258
      setattr(self, key, kwargs[key])
11259

    
11260
    for key in keyset:
11261
      if key not in kwargs:
11262
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11263
                                     " IAllocator" % key)
11264
    self._BuildInputData(fn)
11265

    
11266
  def _ComputeClusterData(self):
11267
    """Compute the generic allocator input data.
11268

11269
    This is the data that is independent of the actual operation.
11270

11271
    """
11272
    cfg = self.cfg
11273
    cluster_info = cfg.GetClusterInfo()
11274
    # cluster data
11275
    data = {
11276
      "version": constants.IALLOCATOR_VERSION,
11277
      "cluster_name": cfg.GetClusterName(),
11278
      "cluster_tags": list(cluster_info.GetTags()),
11279
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11280
      # we don't have job IDs
11281
      }
11282
    ninfo = cfg.GetAllNodesInfo()
11283
    iinfo = cfg.GetAllInstancesInfo().values()
11284
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11285

    
11286
    # node data
11287
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11288

    
11289
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11290
      hypervisor_name = self.hypervisor
11291
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11292
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11293
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
11294
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11295

    
11296
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11297
                                        hypervisor_name)
11298
    node_iinfo = \
11299
      self.rpc.call_all_instances_info(node_list,
11300
                                       cluster_info.enabled_hypervisors)
11301

    
11302
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11303

    
11304
    config_ndata = self._ComputeBasicNodeData(ninfo)
11305
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
11306
                                                 i_list, config_ndata)
11307
    assert len(data["nodes"]) == len(ninfo), \
11308
        "Incomplete node data computed"
11309

    
11310
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
11311

    
11312
    self.in_data = data
11313

    
11314
  @staticmethod
11315
  def _ComputeNodeGroupData(cfg):
11316
    """Compute node groups data.
11317

11318
    """
11319
    ng = {}
11320
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
11321
      ng[guuid] = {
11322
        "name": gdata.name,
11323
        "alloc_policy": gdata.alloc_policy,
11324
        }
11325
    return ng
11326

    
11327
  @staticmethod
11328
  def _ComputeBasicNodeData(node_cfg):
11329
    """Compute global node data.
11330

11331
    @rtype: dict
11332
    @returns: a dict of name: (node dict, node config)
11333

11334
    """
11335
    node_results = {}
11336
    for ninfo in node_cfg.values():
11337
      # fill in static (config-based) values
11338
      pnr = {
11339
        "tags": list(ninfo.GetTags()),
11340
        "primary_ip": ninfo.primary_ip,
11341
        "secondary_ip": ninfo.secondary_ip,
11342
        "offline": ninfo.offline,
11343
        "drained": ninfo.drained,
11344
        "master_candidate": ninfo.master_candidate,
11345
        "group": ninfo.group,
11346
        "master_capable": ninfo.master_capable,
11347
        "vm_capable": ninfo.vm_capable,
11348
        }
11349

    
11350
      node_results[ninfo.name] = pnr
11351

    
11352
    return node_results
11353

    
11354
  @staticmethod
11355
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
11356
                              node_results):
11357
    """Compute global node data.
11358

11359
    @param node_results: the basic node structures as filled from the config
11360

11361
    """
11362
    # make a copy of the current dict
11363
    node_results = dict(node_results)
11364
    for nname, nresult in node_data.items():
11365
      assert nname in node_results, "Missing basic data for node %s" % nname
11366
      ninfo = node_cfg[nname]
11367

    
11368
      if not (ninfo.offline or ninfo.drained):
11369
        nresult.Raise("Can't get data for node %s" % nname)
11370
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11371
                                nname)
11372
        remote_info = nresult.payload
11373

    
11374
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11375
                     'vg_size', 'vg_free', 'cpu_total']:
11376
          if attr not in remote_info:
11377
            raise errors.OpExecError("Node '%s' didn't return attribute"
11378
                                     " '%s'" % (nname, attr))
11379
          if not isinstance(remote_info[attr], int):
11380
            raise errors.OpExecError("Node '%s' returned invalid value"
11381
                                     " for '%s': %s" %
11382
                                     (nname, attr, remote_info[attr]))
11383
        # compute memory used by primary instances
11384
        i_p_mem = i_p_up_mem = 0
11385
        for iinfo, beinfo in i_list:
11386
          if iinfo.primary_node == nname:
11387
            i_p_mem += beinfo[constants.BE_MEMORY]
11388
            if iinfo.name not in node_iinfo[nname].payload:
11389
              i_used_mem = 0
11390
            else:
11391
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11392
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11393
            remote_info['memory_free'] -= max(0, i_mem_diff)
11394

    
11395
            if iinfo.admin_up:
11396
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11397

    
11398
        # compute memory used by instances
11399
        pnr_dyn = {
11400
          "total_memory": remote_info['memory_total'],
11401
          "reserved_memory": remote_info['memory_dom0'],
11402
          "free_memory": remote_info['memory_free'],
11403
          "total_disk": remote_info['vg_size'],
11404
          "free_disk": remote_info['vg_free'],
11405
          "total_cpus": remote_info['cpu_total'],
11406
          "i_pri_memory": i_p_mem,
11407
          "i_pri_up_memory": i_p_up_mem,
11408
          }
11409
        pnr_dyn.update(node_results[nname])
11410
        node_results[nname] = pnr_dyn
11411

    
11412
    return node_results
11413

    
11414
  @staticmethod
11415
  def _ComputeInstanceData(cluster_info, i_list):
11416
    """Compute global instance data.
11417

11418
    """
11419
    instance_data = {}
11420
    for iinfo, beinfo in i_list:
11421
      nic_data = []
11422
      for nic in iinfo.nics:
11423
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
11424
        nic_dict = {"mac": nic.mac,
11425
                    "ip": nic.ip,
11426
                    "mode": filled_params[constants.NIC_MODE],
11427
                    "link": filled_params[constants.NIC_LINK],
11428
                   }
11429
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
11430
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
11431
        nic_data.append(nic_dict)
11432
      pir = {
11433
        "tags": list(iinfo.GetTags()),
11434
        "admin_up": iinfo.admin_up,
11435
        "vcpus": beinfo[constants.BE_VCPUS],
11436
        "memory": beinfo[constants.BE_MEMORY],
11437
        "os": iinfo.os,
11438
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
11439
        "nics": nic_data,
11440
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
11441
        "disk_template": iinfo.disk_template,
11442
        "hypervisor": iinfo.hypervisor,
11443
        }
11444
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
11445
                                                 pir["disks"])
11446
      instance_data[iinfo.name] = pir
11447

    
11448
    return instance_data
11449

    
11450
  def _AddNewInstance(self):
11451
    """Add new instance data to allocator structure.
11452

11453
    This in combination with _AllocatorGetClusterData will create the
11454
    correct structure needed as input for the allocator.
11455

11456
    The checks for the completeness of the opcode must have already been
11457
    done.
11458

11459
    """
11460
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11461

    
11462
    if self.disk_template in constants.DTS_INT_MIRROR:
11463
      self.required_nodes = 2
11464
    else:
11465
      self.required_nodes = 1
11466
    request = {
11467
      "name": self.name,
11468
      "disk_template": self.disk_template,
11469
      "tags": self.tags,
11470
      "os": self.os,
11471
      "vcpus": self.vcpus,
11472
      "memory": self.mem_size,
11473
      "disks": self.disks,
11474
      "disk_space_total": disk_space,
11475
      "nics": self.nics,
11476
      "required_nodes": self.required_nodes,
11477
      }
11478
    return request
11479

    
11480
  def _AddRelocateInstance(self):
11481
    """Add relocate instance data to allocator structure.
11482

11483
    This in combination with _IAllocatorGetClusterData will create the
11484
    correct structure needed as input for the allocator.
11485

11486
    The checks for the completeness of the opcode must have already been
11487
    done.
11488

11489
    """
11490
    instance = self.cfg.GetInstanceInfo(self.name)
11491
    if instance is None:
11492
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11493
                                   " IAllocator" % self.name)
11494

    
11495
    if instance.disk_template not in constants.DTS_MIRRORED:
11496
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11497
                                 errors.ECODE_INVAL)
11498

    
11499
    if instance.disk_template in constants.DTS_INT_MIRROR and \
11500
        len(instance.secondary_nodes) != 1:
11501
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11502
                                 errors.ECODE_STATE)
11503

    
11504
    self.required_nodes = 1
11505
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11506
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11507

    
11508
    request = {
11509
      "name": self.name,
11510
      "disk_space_total": disk_space,
11511
      "required_nodes": self.required_nodes,
11512
      "relocate_from": self.relocate_from,
11513
      }
11514
    return request
11515

    
11516
  def _AddEvacuateNodes(self):
11517
    """Add evacuate nodes data to allocator structure.
11518

11519
    """
11520
    request = {
11521
      "evac_nodes": self.evac_nodes
11522
      }
11523
    return request
11524

    
11525
  def _BuildInputData(self, fn):
11526
    """Build input data structures.
11527

11528
    """
11529
    self._ComputeClusterData()
11530

    
11531
    request = fn()
11532
    request["type"] = self.mode
11533
    self.in_data["request"] = request
11534

    
11535
    self.in_text = serializer.Dump(self.in_data)
11536

    
11537
  def Run(self, name, validate=True, call_fn=None):
11538
    """Run an instance allocator and return the results.
11539

11540
    """
11541
    if call_fn is None:
11542
      call_fn = self.rpc.call_iallocator_runner
11543

    
11544
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11545
    result.Raise("Failure while running the iallocator script")
11546

    
11547
    self.out_text = result.payload
11548
    if validate:
11549
      self._ValidateResult()
11550

    
11551
  def _ValidateResult(self):
11552
    """Process the allocator results.
11553

11554
    This will process and if successful save the result in
11555
    self.out_data and the other parameters.
11556

11557
    """
11558
    try:
11559
      rdict = serializer.Load(self.out_text)
11560
    except Exception, err:
11561
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11562

    
11563
    if not isinstance(rdict, dict):
11564
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11565

    
11566
    # TODO: remove backwards compatiblity in later versions
11567
    if "nodes" in rdict and "result" not in rdict:
11568
      rdict["result"] = rdict["nodes"]
11569
      del rdict["nodes"]
11570

    
11571
    for key in "success", "info", "result":
11572
      if key not in rdict:
11573
        raise errors.OpExecError("Can't parse iallocator results:"
11574
                                 " missing key '%s'" % key)
11575
      setattr(self, key, rdict[key])
11576

    
11577
    if not isinstance(rdict["result"], list):
11578
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11579
                               " is not a list")
11580
    self.out_data = rdict
11581

    
11582

    
11583
class LUTestAllocator(NoHooksLU):
11584
  """Run allocator tests.
11585

11586
  This LU runs the allocator tests
11587

11588
  """
11589
  def CheckPrereq(self):
11590
    """Check prerequisites.
11591

11592
    This checks the opcode parameters depending on the director and mode test.
11593

11594
    """
11595
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11596
      for attr in ["mem_size", "disks", "disk_template",
11597
                   "os", "tags", "nics", "vcpus"]:
11598
        if not hasattr(self.op, attr):
11599
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11600
                                     attr, errors.ECODE_INVAL)
11601
      iname = self.cfg.ExpandInstanceName(self.op.name)
11602
      if iname is not None:
11603
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11604
                                   iname, errors.ECODE_EXISTS)
11605
      if not isinstance(self.op.nics, list):
11606
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11607
                                   errors.ECODE_INVAL)
11608
      if not isinstance(self.op.disks, list):
11609
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11610
                                   errors.ECODE_INVAL)
11611
      for row in self.op.disks:
11612
        if (not isinstance(row, dict) or
11613
            "size" not in row or
11614
            not isinstance(row["size"], int) or
11615
            "mode" not in row or
11616
            row["mode"] not in ['r', 'w']):
11617
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11618
                                     " parameter", errors.ECODE_INVAL)
11619
      if self.op.hypervisor is None:
11620
        self.op.hypervisor = self.cfg.GetHypervisorType()
11621
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11622
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11623
      self.op.name = fname
11624
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11625
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11626
      if not hasattr(self.op, "evac_nodes"):
11627
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11628
                                   " opcode input", errors.ECODE_INVAL)
11629
    else:
11630
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11631
                                 self.op.mode, errors.ECODE_INVAL)
11632

    
11633
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11634
      if self.op.allocator is None:
11635
        raise errors.OpPrereqError("Missing allocator name",
11636
                                   errors.ECODE_INVAL)
11637
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11638
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11639
                                 self.op.direction, errors.ECODE_INVAL)
11640

    
11641
  def Exec(self, feedback_fn):
11642
    """Run the allocator test.
11643

11644
    """
11645
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11646
      ial = IAllocator(self.cfg, self.rpc,
11647
                       mode=self.op.mode,
11648
                       name=self.op.name,
11649
                       mem_size=self.op.mem_size,
11650
                       disks=self.op.disks,
11651
                       disk_template=self.op.disk_template,
11652
                       os=self.op.os,
11653
                       tags=self.op.tags,
11654
                       nics=self.op.nics,
11655
                       vcpus=self.op.vcpus,
11656
                       hypervisor=self.op.hypervisor,
11657
                       )
11658
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11659
      ial = IAllocator(self.cfg, self.rpc,
11660
                       mode=self.op.mode,
11661
                       name=self.op.name,
11662
                       relocate_from=list(self.relocate_from),
11663
                       )
11664
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11665
      ial = IAllocator(self.cfg, self.rpc,
11666
                       mode=self.op.mode,
11667
                       evac_nodes=self.op.evac_nodes)
11668
    else:
11669
      raise errors.ProgrammerError("Uncatched mode %s in"
11670
                                   " LUTestAllocator.Exec", self.op.mode)
11671

    
11672
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11673
      result = ial.in_text
11674
    else:
11675
      ial.Run(self.op.allocator, validate=False)
11676
      result = ial.out_text
11677
    return result
11678

    
11679

    
11680
#: Query type implementations
11681
_QUERY_IMPL = {
11682
  constants.QR_INSTANCE: _InstanceQuery,
11683
  constants.QR_NODE: _NodeQuery,
11684
  constants.QR_GROUP: _GroupQuery,
11685
  constants.QR_OS: _OsQuery,
11686
  }
11687

    
11688
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
11689

    
11690

    
11691
def _GetQueryImplementation(name):
11692
  """Returns the implemtnation for a query type.
11693

11694
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
11695

11696
  """
11697
  try:
11698
    return _QUERY_IMPL[name]
11699
  except KeyError:
11700
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11701
                               errors.ECODE_INVAL)