Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 197e3bb2

History | View | Annotate | Download (372.9 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

    
43
from ganeti import ssh
44
from ganeti import utils
45
from ganeti import errors
46
from ganeti import hypervisor
47
from ganeti import locking
48
from ganeti import constants
49
from ganeti import objects
50
from ganeti import serializer
51
from ganeti import ssconf
52
from ganeti import uidpool
53
from ganeti import compat
54
from ganeti import masterd
55
from ganeti import netutils
56
from ganeti import ht
57

    
58
import ganeti.masterd.instance # pylint: disable-msg=W0611
59

    
60
# Common opcode attributes
61

    
62
#: output fields for a query operation
63
_POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString))
64

    
65

    
66
#: the shutdown timeout
67
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
68
                     ht.TPositiveInt)
69

    
70
#: the force parameter
71
_PForce = ("force", False, ht.TBool)
72

    
73
#: a required instance name (for single-instance LUs)
74
_PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString)
75

    
76
#: Whether to ignore offline nodes
77
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool)
78

    
79
#: a required node name (for single-node LUs)
80
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString)
81

    
82
#: the migration type (live/non-live)
83
_PMigrationMode = ("mode", None,
84
                   ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)))
85

    
86
#: the obsolete 'live' mode (boolean)
87
_PMigrationLive = ("live", None, ht.TMaybeBool)
88

    
89

    
90
# End types
91
class LogicalUnit(object):
92
  """Logical Unit base class.
93

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

103
  Note that all commands require root permissions.
104

105
  @ivar dry_run_result: the value (if any) that will be returned to the caller
106
      in dry-run mode (signalled by opcode dry_run parameter)
107
  @cvar _OP_PARAMS: a list of opcode attributes, their defaults values
108
      they should get if not already defined, and types they must match
109

110
  """
111
  HPATH = None
112
  HTYPE = None
113
  _OP_PARAMS = []
114
  REQ_BGL = True
115

    
116
  def __init__(self, processor, op, context, rpc):
117
    """Constructor for LogicalUnit.
118

119
    This needs to be overridden in derived classes in order to check op
120
    validity.
121

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

    
149
    # Tasklets
150
    self.tasklets = None
151

    
152
    # The new kind-of-type-system
153
    op_id = self.op.OP_ID
154
    for attr_name, aval, test in self._OP_PARAMS:
155
      if not hasattr(op, attr_name):
156
        if aval == ht.NoDefault:
157
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
158
                                     (op_id, attr_name), errors.ECODE_INVAL)
159
        else:
160
          if callable(aval):
161
            dval = aval()
162
          else:
163
            dval = aval
164
          setattr(self.op, attr_name, dval)
165
      attr_val = getattr(op, attr_name)
166
      if test == ht.NoType:
167
        # no tests here
168
        continue
169
      if not callable(test):
170
        raise errors.ProgrammerError("Validation for parameter '%s.%s' failed,"
171
                                     " given type is not a proper type (%s)" %
172
                                     (op_id, attr_name, test))
173
      if not test(attr_val):
174
        logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
175
                      self.op.OP_ID, attr_name, type(attr_val), attr_val)
176
        raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
177
                                   (op_id, attr_name), errors.ECODE_INVAL)
178

    
179
    self.CheckArguments()
180

    
181
  def __GetSSH(self):
182
    """Returns the SshRunner object
183

184
    """
185
    if not self.__ssh:
186
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
187
    return self.__ssh
188

    
189
  ssh = property(fget=__GetSSH)
190

    
191
  def CheckArguments(self):
192
    """Check syntactic validity for the opcode arguments.
193

194
    This method is for doing a simple syntactic check and ensure
195
    validity of opcode parameters, without any cluster-related
196
    checks. While the same can be accomplished in ExpandNames and/or
197
    CheckPrereq, doing these separate is better because:
198

199
      - ExpandNames is left as as purely a lock-related function
200
      - CheckPrereq is run after we have acquired locks (and possible
201
        waited for them)
202

203
    The function is allowed to change the self.op attribute so that
204
    later methods can no longer worry about missing parameters.
205

206
    """
207
    pass
208

    
209
  def ExpandNames(self):
210
    """Expand names for this LU.
211

212
    This method is called before starting to execute the opcode, and it should
213
    update all the parameters of the opcode to their canonical form (e.g. a
214
    short node name must be fully expanded after this method has successfully
215
    completed). This way locking, hooks, logging, ecc. can work correctly.
216

217
    LUs which implement this method must also populate the self.needed_locks
218
    member, as a dict with lock levels as keys, and a list of needed lock names
219
    as values. Rules:
220

221
      - use an empty dict if you don't need any lock
222
      - if you don't need any lock at a particular level omit that level
223
      - don't put anything for the BGL level
224
      - if you want all locks at a level use locking.ALL_SET as a value
225

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

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

234
    Examples::
235

236
      # Acquire all nodes and one instance
237
      self.needed_locks = {
238
        locking.LEVEL_NODE: locking.ALL_SET,
239
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
240
      }
241
      # Acquire just two nodes
242
      self.needed_locks = {
243
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
244
      }
245
      # Acquire no locks
246
      self.needed_locks = {} # No, you can't leave it to the default value None
247

248
    """
249
    # The implementation of this method is mandatory only if the new LU is
250
    # concurrent, so that old LUs don't need to be changed all at the same
251
    # time.
252
    if self.REQ_BGL:
253
      self.needed_locks = {} # Exclusive LUs don't need locks.
254
    else:
255
      raise NotImplementedError
256

    
257
  def DeclareLocks(self, level):
258
    """Declare LU locking needs for a level
259

260
    While most LUs can just declare their locking needs at ExpandNames time,
261
    sometimes there's the need to calculate some locks after having acquired
262
    the ones before. This function is called just before acquiring locks at a
263
    particular level, but after acquiring the ones at lower levels, and permits
264
    such calculations. It can be used to modify self.needed_locks, and by
265
    default it does nothing.
266

267
    This function is only called if you have something already set in
268
    self.needed_locks for the level.
269

270
    @param level: Locking level which is going to be locked
271
    @type level: member of ganeti.locking.LEVELS
272

273
    """
274

    
275
  def CheckPrereq(self):
276
    """Check prerequisites for this LU.
277

278
    This method should check that the prerequisites for the execution
279
    of this LU are fulfilled. It can do internode communication, but
280
    it should be idempotent - no cluster or system changes are
281
    allowed.
282

283
    The method should raise errors.OpPrereqError in case something is
284
    not fulfilled. Its return value is ignored.
285

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

289
    """
290
    if self.tasklets is not None:
291
      for (idx, tl) in enumerate(self.tasklets):
292
        logging.debug("Checking prerequisites for tasklet %s/%s",
293
                      idx + 1, len(self.tasklets))
294
        tl.CheckPrereq()
295
    else:
296
      pass
297

    
298
  def Exec(self, feedback_fn):
299
    """Execute the LU.
300

301
    This method should implement the actual work. It should raise
302
    errors.OpExecError for failures that are somewhat dealt with in
303
    code, or expected.
304

305
    """
306
    if self.tasklets is not None:
307
      for (idx, tl) in enumerate(self.tasklets):
308
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
309
        tl.Exec(feedback_fn)
310
    else:
311
      raise NotImplementedError
312

    
313
  def BuildHooksEnv(self):
314
    """Build hooks environment for this LU.
315

316
    This method should return a three-node tuple consisting of: a dict
317
    containing the environment that will be used for running the
318
    specific hook for this LU, a list of node names on which the hook
319
    should run before the execution, and a list of node names on which
320
    the hook should run after the execution.
321

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

327
    No nodes should be returned as an empty list (and not None).
328

329
    Note that if the HPATH for a LU class is None, this function will
330
    not be called.
331

332
    """
333
    raise NotImplementedError
334

    
335
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
336
    """Notify the LU about the results of its hooks.
337

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

344
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
345
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
346
    @param hook_results: the results of the multi-node hooks rpc call
347
    @param feedback_fn: function used send feedback back to the caller
348
    @param lu_result: the previous Exec result this LU had, or None
349
        in the PRE phase
350
    @return: the new Exec result, based on the previous result
351
        and hook results
352

353
    """
354
    # API must be kept, thus we ignore the unused argument and could
355
    # be a function warnings
356
    # pylint: disable-msg=W0613,R0201
357
    return lu_result
358

    
359
  def _ExpandAndLockInstance(self):
360
    """Helper function to expand and lock an instance.
361

362
    Many LUs that work on an instance take its name in self.op.instance_name
363
    and need to expand it and then declare the expanded name for locking. This
364
    function does it, and then updates self.op.instance_name to the expanded
365
    name. It also initializes needed_locks as a dict, if this hasn't been done
366
    before.
367

368
    """
369
    if self.needed_locks is None:
370
      self.needed_locks = {}
371
    else:
372
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
373
        "_ExpandAndLockInstance called with instance-level locks set"
374
    self.op.instance_name = _ExpandInstanceName(self.cfg,
375
                                                self.op.instance_name)
376
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
377

    
378
  def _LockInstancesNodes(self, primary_only=False):
379
    """Helper function to declare instances' nodes for locking.
380

381
    This function should be called after locking one or more instances to lock
382
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
383
    with all primary or secondary nodes for instances already locked and
384
    present in self.needed_locks[locking.LEVEL_INSTANCE].
385

386
    It should be called from DeclareLocks, and for safety only works if
387
    self.recalculate_locks[locking.LEVEL_NODE] is set.
388

389
    In the future it may grow parameters to just lock some instance's nodes, or
390
    to just lock primaries or secondary nodes, if needed.
391

392
    If should be called in DeclareLocks in a way similar to::
393

394
      if level == locking.LEVEL_NODE:
395
        self._LockInstancesNodes()
396

397
    @type primary_only: boolean
398
    @param primary_only: only lock primary nodes of locked instances
399

400
    """
401
    assert locking.LEVEL_NODE in self.recalculate_locks, \
402
      "_LockInstancesNodes helper function called with no nodes to recalculate"
403

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

    
406
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
407
    # future we might want to have different behaviors depending on the value
408
    # of self.recalculate_locks[locking.LEVEL_NODE]
409
    wanted_nodes = []
410
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
411
      instance = self.context.cfg.GetInstanceInfo(instance_name)
412
      wanted_nodes.append(instance.primary_node)
413
      if not primary_only:
414
        wanted_nodes.extend(instance.secondary_nodes)
415

    
416
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
417
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
418
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
419
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
420

    
421
    del self.recalculate_locks[locking.LEVEL_NODE]
422

    
423

    
424
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
425
  """Simple LU which runs no hooks.
426

427
  This LU is intended as a parent for other LogicalUnits which will
428
  run no hooks, in order to reduce duplicate code.
429

430
  """
431
  HPATH = None
432
  HTYPE = None
433

    
434
  def BuildHooksEnv(self):
435
    """Empty BuildHooksEnv for NoHooksLu.
436

437
    This just raises an error.
438

439
    """
440
    assert False, "BuildHooksEnv called for NoHooksLUs"
441

    
442

    
443
class Tasklet:
444
  """Tasklet base class.
445

446
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
447
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
448
  tasklets know nothing about locks.
449

450
  Subclasses must follow these rules:
451
    - Implement CheckPrereq
452
    - Implement Exec
453

454
  """
455
  def __init__(self, lu):
456
    self.lu = lu
457

    
458
    # Shortcuts
459
    self.cfg = lu.cfg
460
    self.rpc = lu.rpc
461

    
462
  def CheckPrereq(self):
463
    """Check prerequisites for this tasklets.
464

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

469
    The method should raise errors.OpPrereqError in case something is not
470
    fulfilled. Its return value is ignored.
471

472
    This method should also update all parameters to their canonical form if it
473
    hasn't been done before.
474

475
    """
476
    pass
477

    
478
  def Exec(self, feedback_fn):
479
    """Execute the tasklet.
480

481
    This method should implement the actual work. It should raise
482
    errors.OpExecError for failures that are somewhat dealt with in code, or
483
    expected.
484

485
    """
486
    raise NotImplementedError
487

    
488

    
489
def _GetWantedNodes(lu, nodes):
490
  """Returns list of checked and expanded node names.
491

492
  @type lu: L{LogicalUnit}
493
  @param lu: the logical unit on whose behalf we execute
494
  @type nodes: list
495
  @param nodes: list of node names or None for all nodes
496
  @rtype: list
497
  @return: the list of nodes, sorted
498
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
499

500
  """
501
  if not nodes:
502
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
503
      " non-empty list of nodes whose name is to be expanded.")
504

    
505
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
506
  return utils.NiceSort(wanted)
507

    
508

    
509
def _GetWantedInstances(lu, instances):
510
  """Returns list of checked and expanded instance names.
511

512
  @type lu: L{LogicalUnit}
513
  @param lu: the logical unit on whose behalf we execute
514
  @type instances: list
515
  @param instances: list of instance names or None for all instances
516
  @rtype: list
517
  @return: the list of instances, sorted
518
  @raise errors.OpPrereqError: if the instances parameter is wrong type
519
  @raise errors.OpPrereqError: if any of the passed instances is not found
520

521
  """
522
  if instances:
523
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
524
  else:
525
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
526
  return wanted
527

    
528

    
529
def _GetUpdatedParams(old_params, update_dict,
530
                      use_default=True, use_none=False):
531
  """Return the new version of a parameter dictionary.
532

533
  @type old_params: dict
534
  @param old_params: old parameters
535
  @type update_dict: dict
536
  @param update_dict: dict containing new parameter values, or
537
      constants.VALUE_DEFAULT to reset the parameter to its default
538
      value
539
  @param use_default: boolean
540
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
541
      values as 'to be deleted' values
542
  @param use_none: boolean
543
  @type use_none: whether to recognise C{None} values as 'to be
544
      deleted' values
545
  @rtype: dict
546
  @return: the new parameter dictionary
547

548
  """
549
  params_copy = copy.deepcopy(old_params)
550
  for key, val in update_dict.iteritems():
551
    if ((use_default and val == constants.VALUE_DEFAULT) or
552
        (use_none and val is None)):
553
      try:
554
        del params_copy[key]
555
      except KeyError:
556
        pass
557
    else:
558
      params_copy[key] = val
559
  return params_copy
560

    
561

    
562
def _CheckOutputFields(static, dynamic, selected):
563
  """Checks whether all selected fields are valid.
564

565
  @type static: L{utils.FieldSet}
566
  @param static: static fields set
567
  @type dynamic: L{utils.FieldSet}
568
  @param dynamic: dynamic fields set
569

570
  """
571
  f = utils.FieldSet()
572
  f.Extend(static)
573
  f.Extend(dynamic)
574

    
575
  delta = f.NonMatching(selected)
576
  if delta:
577
    raise errors.OpPrereqError("Unknown output fields selected: %s"
578
                               % ",".join(delta), errors.ECODE_INVAL)
579

    
580

    
581
def _CheckGlobalHvParams(params):
582
  """Validates that given hypervisor params are not global ones.
583

584
  This will ensure that instances don't get customised versions of
585
  global params.
586

587
  """
588
  used_globals = constants.HVC_GLOBALS.intersection(params)
589
  if used_globals:
590
    msg = ("The following hypervisor parameters are global and cannot"
591
           " be customized at instance level, please modify them at"
592
           " cluster level: %s" % utils.CommaJoin(used_globals))
593
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
594

    
595

    
596
def _CheckNodeOnline(lu, node):
597
  """Ensure that a given node is online.
598

599
  @param lu: the LU on behalf of which we make the check
600
  @param node: the node to check
601
  @raise errors.OpPrereqError: if the node is offline
602

603
  """
604
  if lu.cfg.GetNodeInfo(node).offline:
605
    raise errors.OpPrereqError("Can't use offline node %s" % node,
606
                               errors.ECODE_INVAL)
607

    
608

    
609
def _CheckNodeNotDrained(lu, node):
610
  """Ensure that a given node is not drained.
611

612
  @param lu: the LU on behalf of which we make the check
613
  @param node: the node to check
614
  @raise errors.OpPrereqError: if the node is drained
615

616
  """
617
  if lu.cfg.GetNodeInfo(node).drained:
618
    raise errors.OpPrereqError("Can't use drained node %s" % node,
619
                               errors.ECODE_INVAL)
620

    
621

    
622
def _CheckNodeHasOS(lu, node, os_name, force_variant):
623
  """Ensure that a node supports a given OS.
624

625
  @param lu: the LU on behalf of which we make the check
626
  @param node: the node to check
627
  @param os_name: the OS to query about
628
  @param force_variant: whether to ignore variant errors
629
  @raise errors.OpPrereqError: if the node is not supporting the OS
630

631
  """
632
  result = lu.rpc.call_os_get(node, os_name)
633
  result.Raise("OS '%s' not in supported OS list for node %s" %
634
               (os_name, node),
635
               prereq=True, ecode=errors.ECODE_INVAL)
636
  if not force_variant:
637
    _CheckOSVariant(result.payload, os_name)
638

    
639

    
640
def _RequireFileStorage():
641
  """Checks that file storage is enabled.
642

643
  @raise errors.OpPrereqError: when file storage is disabled
644

645
  """
646
  if not constants.ENABLE_FILE_STORAGE:
647
    raise errors.OpPrereqError("File storage disabled at configure time",
648
                               errors.ECODE_INVAL)
649

    
650

    
651
def _CheckDiskTemplate(template):
652
  """Ensure a given disk template is valid.
653

654
  """
655
  if template not in constants.DISK_TEMPLATES:
656
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
657
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
658
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
659
  if template == constants.DT_FILE:
660
    _RequireFileStorage()
661
  return True
662

    
663

    
664
def _CheckStorageType(storage_type):
665
  """Ensure a given storage type is valid.
666

667
  """
668
  if storage_type not in constants.VALID_STORAGE_TYPES:
669
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
670
                               errors.ECODE_INVAL)
671
  if storage_type == constants.ST_FILE:
672
    _RequireFileStorage()
673
  return True
674

    
675

    
676
def _GetClusterDomainSecret():
677
  """Reads the cluster domain secret.
678

679
  """
680
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
681
                               strict=True)
682

    
683

    
684
def _CheckInstanceDown(lu, instance, reason):
685
  """Ensure that an instance is not running."""
686
  if instance.admin_up:
687
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
688
                               (instance.name, reason), errors.ECODE_STATE)
689

    
690
  pnode = instance.primary_node
691
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
692
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
693
              prereq=True, ecode=errors.ECODE_ENVIRON)
694

    
695
  if instance.name in ins_l.payload:
696
    raise errors.OpPrereqError("Instance %s is running, %s" %
697
                               (instance.name, reason), errors.ECODE_STATE)
698

    
699

    
700
def _ExpandItemName(fn, name, kind):
701
  """Expand an item name.
702

703
  @param fn: the function to use for expansion
704
  @param name: requested item name
705
  @param kind: text description ('Node' or 'Instance')
706
  @return: the resolved (full) name
707
  @raise errors.OpPrereqError: if the item is not found
708

709
  """
710
  full_name = fn(name)
711
  if full_name is None:
712
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
713
                               errors.ECODE_NOENT)
714
  return full_name
715

    
716

    
717
def _ExpandNodeName(cfg, name):
718
  """Wrapper over L{_ExpandItemName} for nodes."""
719
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
720

    
721

    
722
def _ExpandInstanceName(cfg, name):
723
  """Wrapper over L{_ExpandItemName} for instance."""
724
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
725

    
726

    
727
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
728
                          memory, vcpus, nics, disk_template, disks,
729
                          bep, hvp, hypervisor_name):
730
  """Builds instance related env variables for hooks
731

732
  This builds the hook environment from individual variables.
733

734
  @type name: string
735
  @param name: the name of the instance
736
  @type primary_node: string
737
  @param primary_node: the name of the instance's primary node
738
  @type secondary_nodes: list
739
  @param secondary_nodes: list of secondary nodes as strings
740
  @type os_type: string
741
  @param os_type: the name of the instance's OS
742
  @type status: boolean
743
  @param status: the should_run status of the instance
744
  @type memory: string
745
  @param memory: the memory size of the instance
746
  @type vcpus: string
747
  @param vcpus: the count of VCPUs the instance has
748
  @type nics: list
749
  @param nics: list of tuples (ip, mac, mode, link) representing
750
      the NICs the instance has
751
  @type disk_template: string
752
  @param disk_template: the disk template of the instance
753
  @type disks: list
754
  @param disks: the list of (size, mode) pairs
755
  @type bep: dict
756
  @param bep: the backend parameters for the instance
757
  @type hvp: dict
758
  @param hvp: the hypervisor parameters for the instance
759
  @type hypervisor_name: string
760
  @param hypervisor_name: the hypervisor for the instance
761
  @rtype: dict
762
  @return: the hook environment for this instance
763

764
  """
765
  if status:
766
    str_status = "up"
767
  else:
768
    str_status = "down"
769
  env = {
770
    "OP_TARGET": name,
771
    "INSTANCE_NAME": name,
772
    "INSTANCE_PRIMARY": primary_node,
773
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
774
    "INSTANCE_OS_TYPE": os_type,
775
    "INSTANCE_STATUS": str_status,
776
    "INSTANCE_MEMORY": memory,
777
    "INSTANCE_VCPUS": vcpus,
778
    "INSTANCE_DISK_TEMPLATE": disk_template,
779
    "INSTANCE_HYPERVISOR": hypervisor_name,
780
  }
781

    
782
  if nics:
783
    nic_count = len(nics)
784
    for idx, (ip, mac, mode, link) in enumerate(nics):
785
      if ip is None:
786
        ip = ""
787
      env["INSTANCE_NIC%d_IP" % idx] = ip
788
      env["INSTANCE_NIC%d_MAC" % idx] = mac
789
      env["INSTANCE_NIC%d_MODE" % idx] = mode
790
      env["INSTANCE_NIC%d_LINK" % idx] = link
791
      if mode == constants.NIC_MODE_BRIDGED:
792
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
793
  else:
794
    nic_count = 0
795

    
796
  env["INSTANCE_NIC_COUNT"] = nic_count
797

    
798
  if disks:
799
    disk_count = len(disks)
800
    for idx, (size, mode) in enumerate(disks):
801
      env["INSTANCE_DISK%d_SIZE" % idx] = size
802
      env["INSTANCE_DISK%d_MODE" % idx] = mode
803
  else:
804
    disk_count = 0
805

    
806
  env["INSTANCE_DISK_COUNT"] = disk_count
807

    
808
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
809
    for key, value in source.items():
810
      env["INSTANCE_%s_%s" % (kind, key)] = value
811

    
812
  return env
813

    
814

    
815
def _NICListToTuple(lu, nics):
816
  """Build a list of nic information tuples.
817

818
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
819
  value in LUQueryInstanceData.
820

821
  @type lu:  L{LogicalUnit}
822
  @param lu: the logical unit on whose behalf we execute
823
  @type nics: list of L{objects.NIC}
824
  @param nics: list of nics to convert to hooks tuples
825

826
  """
827
  hooks_nics = []
828
  cluster = lu.cfg.GetClusterInfo()
829
  for nic in nics:
830
    ip = nic.ip
831
    mac = nic.mac
832
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
833
    mode = filled_params[constants.NIC_MODE]
834
    link = filled_params[constants.NIC_LINK]
835
    hooks_nics.append((ip, mac, mode, link))
836
  return hooks_nics
837

    
838

    
839
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
840
  """Builds instance related env variables for hooks from an object.
841

842
  @type lu: L{LogicalUnit}
843
  @param lu: the logical unit on whose behalf we execute
844
  @type instance: L{objects.Instance}
845
  @param instance: the instance for which we should build the
846
      environment
847
  @type override: dict
848
  @param override: dictionary with key/values that will override
849
      our values
850
  @rtype: dict
851
  @return: the hook environment dictionary
852

853
  """
854
  cluster = lu.cfg.GetClusterInfo()
855
  bep = cluster.FillBE(instance)
856
  hvp = cluster.FillHV(instance)
857
  args = {
858
    'name': instance.name,
859
    'primary_node': instance.primary_node,
860
    'secondary_nodes': instance.secondary_nodes,
861
    'os_type': instance.os,
862
    'status': instance.admin_up,
863
    'memory': bep[constants.BE_MEMORY],
864
    'vcpus': bep[constants.BE_VCPUS],
865
    'nics': _NICListToTuple(lu, instance.nics),
866
    'disk_template': instance.disk_template,
867
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
868
    'bep': bep,
869
    'hvp': hvp,
870
    'hypervisor_name': instance.hypervisor,
871
  }
872
  if override:
873
    args.update(override)
874
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
875

    
876

    
877
def _AdjustCandidatePool(lu, exceptions):
878
  """Adjust the candidate pool after node operations.
879

880
  """
881
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
882
  if mod_list:
883
    lu.LogInfo("Promoted nodes to master candidate role: %s",
884
               utils.CommaJoin(node.name for node in mod_list))
885
    for name in mod_list:
886
      lu.context.ReaddNode(name)
887
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
888
  if mc_now > mc_max:
889
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
890
               (mc_now, mc_max))
891

    
892

    
893
def _DecideSelfPromotion(lu, exceptions=None):
894
  """Decide whether I should promote myself as a master candidate.
895

896
  """
897
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
898
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
899
  # the new node will increase mc_max with one, so:
900
  mc_should = min(mc_should + 1, cp_size)
901
  return mc_now < mc_should
902

    
903

    
904
def _CheckNicsBridgesExist(lu, target_nics, target_node):
905
  """Check that the brigdes needed by a list of nics exist.
906

907
  """
908
  cluster = lu.cfg.GetClusterInfo()
909
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
910
  brlist = [params[constants.NIC_LINK] for params in paramslist
911
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
912
  if brlist:
913
    result = lu.rpc.call_bridges_exist(target_node, brlist)
914
    result.Raise("Error checking bridges on destination node '%s'" %
915
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
916

    
917

    
918
def _CheckInstanceBridgesExist(lu, instance, node=None):
919
  """Check that the brigdes needed by an instance exist.
920

921
  """
922
  if node is None:
923
    node = instance.primary_node
924
  _CheckNicsBridgesExist(lu, instance.nics, node)
925

    
926

    
927
def _CheckOSVariant(os_obj, name):
928
  """Check whether an OS name conforms to the os variants specification.
929

930
  @type os_obj: L{objects.OS}
931
  @param os_obj: OS object to check
932
  @type name: string
933
  @param name: OS name passed by the user, to check for validity
934

935
  """
936
  if not os_obj.supported_variants:
937
    return
938
  variant = objects.OS.GetVariant(name)
939
  if not variant:
940
    raise errors.OpPrereqError("OS name must include a variant",
941
                               errors.ECODE_INVAL)
942

    
943
  if variant not in os_obj.supported_variants:
944
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
945

    
946

    
947
def _GetNodeInstancesInner(cfg, fn):
948
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
949

    
950

    
951
def _GetNodeInstances(cfg, node_name):
952
  """Returns a list of all primary and secondary instances on a node.
953

954
  """
955

    
956
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
957

    
958

    
959
def _GetNodePrimaryInstances(cfg, node_name):
960
  """Returns primary instances on a node.
961

962
  """
963
  return _GetNodeInstancesInner(cfg,
964
                                lambda inst: node_name == inst.primary_node)
965

    
966

    
967
def _GetNodeSecondaryInstances(cfg, node_name):
968
  """Returns secondary instances on a node.
969

970
  """
971
  return _GetNodeInstancesInner(cfg,
972
                                lambda inst: node_name in inst.secondary_nodes)
973

    
974

    
975
def _GetStorageTypeArgs(cfg, storage_type):
976
  """Returns the arguments for a storage type.
977

978
  """
979
  # Special case for file storage
980
  if storage_type == constants.ST_FILE:
981
    # storage.FileStorage wants a list of storage directories
982
    return [[cfg.GetFileStorageDir()]]
983

    
984
  return []
985

    
986

    
987
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
988
  faulty = []
989

    
990
  for dev in instance.disks:
991
    cfg.SetDiskID(dev, node_name)
992

    
993
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
994
  result.Raise("Failed to get disk status from node %s" % node_name,
995
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
996

    
997
  for idx, bdev_status in enumerate(result.payload):
998
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
999
      faulty.append(idx)
1000

    
1001
  return faulty
1002

    
1003

    
1004
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1005
  """Check the sanity of iallocator and node arguments and use the
1006
  cluster-wide iallocator if appropriate.
1007

1008
  Check that at most one of (iallocator, node) is specified. If none is
1009
  specified, then the LU's opcode's iallocator slot is filled with the
1010
  cluster-wide default iallocator.
1011

1012
  @type iallocator_slot: string
1013
  @param iallocator_slot: the name of the opcode iallocator slot
1014
  @type node_slot: string
1015
  @param node_slot: the name of the opcode target node slot
1016

1017
  """
1018
  node = getattr(lu.op, node_slot, None)
1019
  iallocator = getattr(lu.op, iallocator_slot, None)
1020

    
1021
  if node is not None and iallocator is not None:
1022
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1023
                               errors.ECODE_INVAL)
1024
  elif node is None and iallocator is None:
1025
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1026
    if default_iallocator:
1027
      setattr(lu.op, iallocator_slot, default_iallocator)
1028
    else:
1029
      raise errors.OpPrereqError("No iallocator or node given and no"
1030
                                 " cluster-wide default iallocator found."
1031
                                 " Please specify either an iallocator or a"
1032
                                 " node, or set a cluster-wide default"
1033
                                 " iallocator.")
1034

    
1035

    
1036
class LUPostInitCluster(LogicalUnit):
1037
  """Logical unit for running hooks after cluster initialization.
1038

1039
  """
1040
  HPATH = "cluster-init"
1041
  HTYPE = constants.HTYPE_CLUSTER
1042

    
1043
  def BuildHooksEnv(self):
1044
    """Build hooks env.
1045

1046
    """
1047
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1048
    mn = self.cfg.GetMasterNode()
1049
    return env, [], [mn]
1050

    
1051
  def Exec(self, feedback_fn):
1052
    """Nothing to do.
1053

1054
    """
1055
    return True
1056

    
1057

    
1058
class LUDestroyCluster(LogicalUnit):
1059
  """Logical unit for destroying the cluster.
1060

1061
  """
1062
  HPATH = "cluster-destroy"
1063
  HTYPE = constants.HTYPE_CLUSTER
1064

    
1065
  def BuildHooksEnv(self):
1066
    """Build hooks env.
1067

1068
    """
1069
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1070
    return env, [], []
1071

    
1072
  def CheckPrereq(self):
1073
    """Check prerequisites.
1074

1075
    This checks whether the cluster is empty.
1076

1077
    Any errors are signaled by raising errors.OpPrereqError.
1078

1079
    """
1080
    master = self.cfg.GetMasterNode()
1081

    
1082
    nodelist = self.cfg.GetNodeList()
1083
    if len(nodelist) != 1 or nodelist[0] != master:
1084
      raise errors.OpPrereqError("There are still %d node(s) in"
1085
                                 " this cluster." % (len(nodelist) - 1),
1086
                                 errors.ECODE_INVAL)
1087
    instancelist = self.cfg.GetInstanceList()
1088
    if instancelist:
1089
      raise errors.OpPrereqError("There are still %d instance(s) in"
1090
                                 " this cluster." % len(instancelist),
1091
                                 errors.ECODE_INVAL)
1092

    
1093
  def Exec(self, feedback_fn):
1094
    """Destroys the cluster.
1095

1096
    """
1097
    master = self.cfg.GetMasterNode()
1098

    
1099
    # Run post hooks on master node before it's removed
1100
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1101
    try:
1102
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1103
    except:
1104
      # pylint: disable-msg=W0702
1105
      self.LogWarning("Errors occurred running hooks on %s" % master)
1106

    
1107
    result = self.rpc.call_node_stop_master(master, False)
1108
    result.Raise("Could not disable the master role")
1109

    
1110
    return master
1111

    
1112

    
1113
def _VerifyCertificate(filename):
1114
  """Verifies a certificate for LUVerifyCluster.
1115

1116
  @type filename: string
1117
  @param filename: Path to PEM file
1118

1119
  """
1120
  try:
1121
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1122
                                           utils.ReadFile(filename))
1123
  except Exception, err: # pylint: disable-msg=W0703
1124
    return (LUVerifyCluster.ETYPE_ERROR,
1125
            "Failed to load X509 certificate %s: %s" % (filename, err))
1126

    
1127
  (errcode, msg) = \
1128
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1129
                                constants.SSL_CERT_EXPIRATION_ERROR)
1130

    
1131
  if msg:
1132
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1133
  else:
1134
    fnamemsg = None
1135

    
1136
  if errcode is None:
1137
    return (None, fnamemsg)
1138
  elif errcode == utils.CERT_WARNING:
1139
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1140
  elif errcode == utils.CERT_ERROR:
1141
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1142

    
1143
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1144

    
1145

    
1146
class LUVerifyCluster(LogicalUnit):
1147
  """Verifies the cluster status.
1148

1149
  """
1150
  HPATH = "cluster-verify"
1151
  HTYPE = constants.HTYPE_CLUSTER
1152
  _OP_PARAMS = [
1153
    ("skip_checks", ht.EmptyList,
1154
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1155
    ("verbose", False, ht.TBool),
1156
    ("error_codes", False, ht.TBool),
1157
    ("debug_simulate_errors", False, ht.TBool),
1158
    ]
1159
  REQ_BGL = False
1160

    
1161
  TCLUSTER = "cluster"
1162
  TNODE = "node"
1163
  TINSTANCE = "instance"
1164

    
1165
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1166
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1167
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1168
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1169
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1170
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1171
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1172
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1173
  ENODEDRBD = (TNODE, "ENODEDRBD")
1174
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1175
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1176
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1177
  ENODEHV = (TNODE, "ENODEHV")
1178
  ENODELVM = (TNODE, "ENODELVM")
1179
  ENODEN1 = (TNODE, "ENODEN1")
1180
  ENODENET = (TNODE, "ENODENET")
1181
  ENODEOS = (TNODE, "ENODEOS")
1182
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1183
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1184
  ENODERPC = (TNODE, "ENODERPC")
1185
  ENODESSH = (TNODE, "ENODESSH")
1186
  ENODEVERSION = (TNODE, "ENODEVERSION")
1187
  ENODESETUP = (TNODE, "ENODESETUP")
1188
  ENODETIME = (TNODE, "ENODETIME")
1189

    
1190
  ETYPE_FIELD = "code"
1191
  ETYPE_ERROR = "ERROR"
1192
  ETYPE_WARNING = "WARNING"
1193

    
1194
  class NodeImage(object):
1195
    """A class representing the logical and physical status of a node.
1196

1197
    @type name: string
1198
    @ivar name: the node name to which this object refers
1199
    @ivar volumes: a structure as returned from
1200
        L{ganeti.backend.GetVolumeList} (runtime)
1201
    @ivar instances: a list of running instances (runtime)
1202
    @ivar pinst: list of configured primary instances (config)
1203
    @ivar sinst: list of configured secondary instances (config)
1204
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1205
        of this node (config)
1206
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1207
    @ivar dfree: free disk, as reported by the node (runtime)
1208
    @ivar offline: the offline status (config)
1209
    @type rpc_fail: boolean
1210
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1211
        not whether the individual keys were correct) (runtime)
1212
    @type lvm_fail: boolean
1213
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1214
    @type hyp_fail: boolean
1215
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1216
    @type ghost: boolean
1217
    @ivar ghost: whether this is a known node or not (config)
1218
    @type os_fail: boolean
1219
    @ivar os_fail: whether the RPC call didn't return valid OS data
1220
    @type oslist: list
1221
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1222

1223
    """
1224
    def __init__(self, offline=False, name=None):
1225
      self.name = name
1226
      self.volumes = {}
1227
      self.instances = []
1228
      self.pinst = []
1229
      self.sinst = []
1230
      self.sbp = {}
1231
      self.mfree = 0
1232
      self.dfree = 0
1233
      self.offline = offline
1234
      self.rpc_fail = False
1235
      self.lvm_fail = False
1236
      self.hyp_fail = False
1237
      self.ghost = False
1238
      self.os_fail = False
1239
      self.oslist = {}
1240

    
1241
  def ExpandNames(self):
1242
    self.needed_locks = {
1243
      locking.LEVEL_NODE: locking.ALL_SET,
1244
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1245
    }
1246
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1247

    
1248
  def _Error(self, ecode, item, msg, *args, **kwargs):
1249
    """Format an error message.
1250

1251
    Based on the opcode's error_codes parameter, either format a
1252
    parseable error code, or a simpler error string.
1253

1254
    This must be called only from Exec and functions called from Exec.
1255

1256
    """
1257
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1258
    itype, etxt = ecode
1259
    # first complete the msg
1260
    if args:
1261
      msg = msg % args
1262
    # then format the whole message
1263
    if self.op.error_codes:
1264
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1265
    else:
1266
      if item:
1267
        item = " " + item
1268
      else:
1269
        item = ""
1270
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1271
    # and finally report it via the feedback_fn
1272
    self._feedback_fn("  - %s" % msg)
1273

    
1274
  def _ErrorIf(self, cond, *args, **kwargs):
1275
    """Log an error message if the passed condition is True.
1276

1277
    """
1278
    cond = bool(cond) or self.op.debug_simulate_errors
1279
    if cond:
1280
      self._Error(*args, **kwargs)
1281
    # do not mark the operation as failed for WARN cases only
1282
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1283
      self.bad = self.bad or cond
1284

    
1285
  def _VerifyNode(self, ninfo, nresult):
1286
    """Perform some basic validation on data returned from a node.
1287

1288
      - check the result data structure is well formed and has all the
1289
        mandatory fields
1290
      - check ganeti version
1291

1292
    @type ninfo: L{objects.Node}
1293
    @param ninfo: the node to check
1294
    @param nresult: the results from the node
1295
    @rtype: boolean
1296
    @return: whether overall this call was successful (and we can expect
1297
         reasonable values in the respose)
1298

1299
    """
1300
    node = ninfo.name
1301
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1302

    
1303
    # main result, nresult should be a non-empty dict
1304
    test = not nresult or not isinstance(nresult, dict)
1305
    _ErrorIf(test, self.ENODERPC, node,
1306
                  "unable to verify node: no data returned")
1307
    if test:
1308
      return False
1309

    
1310
    # compares ganeti version
1311
    local_version = constants.PROTOCOL_VERSION
1312
    remote_version = nresult.get("version", None)
1313
    test = not (remote_version and
1314
                isinstance(remote_version, (list, tuple)) and
1315
                len(remote_version) == 2)
1316
    _ErrorIf(test, self.ENODERPC, node,
1317
             "connection to node returned invalid data")
1318
    if test:
1319
      return False
1320

    
1321
    test = local_version != remote_version[0]
1322
    _ErrorIf(test, self.ENODEVERSION, node,
1323
             "incompatible protocol versions: master %s,"
1324
             " node %s", local_version, remote_version[0])
1325
    if test:
1326
      return False
1327

    
1328
    # node seems compatible, we can actually try to look into its results
1329

    
1330
    # full package version
1331
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1332
                  self.ENODEVERSION, node,
1333
                  "software version mismatch: master %s, node %s",
1334
                  constants.RELEASE_VERSION, remote_version[1],
1335
                  code=self.ETYPE_WARNING)
1336

    
1337
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1338
    if isinstance(hyp_result, dict):
1339
      for hv_name, hv_result in hyp_result.iteritems():
1340
        test = hv_result is not None
1341
        _ErrorIf(test, self.ENODEHV, node,
1342
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1343

    
1344

    
1345
    test = nresult.get(constants.NV_NODESETUP,
1346
                           ["Missing NODESETUP results"])
1347
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1348
             "; ".join(test))
1349

    
1350
    return True
1351

    
1352
  def _VerifyNodeTime(self, ninfo, nresult,
1353
                      nvinfo_starttime, nvinfo_endtime):
1354
    """Check the node time.
1355

1356
    @type ninfo: L{objects.Node}
1357
    @param ninfo: the node to check
1358
    @param nresult: the remote results for the node
1359
    @param nvinfo_starttime: the start time of the RPC call
1360
    @param nvinfo_endtime: the end time of the RPC call
1361

1362
    """
1363
    node = ninfo.name
1364
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1365

    
1366
    ntime = nresult.get(constants.NV_TIME, None)
1367
    try:
1368
      ntime_merged = utils.MergeTime(ntime)
1369
    except (ValueError, TypeError):
1370
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1371
      return
1372

    
1373
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1374
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1375
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1376
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1377
    else:
1378
      ntime_diff = None
1379

    
1380
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1381
             "Node time diverges by at least %s from master node time",
1382
             ntime_diff)
1383

    
1384
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1385
    """Check the node time.
1386

1387
    @type ninfo: L{objects.Node}
1388
    @param ninfo: the node to check
1389
    @param nresult: the remote results for the node
1390
    @param vg_name: the configured VG name
1391

1392
    """
1393
    if vg_name is None:
1394
      return
1395

    
1396
    node = ninfo.name
1397
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1398

    
1399
    # checks vg existence and size > 20G
1400
    vglist = nresult.get(constants.NV_VGLIST, None)
1401
    test = not vglist
1402
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1403
    if not test:
1404
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1405
                                            constants.MIN_VG_SIZE)
1406
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1407

    
1408
    # check pv names
1409
    pvlist = nresult.get(constants.NV_PVLIST, None)
1410
    test = pvlist is None
1411
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1412
    if not test:
1413
      # check that ':' is not present in PV names, since it's a
1414
      # special character for lvcreate (denotes the range of PEs to
1415
      # use on the PV)
1416
      for _, pvname, owner_vg in pvlist:
1417
        test = ":" in pvname
1418
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1419
                 " '%s' of VG '%s'", pvname, owner_vg)
1420

    
1421
  def _VerifyNodeNetwork(self, ninfo, nresult):
1422
    """Check the node time.
1423

1424
    @type ninfo: L{objects.Node}
1425
    @param ninfo: the node to check
1426
    @param nresult: the remote results for the node
1427

1428
    """
1429
    node = ninfo.name
1430
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1431

    
1432
    test = constants.NV_NODELIST not in nresult
1433
    _ErrorIf(test, self.ENODESSH, node,
1434
             "node hasn't returned node ssh connectivity data")
1435
    if not test:
1436
      if nresult[constants.NV_NODELIST]:
1437
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1438
          _ErrorIf(True, self.ENODESSH, node,
1439
                   "ssh communication with node '%s': %s", a_node, a_msg)
1440

    
1441
    test = constants.NV_NODENETTEST not in nresult
1442
    _ErrorIf(test, self.ENODENET, node,
1443
             "node hasn't returned node tcp connectivity data")
1444
    if not test:
1445
      if nresult[constants.NV_NODENETTEST]:
1446
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1447
        for anode in nlist:
1448
          _ErrorIf(True, self.ENODENET, node,
1449
                   "tcp communication with node '%s': %s",
1450
                   anode, nresult[constants.NV_NODENETTEST][anode])
1451

    
1452
    test = constants.NV_MASTERIP not in nresult
1453
    _ErrorIf(test, self.ENODENET, node,
1454
             "node hasn't returned node master IP reachability data")
1455
    if not test:
1456
      if not nresult[constants.NV_MASTERIP]:
1457
        if node == self.master_node:
1458
          msg = "the master node cannot reach the master IP (not configured?)"
1459
        else:
1460
          msg = "cannot reach the master IP"
1461
        _ErrorIf(True, self.ENODENET, node, msg)
1462

    
1463

    
1464
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1465
    """Verify an instance.
1466

1467
    This function checks to see if the required block devices are
1468
    available on the instance's node.
1469

1470
    """
1471
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1472
    node_current = instanceconfig.primary_node
1473

    
1474
    node_vol_should = {}
1475
    instanceconfig.MapLVsByNode(node_vol_should)
1476

    
1477
    for node in node_vol_should:
1478
      n_img = node_image[node]
1479
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1480
        # ignore missing volumes on offline or broken nodes
1481
        continue
1482
      for volume in node_vol_should[node]:
1483
        test = volume not in n_img.volumes
1484
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1485
                 "volume %s missing on node %s", volume, node)
1486

    
1487
    if instanceconfig.admin_up:
1488
      pri_img = node_image[node_current]
1489
      test = instance not in pri_img.instances and not pri_img.offline
1490
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1491
               "instance not running on its primary node %s",
1492
               node_current)
1493

    
1494
    for node, n_img in node_image.items():
1495
      if (not node == node_current):
1496
        test = instance in n_img.instances
1497
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1498
                 "instance should not run on node %s", node)
1499

    
1500
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1501
    """Verify if there are any unknown volumes in the cluster.
1502

1503
    The .os, .swap and backup volumes are ignored. All other volumes are
1504
    reported as unknown.
1505

1506
    @type reserved: L{ganeti.utils.FieldSet}
1507
    @param reserved: a FieldSet of reserved volume names
1508

1509
    """
1510
    for node, n_img in node_image.items():
1511
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1512
        # skip non-healthy nodes
1513
        continue
1514
      for volume in n_img.volumes:
1515
        test = ((node not in node_vol_should or
1516
                volume not in node_vol_should[node]) and
1517
                not reserved.Matches(volume))
1518
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1519
                      "volume %s is unknown", volume)
1520

    
1521
  def _VerifyOrphanInstances(self, instancelist, node_image):
1522
    """Verify the list of running instances.
1523

1524
    This checks what instances are running but unknown to the cluster.
1525

1526
    """
1527
    for node, n_img in node_image.items():
1528
      for o_inst in n_img.instances:
1529
        test = o_inst not in instancelist
1530
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1531
                      "instance %s on node %s should not exist", o_inst, node)
1532

    
1533
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1534
    """Verify N+1 Memory Resilience.
1535

1536
    Check that if one single node dies we can still start all the
1537
    instances it was primary for.
1538

1539
    """
1540
    for node, n_img in node_image.items():
1541
      # This code checks that every node which is now listed as
1542
      # secondary has enough memory to host all instances it is
1543
      # supposed to should a single other node in the cluster fail.
1544
      # FIXME: not ready for failover to an arbitrary node
1545
      # FIXME: does not support file-backed instances
1546
      # WARNING: we currently take into account down instances as well
1547
      # as up ones, considering that even if they're down someone
1548
      # might want to start them even in the event of a node failure.
1549
      for prinode, instances in n_img.sbp.items():
1550
        needed_mem = 0
1551
        for instance in instances:
1552
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1553
          if bep[constants.BE_AUTO_BALANCE]:
1554
            needed_mem += bep[constants.BE_MEMORY]
1555
        test = n_img.mfree < needed_mem
1556
        self._ErrorIf(test, self.ENODEN1, node,
1557
                      "not enough memory on to accommodate"
1558
                      " failovers should peer node %s fail", prinode)
1559

    
1560
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1561
                       master_files):
1562
    """Verifies and computes the node required file checksums.
1563

1564
    @type ninfo: L{objects.Node}
1565
    @param ninfo: the node to check
1566
    @param nresult: the remote results for the node
1567
    @param file_list: required list of files
1568
    @param local_cksum: dictionary of local files and their checksums
1569
    @param master_files: list of files that only masters should have
1570

1571
    """
1572
    node = ninfo.name
1573
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1574

    
1575
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1576
    test = not isinstance(remote_cksum, dict)
1577
    _ErrorIf(test, self.ENODEFILECHECK, node,
1578
             "node hasn't returned file checksum data")
1579
    if test:
1580
      return
1581

    
1582
    for file_name in file_list:
1583
      node_is_mc = ninfo.master_candidate
1584
      must_have = (file_name not in master_files) or node_is_mc
1585
      # missing
1586
      test1 = file_name not in remote_cksum
1587
      # invalid checksum
1588
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1589
      # existing and good
1590
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1591
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1592
               "file '%s' missing", file_name)
1593
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1594
               "file '%s' has wrong checksum", file_name)
1595
      # not candidate and this is not a must-have file
1596
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1597
               "file '%s' should not exist on non master"
1598
               " candidates (and the file is outdated)", file_name)
1599
      # all good, except non-master/non-must have combination
1600
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1601
               "file '%s' should not exist"
1602
               " on non master candidates", file_name)
1603

    
1604
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1605
                      drbd_map):
1606
    """Verifies and the node DRBD status.
1607

1608
    @type ninfo: L{objects.Node}
1609
    @param ninfo: the node to check
1610
    @param nresult: the remote results for the node
1611
    @param instanceinfo: the dict of instances
1612
    @param drbd_helper: the configured DRBD usermode helper
1613
    @param drbd_map: the DRBD map as returned by
1614
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1615

1616
    """
1617
    node = ninfo.name
1618
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1619

    
1620
    if drbd_helper:
1621
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1622
      test = (helper_result == None)
1623
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1624
               "no drbd usermode helper returned")
1625
      if helper_result:
1626
        status, payload = helper_result
1627
        test = not status
1628
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1629
                 "drbd usermode helper check unsuccessful: %s", payload)
1630
        test = status and (payload != drbd_helper)
1631
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1632
                 "wrong drbd usermode helper: %s", payload)
1633

    
1634
    # compute the DRBD minors
1635
    node_drbd = {}
1636
    for minor, instance in drbd_map[node].items():
1637
      test = instance not in instanceinfo
1638
      _ErrorIf(test, self.ECLUSTERCFG, None,
1639
               "ghost instance '%s' in temporary DRBD map", instance)
1640
        # ghost instance should not be running, but otherwise we
1641
        # don't give double warnings (both ghost instance and
1642
        # unallocated minor in use)
1643
      if test:
1644
        node_drbd[minor] = (instance, False)
1645
      else:
1646
        instance = instanceinfo[instance]
1647
        node_drbd[minor] = (instance.name, instance.admin_up)
1648

    
1649
    # and now check them
1650
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1651
    test = not isinstance(used_minors, (tuple, list))
1652
    _ErrorIf(test, self.ENODEDRBD, node,
1653
             "cannot parse drbd status file: %s", str(used_minors))
1654
    if test:
1655
      # we cannot check drbd status
1656
      return
1657

    
1658
    for minor, (iname, must_exist) in node_drbd.items():
1659
      test = minor not in used_minors and must_exist
1660
      _ErrorIf(test, self.ENODEDRBD, node,
1661
               "drbd minor %d of instance %s is not active", minor, iname)
1662
    for minor in used_minors:
1663
      test = minor not in node_drbd
1664
      _ErrorIf(test, self.ENODEDRBD, node,
1665
               "unallocated drbd minor %d is in use", minor)
1666

    
1667
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1668
    """Builds the node OS structures.
1669

1670
    @type ninfo: L{objects.Node}
1671
    @param ninfo: the node to check
1672
    @param nresult: the remote results for the node
1673
    @param nimg: the node image object
1674

1675
    """
1676
    node = ninfo.name
1677
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1678

    
1679
    remote_os = nresult.get(constants.NV_OSLIST, None)
1680
    test = (not isinstance(remote_os, list) or
1681
            not compat.all(isinstance(v, list) and len(v) == 7
1682
                           for v in remote_os))
1683

    
1684
    _ErrorIf(test, self.ENODEOS, node,
1685
             "node hasn't returned valid OS data")
1686

    
1687
    nimg.os_fail = test
1688

    
1689
    if test:
1690
      return
1691

    
1692
    os_dict = {}
1693

    
1694
    for (name, os_path, status, diagnose,
1695
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1696

    
1697
      if name not in os_dict:
1698
        os_dict[name] = []
1699

    
1700
      # parameters is a list of lists instead of list of tuples due to
1701
      # JSON lacking a real tuple type, fix it:
1702
      parameters = [tuple(v) for v in parameters]
1703
      os_dict[name].append((os_path, status, diagnose,
1704
                            set(variants), set(parameters), set(api_ver)))
1705

    
1706
    nimg.oslist = os_dict
1707

    
1708
  def _VerifyNodeOS(self, ninfo, nimg, base):
1709
    """Verifies the node OS list.
1710

1711
    @type ninfo: L{objects.Node}
1712
    @param ninfo: the node to check
1713
    @param nimg: the node image object
1714
    @param base: the 'template' node we match against (e.g. from the master)
1715

1716
    """
1717
    node = ninfo.name
1718
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1719

    
1720
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1721

    
1722
    for os_name, os_data in nimg.oslist.items():
1723
      assert os_data, "Empty OS status for OS %s?!" % os_name
1724
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1725
      _ErrorIf(not f_status, self.ENODEOS, node,
1726
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1727
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1728
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1729
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1730
      # this will catched in backend too
1731
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1732
               and not f_var, self.ENODEOS, node,
1733
               "OS %s with API at least %d does not declare any variant",
1734
               os_name, constants.OS_API_V15)
1735
      # comparisons with the 'base' image
1736
      test = os_name not in base.oslist
1737
      _ErrorIf(test, self.ENODEOS, node,
1738
               "Extra OS %s not present on reference node (%s)",
1739
               os_name, base.name)
1740
      if test:
1741
        continue
1742
      assert base.oslist[os_name], "Base node has empty OS status?"
1743
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1744
      if not b_status:
1745
        # base OS is invalid, skipping
1746
        continue
1747
      for kind, a, b in [("API version", f_api, b_api),
1748
                         ("variants list", f_var, b_var),
1749
                         ("parameters", f_param, b_param)]:
1750
        _ErrorIf(a != b, self.ENODEOS, node,
1751
                 "OS %s %s differs from reference node %s: %s vs. %s",
1752
                 kind, os_name, base.name,
1753
                 utils.CommaJoin(a), utils.CommaJoin(b))
1754

    
1755
    # check any missing OSes
1756
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1757
    _ErrorIf(missing, self.ENODEOS, node,
1758
             "OSes present on reference node %s but missing on this node: %s",
1759
             base.name, utils.CommaJoin(missing))
1760

    
1761
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1762
    """Verifies and updates the node volume data.
1763

1764
    This function will update a L{NodeImage}'s internal structures
1765
    with data from the remote call.
1766

1767
    @type ninfo: L{objects.Node}
1768
    @param ninfo: the node to check
1769
    @param nresult: the remote results for the node
1770
    @param nimg: the node image object
1771
    @param vg_name: the configured VG name
1772

1773
    """
1774
    node = ninfo.name
1775
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1776

    
1777
    nimg.lvm_fail = True
1778
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1779
    if vg_name is None:
1780
      pass
1781
    elif isinstance(lvdata, basestring):
1782
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1783
               utils.SafeEncode(lvdata))
1784
    elif not isinstance(lvdata, dict):
1785
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1786
    else:
1787
      nimg.volumes = lvdata
1788
      nimg.lvm_fail = False
1789

    
1790
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1791
    """Verifies and updates the node instance list.
1792

1793
    If the listing was successful, then updates this node's instance
1794
    list. Otherwise, it marks the RPC call as failed for the instance
1795
    list key.
1796

1797
    @type ninfo: L{objects.Node}
1798
    @param ninfo: the node to check
1799
    @param nresult: the remote results for the node
1800
    @param nimg: the node image object
1801

1802
    """
1803
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1804
    test = not isinstance(idata, list)
1805
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1806
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1807
    if test:
1808
      nimg.hyp_fail = True
1809
    else:
1810
      nimg.instances = idata
1811

    
1812
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1813
    """Verifies and computes a node information map
1814

1815
    @type ninfo: L{objects.Node}
1816
    @param ninfo: the node to check
1817
    @param nresult: the remote results for the node
1818
    @param nimg: the node image object
1819
    @param vg_name: the configured VG name
1820

1821
    """
1822
    node = ninfo.name
1823
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1824

    
1825
    # try to read free memory (from the hypervisor)
1826
    hv_info = nresult.get(constants.NV_HVINFO, None)
1827
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1828
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1829
    if not test:
1830
      try:
1831
        nimg.mfree = int(hv_info["memory_free"])
1832
      except (ValueError, TypeError):
1833
        _ErrorIf(True, self.ENODERPC, node,
1834
                 "node returned invalid nodeinfo, check hypervisor")
1835

    
1836
    # FIXME: devise a free space model for file based instances as well
1837
    if vg_name is not None:
1838
      test = (constants.NV_VGLIST not in nresult or
1839
              vg_name not in nresult[constants.NV_VGLIST])
1840
      _ErrorIf(test, self.ENODELVM, node,
1841
               "node didn't return data for the volume group '%s'"
1842
               " - it is either missing or broken", vg_name)
1843
      if not test:
1844
        try:
1845
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1846
        except (ValueError, TypeError):
1847
          _ErrorIf(True, self.ENODERPC, node,
1848
                   "node returned invalid LVM info, check LVM status")
1849

    
1850
  def BuildHooksEnv(self):
1851
    """Build hooks env.
1852

1853
    Cluster-Verify hooks just ran in the post phase and their failure makes
1854
    the output be logged in the verify output and the verification to fail.
1855

1856
    """
1857
    all_nodes = self.cfg.GetNodeList()
1858
    env = {
1859
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1860
      }
1861
    for node in self.cfg.GetAllNodesInfo().values():
1862
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1863

    
1864
    return env, [], all_nodes
1865

    
1866
  def Exec(self, feedback_fn):
1867
    """Verify integrity of cluster, performing various test on nodes.
1868

1869
    """
1870
    self.bad = False
1871
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1872
    verbose = self.op.verbose
1873
    self._feedback_fn = feedback_fn
1874
    feedback_fn("* Verifying global settings")
1875
    for msg in self.cfg.VerifyConfig():
1876
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1877

    
1878
    # Check the cluster certificates
1879
    for cert_filename in constants.ALL_CERT_FILES:
1880
      (errcode, msg) = _VerifyCertificate(cert_filename)
1881
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1882

    
1883
    vg_name = self.cfg.GetVGName()
1884
    drbd_helper = self.cfg.GetDRBDHelper()
1885
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1886
    cluster = self.cfg.GetClusterInfo()
1887
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1888
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1889
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1890
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1891
                        for iname in instancelist)
1892
    i_non_redundant = [] # Non redundant instances
1893
    i_non_a_balanced = [] # Non auto-balanced instances
1894
    n_offline = 0 # Count of offline nodes
1895
    n_drained = 0 # Count of nodes being drained
1896
    node_vol_should = {}
1897

    
1898
    # FIXME: verify OS list
1899
    # do local checksums
1900
    master_files = [constants.CLUSTER_CONF_FILE]
1901
    master_node = self.master_node = self.cfg.GetMasterNode()
1902
    master_ip = self.cfg.GetMasterIP()
1903

    
1904
    file_names = ssconf.SimpleStore().GetFileList()
1905
    file_names.extend(constants.ALL_CERT_FILES)
1906
    file_names.extend(master_files)
1907
    if cluster.modify_etc_hosts:
1908
      file_names.append(constants.ETC_HOSTS)
1909

    
1910
    local_checksums = utils.FingerprintFiles(file_names)
1911

    
1912
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1913
    node_verify_param = {
1914
      constants.NV_FILELIST: file_names,
1915
      constants.NV_NODELIST: [node.name for node in nodeinfo
1916
                              if not node.offline],
1917
      constants.NV_HYPERVISOR: hypervisors,
1918
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1919
                                  node.secondary_ip) for node in nodeinfo
1920
                                 if not node.offline],
1921
      constants.NV_INSTANCELIST: hypervisors,
1922
      constants.NV_VERSION: None,
1923
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1924
      constants.NV_NODESETUP: None,
1925
      constants.NV_TIME: None,
1926
      constants.NV_MASTERIP: (master_node, master_ip),
1927
      constants.NV_OSLIST: None,
1928
      }
1929

    
1930
    if vg_name is not None:
1931
      node_verify_param[constants.NV_VGLIST] = None
1932
      node_verify_param[constants.NV_LVLIST] = vg_name
1933
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1934
      node_verify_param[constants.NV_DRBDLIST] = None
1935

    
1936
    if drbd_helper:
1937
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
1938

    
1939
    # Build our expected cluster state
1940
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
1941
                                                 name=node.name))
1942
                      for node in nodeinfo)
1943

    
1944
    for instance in instancelist:
1945
      inst_config = instanceinfo[instance]
1946

    
1947
      for nname in inst_config.all_nodes:
1948
        if nname not in node_image:
1949
          # ghost node
1950
          gnode = self.NodeImage(name=nname)
1951
          gnode.ghost = True
1952
          node_image[nname] = gnode
1953

    
1954
      inst_config.MapLVsByNode(node_vol_should)
1955

    
1956
      pnode = inst_config.primary_node
1957
      node_image[pnode].pinst.append(instance)
1958

    
1959
      for snode in inst_config.secondary_nodes:
1960
        nimg = node_image[snode]
1961
        nimg.sinst.append(instance)
1962
        if pnode not in nimg.sbp:
1963
          nimg.sbp[pnode] = []
1964
        nimg.sbp[pnode].append(instance)
1965

    
1966
    # At this point, we have the in-memory data structures complete,
1967
    # except for the runtime information, which we'll gather next
1968

    
1969
    # Due to the way our RPC system works, exact response times cannot be
1970
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1971
    # time before and after executing the request, we can at least have a time
1972
    # window.
1973
    nvinfo_starttime = time.time()
1974
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1975
                                           self.cfg.GetClusterName())
1976
    nvinfo_endtime = time.time()
1977

    
1978
    all_drbd_map = self.cfg.ComputeDRBDMap()
1979

    
1980
    feedback_fn("* Verifying node status")
1981

    
1982
    refos_img = None
1983

    
1984
    for node_i in nodeinfo:
1985
      node = node_i.name
1986
      nimg = node_image[node]
1987

    
1988
      if node_i.offline:
1989
        if verbose:
1990
          feedback_fn("* Skipping offline node %s" % (node,))
1991
        n_offline += 1
1992
        continue
1993

    
1994
      if node == master_node:
1995
        ntype = "master"
1996
      elif node_i.master_candidate:
1997
        ntype = "master candidate"
1998
      elif node_i.drained:
1999
        ntype = "drained"
2000
        n_drained += 1
2001
      else:
2002
        ntype = "regular"
2003
      if verbose:
2004
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2005

    
2006
      msg = all_nvinfo[node].fail_msg
2007
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2008
      if msg:
2009
        nimg.rpc_fail = True
2010
        continue
2011

    
2012
      nresult = all_nvinfo[node].payload
2013

    
2014
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2015
      self._VerifyNodeNetwork(node_i, nresult)
2016
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2017
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2018
                            master_files)
2019
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2020
                           all_drbd_map)
2021
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2022

    
2023
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2024
      self._UpdateNodeInstances(node_i, nresult, nimg)
2025
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2026
      self._UpdateNodeOS(node_i, nresult, nimg)
2027
      if not nimg.os_fail:
2028
        if refos_img is None:
2029
          refos_img = nimg
2030
        self._VerifyNodeOS(node_i, nimg, refos_img)
2031

    
2032
    feedback_fn("* Verifying instance status")
2033
    for instance in instancelist:
2034
      if verbose:
2035
        feedback_fn("* Verifying instance %s" % instance)
2036
      inst_config = instanceinfo[instance]
2037
      self._VerifyInstance(instance, inst_config, node_image)
2038
      inst_nodes_offline = []
2039

    
2040
      pnode = inst_config.primary_node
2041
      pnode_img = node_image[pnode]
2042
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2043
               self.ENODERPC, pnode, "instance %s, connection to"
2044
               " primary node failed", instance)
2045

    
2046
      if pnode_img.offline:
2047
        inst_nodes_offline.append(pnode)
2048

    
2049
      # If the instance is non-redundant we cannot survive losing its primary
2050
      # node, so we are not N+1 compliant. On the other hand we have no disk
2051
      # templates with more than one secondary so that situation is not well
2052
      # supported either.
2053
      # FIXME: does not support file-backed instances
2054
      if not inst_config.secondary_nodes:
2055
        i_non_redundant.append(instance)
2056
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2057
               instance, "instance has multiple secondary nodes: %s",
2058
               utils.CommaJoin(inst_config.secondary_nodes),
2059
               code=self.ETYPE_WARNING)
2060

    
2061
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2062
        i_non_a_balanced.append(instance)
2063

    
2064
      for snode in inst_config.secondary_nodes:
2065
        s_img = node_image[snode]
2066
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2067
                 "instance %s, connection to secondary node failed", instance)
2068

    
2069
        if s_img.offline:
2070
          inst_nodes_offline.append(snode)
2071

    
2072
      # warn that the instance lives on offline nodes
2073
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2074
               "instance lives on offline node(s) %s",
2075
               utils.CommaJoin(inst_nodes_offline))
2076
      # ... or ghost nodes
2077
      for node in inst_config.all_nodes:
2078
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2079
                 "instance lives on ghost node %s", node)
2080

    
2081
    feedback_fn("* Verifying orphan volumes")
2082
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2083
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2084

    
2085
    feedback_fn("* Verifying orphan instances")
2086
    self._VerifyOrphanInstances(instancelist, node_image)
2087

    
2088
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2089
      feedback_fn("* Verifying N+1 Memory redundancy")
2090
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2091

    
2092
    feedback_fn("* Other Notes")
2093
    if i_non_redundant:
2094
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2095
                  % len(i_non_redundant))
2096

    
2097
    if i_non_a_balanced:
2098
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2099
                  % len(i_non_a_balanced))
2100

    
2101
    if n_offline:
2102
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2103

    
2104
    if n_drained:
2105
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2106

    
2107
    return not self.bad
2108

    
2109
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2110
    """Analyze the post-hooks' result
2111

2112
    This method analyses the hook result, handles it, and sends some
2113
    nicely-formatted feedback back to the user.
2114

2115
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2116
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2117
    @param hooks_results: the results of the multi-node hooks rpc call
2118
    @param feedback_fn: function used send feedback back to the caller
2119
    @param lu_result: previous Exec result
2120
    @return: the new Exec result, based on the previous result
2121
        and hook results
2122

2123
    """
2124
    # We only really run POST phase hooks, and are only interested in
2125
    # their results
2126
    if phase == constants.HOOKS_PHASE_POST:
2127
      # Used to change hooks' output to proper indentation
2128
      indent_re = re.compile('^', re.M)
2129
      feedback_fn("* Hooks Results")
2130
      assert hooks_results, "invalid result from hooks"
2131

    
2132
      for node_name in hooks_results:
2133
        res = hooks_results[node_name]
2134
        msg = res.fail_msg
2135
        test = msg and not res.offline
2136
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2137
                      "Communication failure in hooks execution: %s", msg)
2138
        if res.offline or msg:
2139
          # No need to investigate payload if node is offline or gave an error.
2140
          # override manually lu_result here as _ErrorIf only
2141
          # overrides self.bad
2142
          lu_result = 1
2143
          continue
2144
        for script, hkr, output in res.payload:
2145
          test = hkr == constants.HKR_FAIL
2146
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2147
                        "Script %s failed, output:", script)
2148
          if test:
2149
            output = indent_re.sub('      ', output)
2150
            feedback_fn("%s" % output)
2151
            lu_result = 0
2152

    
2153
      return lu_result
2154

    
2155

    
2156
class LUVerifyDisks(NoHooksLU):
2157
  """Verifies the cluster disks status.
2158

2159
  """
2160
  REQ_BGL = False
2161

    
2162
  def ExpandNames(self):
2163
    self.needed_locks = {
2164
      locking.LEVEL_NODE: locking.ALL_SET,
2165
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2166
    }
2167
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2168

    
2169
  def Exec(self, feedback_fn):
2170
    """Verify integrity of cluster disks.
2171

2172
    @rtype: tuple of three items
2173
    @return: a tuple of (dict of node-to-node_error, list of instances
2174
        which need activate-disks, dict of instance: (node, volume) for
2175
        missing volumes
2176

2177
    """
2178
    result = res_nodes, res_instances, res_missing = {}, [], {}
2179

    
2180
    vg_name = self.cfg.GetVGName()
2181
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2182
    instances = [self.cfg.GetInstanceInfo(name)
2183
                 for name in self.cfg.GetInstanceList()]
2184

    
2185
    nv_dict = {}
2186
    for inst in instances:
2187
      inst_lvs = {}
2188
      if (not inst.admin_up or
2189
          inst.disk_template not in constants.DTS_NET_MIRROR):
2190
        continue
2191
      inst.MapLVsByNode(inst_lvs)
2192
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2193
      for node, vol_list in inst_lvs.iteritems():
2194
        for vol in vol_list:
2195
          nv_dict[(node, vol)] = inst
2196

    
2197
    if not nv_dict:
2198
      return result
2199

    
2200
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2201

    
2202
    for node in nodes:
2203
      # node_volume
2204
      node_res = node_lvs[node]
2205
      if node_res.offline:
2206
        continue
2207
      msg = node_res.fail_msg
2208
      if msg:
2209
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2210
        res_nodes[node] = msg
2211
        continue
2212

    
2213
      lvs = node_res.payload
2214
      for lv_name, (_, _, lv_online) in lvs.items():
2215
        inst = nv_dict.pop((node, lv_name), None)
2216
        if (not lv_online and inst is not None
2217
            and inst.name not in res_instances):
2218
          res_instances.append(inst.name)
2219

    
2220
    # any leftover items in nv_dict are missing LVs, let's arrange the
2221
    # data better
2222
    for key, inst in nv_dict.iteritems():
2223
      if inst.name not in res_missing:
2224
        res_missing[inst.name] = []
2225
      res_missing[inst.name].append(key)
2226

    
2227
    return result
2228

    
2229

    
2230
class LURepairDiskSizes(NoHooksLU):
2231
  """Verifies the cluster disks sizes.
2232

2233
  """
2234
  _OP_PARAMS = [("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString))]
2235
  REQ_BGL = False
2236

    
2237
  def ExpandNames(self):
2238
    if self.op.instances:
2239
      self.wanted_names = []
2240
      for name in self.op.instances:
2241
        full_name = _ExpandInstanceName(self.cfg, name)
2242
        self.wanted_names.append(full_name)
2243
      self.needed_locks = {
2244
        locking.LEVEL_NODE: [],
2245
        locking.LEVEL_INSTANCE: self.wanted_names,
2246
        }
2247
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2248
    else:
2249
      self.wanted_names = None
2250
      self.needed_locks = {
2251
        locking.LEVEL_NODE: locking.ALL_SET,
2252
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2253
        }
2254
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2255

    
2256
  def DeclareLocks(self, level):
2257
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2258
      self._LockInstancesNodes(primary_only=True)
2259

    
2260
  def CheckPrereq(self):
2261
    """Check prerequisites.
2262

2263
    This only checks the optional instance list against the existing names.
2264

2265
    """
2266
    if self.wanted_names is None:
2267
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2268

    
2269
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2270
                             in self.wanted_names]
2271

    
2272
  def _EnsureChildSizes(self, disk):
2273
    """Ensure children of the disk have the needed disk size.
2274

2275
    This is valid mainly for DRBD8 and fixes an issue where the
2276
    children have smaller disk size.
2277

2278
    @param disk: an L{ganeti.objects.Disk} object
2279

2280
    """
2281
    if disk.dev_type == constants.LD_DRBD8:
2282
      assert disk.children, "Empty children for DRBD8?"
2283
      fchild = disk.children[0]
2284
      mismatch = fchild.size < disk.size
2285
      if mismatch:
2286
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2287
                     fchild.size, disk.size)
2288
        fchild.size = disk.size
2289

    
2290
      # and we recurse on this child only, not on the metadev
2291
      return self._EnsureChildSizes(fchild) or mismatch
2292
    else:
2293
      return False
2294

    
2295
  def Exec(self, feedback_fn):
2296
    """Verify the size of cluster disks.
2297

2298
    """
2299
    # TODO: check child disks too
2300
    # TODO: check differences in size between primary/secondary nodes
2301
    per_node_disks = {}
2302
    for instance in self.wanted_instances:
2303
      pnode = instance.primary_node
2304
      if pnode not in per_node_disks:
2305
        per_node_disks[pnode] = []
2306
      for idx, disk in enumerate(instance.disks):
2307
        per_node_disks[pnode].append((instance, idx, disk))
2308

    
2309
    changed = []
2310
    for node, dskl in per_node_disks.items():
2311
      newl = [v[2].Copy() for v in dskl]
2312
      for dsk in newl:
2313
        self.cfg.SetDiskID(dsk, node)
2314
      result = self.rpc.call_blockdev_getsizes(node, newl)
2315
      if result.fail_msg:
2316
        self.LogWarning("Failure in blockdev_getsizes call to node"
2317
                        " %s, ignoring", node)
2318
        continue
2319
      if len(result.data) != len(dskl):
2320
        self.LogWarning("Invalid result from node %s, ignoring node results",
2321
                        node)
2322
        continue
2323
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2324
        if size is None:
2325
          self.LogWarning("Disk %d of instance %s did not return size"
2326
                          " information, ignoring", idx, instance.name)
2327
          continue
2328
        if not isinstance(size, (int, long)):
2329
          self.LogWarning("Disk %d of instance %s did not return valid"
2330
                          " size information, ignoring", idx, instance.name)
2331
          continue
2332
        size = size >> 20
2333
        if size != disk.size:
2334
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2335
                       " correcting: recorded %d, actual %d", idx,
2336
                       instance.name, disk.size, size)
2337
          disk.size = size
2338
          self.cfg.Update(instance, feedback_fn)
2339
          changed.append((instance.name, idx, size))
2340
        if self._EnsureChildSizes(disk):
2341
          self.cfg.Update(instance, feedback_fn)
2342
          changed.append((instance.name, idx, disk.size))
2343
    return changed
2344

    
2345

    
2346
class LURenameCluster(LogicalUnit):
2347
  """Rename the cluster.
2348

2349
  """
2350
  HPATH = "cluster-rename"
2351
  HTYPE = constants.HTYPE_CLUSTER
2352
  _OP_PARAMS = [("name", ht.NoDefault, ht.TNonEmptyString)]
2353

    
2354
  def BuildHooksEnv(self):
2355
    """Build hooks env.
2356

2357
    """
2358
    env = {
2359
      "OP_TARGET": self.cfg.GetClusterName(),
2360
      "NEW_NAME": self.op.name,
2361
      }
2362
    mn = self.cfg.GetMasterNode()
2363
    all_nodes = self.cfg.GetNodeList()
2364
    return env, [mn], all_nodes
2365

    
2366
  def CheckPrereq(self):
2367
    """Verify that the passed name is a valid one.
2368

2369
    """
2370
    hostname = netutils.GetHostname(name=self.op.name,
2371
                                    family=self.cfg.GetPrimaryIPFamily())
2372

    
2373
    new_name = hostname.name
2374
    self.ip = new_ip = hostname.ip
2375
    old_name = self.cfg.GetClusterName()
2376
    old_ip = self.cfg.GetMasterIP()
2377
    if new_name == old_name and new_ip == old_ip:
2378
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2379
                                 " cluster has changed",
2380
                                 errors.ECODE_INVAL)
2381
    if new_ip != old_ip:
2382
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2383
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2384
                                   " reachable on the network" %
2385
                                   new_ip, errors.ECODE_NOTUNIQUE)
2386

    
2387
    self.op.name = new_name
2388

    
2389
  def Exec(self, feedback_fn):
2390
    """Rename the cluster.
2391

2392
    """
2393
    clustername = self.op.name
2394
    ip = self.ip
2395

    
2396
    # shutdown the master IP
2397
    master = self.cfg.GetMasterNode()
2398
    result = self.rpc.call_node_stop_master(master, False)
2399
    result.Raise("Could not disable the master role")
2400

    
2401
    try:
2402
      cluster = self.cfg.GetClusterInfo()
2403
      cluster.cluster_name = clustername
2404
      cluster.master_ip = ip
2405
      self.cfg.Update(cluster, feedback_fn)
2406

    
2407
      # update the known hosts file
2408
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2409
      node_list = self.cfg.GetNodeList()
2410
      try:
2411
        node_list.remove(master)
2412
      except ValueError:
2413
        pass
2414
      result = self.rpc.call_upload_file(node_list,
2415
                                         constants.SSH_KNOWN_HOSTS_FILE)
2416
      for to_node, to_result in result.iteritems():
2417
        msg = to_result.fail_msg
2418
        if msg:
2419
          msg = ("Copy of file %s to node %s failed: %s" %
2420
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2421
          self.proc.LogWarning(msg)
2422

    
2423
    finally:
2424
      result = self.rpc.call_node_start_master(master, False, False)
2425
      msg = result.fail_msg
2426
      if msg:
2427
        self.LogWarning("Could not re-enable the master role on"
2428
                        " the master, please restart manually: %s", msg)
2429

    
2430
    return clustername
2431

    
2432

    
2433
class LUSetClusterParams(LogicalUnit):
2434
  """Change the parameters of the cluster.
2435

2436
  """
2437
  HPATH = "cluster-modify"
2438
  HTYPE = constants.HTYPE_CLUSTER
2439
  _OP_PARAMS = [
2440
    ("vg_name", None, ht.TMaybeString),
2441
    ("enabled_hypervisors", None,
2442
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
2443
            ht.TNone)),
2444
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2445
                              ht.TNone)),
2446
    ("beparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2447
                              ht.TNone)),
2448
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2449
                            ht.TNone)),
2450
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2451
                              ht.TNone)),
2452
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
2453
    ("uid_pool", None, ht.NoType),
2454
    ("add_uids", None, ht.NoType),
2455
    ("remove_uids", None, ht.NoType),
2456
    ("maintain_node_health", None, ht.TMaybeBool),
2457
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
2458
    ("nicparams", None, ht.TOr(ht.TDict, ht.TNone)),
2459
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
2460
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
2461
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
2462
    ("hidden_os", None, ht.TOr(ht.TListOf(\
2463
          ht.TAnd(ht.TList,
2464
                ht.TIsLength(2),
2465
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2466
          ht.TNone)),
2467
    ("blacklisted_os", None, ht.TOr(ht.TListOf(\
2468
          ht.TAnd(ht.TList,
2469
                ht.TIsLength(2),
2470
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2471
          ht.TNone)),
2472
    ]
2473
  REQ_BGL = False
2474

    
2475
  def CheckArguments(self):
2476
    """Check parameters
2477

2478
    """
2479
    if self.op.uid_pool:
2480
      uidpool.CheckUidPool(self.op.uid_pool)
2481

    
2482
    if self.op.add_uids:
2483
      uidpool.CheckUidPool(self.op.add_uids)
2484

    
2485
    if self.op.remove_uids:
2486
      uidpool.CheckUidPool(self.op.remove_uids)
2487

    
2488
  def ExpandNames(self):
2489
    # FIXME: in the future maybe other cluster params won't require checking on
2490
    # all nodes to be modified.
2491
    self.needed_locks = {
2492
      locking.LEVEL_NODE: locking.ALL_SET,
2493
    }
2494
    self.share_locks[locking.LEVEL_NODE] = 1
2495

    
2496
  def BuildHooksEnv(self):
2497
    """Build hooks env.
2498

2499
    """
2500
    env = {
2501
      "OP_TARGET": self.cfg.GetClusterName(),
2502
      "NEW_VG_NAME": self.op.vg_name,
2503
      }
2504
    mn = self.cfg.GetMasterNode()
2505
    return env, [mn], [mn]
2506

    
2507
  def CheckPrereq(self):
2508
    """Check prerequisites.
2509

2510
    This checks whether the given params don't conflict and
2511
    if the given volume group is valid.
2512

2513
    """
2514
    if self.op.vg_name is not None and not self.op.vg_name:
2515
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2516
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2517
                                   " instances exist", errors.ECODE_INVAL)
2518

    
2519
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2520
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2521
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2522
                                   " drbd-based instances exist",
2523
                                   errors.ECODE_INVAL)
2524

    
2525
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2526

    
2527
    # if vg_name not None, checks given volume group on all nodes
2528
    if self.op.vg_name:
2529
      vglist = self.rpc.call_vg_list(node_list)
2530
      for node in node_list:
2531
        msg = vglist[node].fail_msg
2532
        if msg:
2533
          # ignoring down node
2534
          self.LogWarning("Error while gathering data on node %s"
2535
                          " (ignoring node): %s", node, msg)
2536
          continue
2537
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2538
                                              self.op.vg_name,
2539
                                              constants.MIN_VG_SIZE)
2540
        if vgstatus:
2541
          raise errors.OpPrereqError("Error on node '%s': %s" %
2542
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2543

    
2544
    if self.op.drbd_helper:
2545
      # checks given drbd helper on all nodes
2546
      helpers = self.rpc.call_drbd_helper(node_list)
2547
      for node in node_list:
2548
        ninfo = self.cfg.GetNodeInfo(node)
2549
        if ninfo.offline:
2550
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2551
          continue
2552
        msg = helpers[node].fail_msg
2553
        if msg:
2554
          raise errors.OpPrereqError("Error checking drbd helper on node"
2555
                                     " '%s': %s" % (node, msg),
2556
                                     errors.ECODE_ENVIRON)
2557
        node_helper = helpers[node].payload
2558
        if node_helper != self.op.drbd_helper:
2559
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2560
                                     (node, node_helper), errors.ECODE_ENVIRON)
2561

    
2562
    self.cluster = cluster = self.cfg.GetClusterInfo()
2563
    # validate params changes
2564
    if self.op.beparams:
2565
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2566
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2567

    
2568
    if self.op.nicparams:
2569
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2570
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2571
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2572
      nic_errors = []
2573

    
2574
      # check all instances for consistency
2575
      for instance in self.cfg.GetAllInstancesInfo().values():
2576
        for nic_idx, nic in enumerate(instance.nics):
2577
          params_copy = copy.deepcopy(nic.nicparams)
2578
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2579

    
2580
          # check parameter syntax
2581
          try:
2582
            objects.NIC.CheckParameterSyntax(params_filled)
2583
          except errors.ConfigurationError, err:
2584
            nic_errors.append("Instance %s, nic/%d: %s" %
2585
                              (instance.name, nic_idx, err))
2586

    
2587
          # if we're moving instances to routed, check that they have an ip
2588
          target_mode = params_filled[constants.NIC_MODE]
2589
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2590
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2591
                              (instance.name, nic_idx))
2592
      if nic_errors:
2593
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2594
                                   "\n".join(nic_errors))
2595

    
2596
    # hypervisor list/parameters
2597
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2598
    if self.op.hvparams:
2599
      for hv_name, hv_dict in self.op.hvparams.items():
2600
        if hv_name not in self.new_hvparams:
2601
          self.new_hvparams[hv_name] = hv_dict
2602
        else:
2603
          self.new_hvparams[hv_name].update(hv_dict)
2604

    
2605
    # os hypervisor parameters
2606
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2607
    if self.op.os_hvp:
2608
      for os_name, hvs in self.op.os_hvp.items():
2609
        if os_name not in self.new_os_hvp:
2610
          self.new_os_hvp[os_name] = hvs
2611
        else:
2612
          for hv_name, hv_dict in hvs.items():
2613
            if hv_name not in self.new_os_hvp[os_name]:
2614
              self.new_os_hvp[os_name][hv_name] = hv_dict
2615
            else:
2616
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2617

    
2618
    # os parameters
2619
    self.new_osp = objects.FillDict(cluster.osparams, {})
2620
    if self.op.osparams:
2621
      for os_name, osp in self.op.osparams.items():
2622
        if os_name not in self.new_osp:
2623
          self.new_osp[os_name] = {}
2624

    
2625
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2626
                                                  use_none=True)
2627

    
2628
        if not self.new_osp[os_name]:
2629
          # we removed all parameters
2630
          del self.new_osp[os_name]
2631
        else:
2632
          # check the parameter validity (remote check)
2633
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2634
                         os_name, self.new_osp[os_name])
2635

    
2636
    # changes to the hypervisor list
2637
    if self.op.enabled_hypervisors is not None:
2638
      self.hv_list = self.op.enabled_hypervisors
2639
      for hv in self.hv_list:
2640
        # if the hypervisor doesn't already exist in the cluster
2641
        # hvparams, we initialize it to empty, and then (in both
2642
        # cases) we make sure to fill the defaults, as we might not
2643
        # have a complete defaults list if the hypervisor wasn't
2644
        # enabled before
2645
        if hv not in new_hvp:
2646
          new_hvp[hv] = {}
2647
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2648
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2649
    else:
2650
      self.hv_list = cluster.enabled_hypervisors
2651

    
2652
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2653
      # either the enabled list has changed, or the parameters have, validate
2654
      for hv_name, hv_params in self.new_hvparams.items():
2655
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2656
            (self.op.enabled_hypervisors and
2657
             hv_name in self.op.enabled_hypervisors)):
2658
          # either this is a new hypervisor, or its parameters have changed
2659
          hv_class = hypervisor.GetHypervisor(hv_name)
2660
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2661
          hv_class.CheckParameterSyntax(hv_params)
2662
          _CheckHVParams(self, node_list, hv_name, hv_params)
2663

    
2664
    if self.op.os_hvp:
2665
      # no need to check any newly-enabled hypervisors, since the
2666
      # defaults have already been checked in the above code-block
2667
      for os_name, os_hvp in self.new_os_hvp.items():
2668
        for hv_name, hv_params in os_hvp.items():
2669
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2670
          # we need to fill in the new os_hvp on top of the actual hv_p
2671
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2672
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2673
          hv_class = hypervisor.GetHypervisor(hv_name)
2674
          hv_class.CheckParameterSyntax(new_osp)
2675
          _CheckHVParams(self, node_list, hv_name, new_osp)
2676

    
2677
    if self.op.default_iallocator:
2678
      alloc_script = utils.FindFile(self.op.default_iallocator,
2679
                                    constants.IALLOCATOR_SEARCH_PATH,
2680
                                    os.path.isfile)
2681
      if alloc_script is None:
2682
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2683
                                   " specified" % self.op.default_iallocator,
2684
                                   errors.ECODE_INVAL)
2685

    
2686
  def Exec(self, feedback_fn):
2687
    """Change the parameters of the cluster.
2688

2689
    """
2690
    if self.op.vg_name is not None:
2691
      new_volume = self.op.vg_name
2692
      if not new_volume:
2693
        new_volume = None
2694
      if new_volume != self.cfg.GetVGName():
2695
        self.cfg.SetVGName(new_volume)
2696
      else:
2697
        feedback_fn("Cluster LVM configuration already in desired"
2698
                    " state, not changing")
2699
    if self.op.drbd_helper is not None:
2700
      new_helper = self.op.drbd_helper
2701
      if not new_helper:
2702
        new_helper = None
2703
      if new_helper != self.cfg.GetDRBDHelper():
2704
        self.cfg.SetDRBDHelper(new_helper)
2705
      else:
2706
        feedback_fn("Cluster DRBD helper already in desired state,"
2707
                    " not changing")
2708
    if self.op.hvparams:
2709
      self.cluster.hvparams = self.new_hvparams
2710
    if self.op.os_hvp:
2711
      self.cluster.os_hvp = self.new_os_hvp
2712
    if self.op.enabled_hypervisors is not None:
2713
      self.cluster.hvparams = self.new_hvparams
2714
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2715
    if self.op.beparams:
2716
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2717
    if self.op.nicparams:
2718
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2719
    if self.op.osparams:
2720
      self.cluster.osparams = self.new_osp
2721

    
2722
    if self.op.candidate_pool_size is not None:
2723
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2724
      # we need to update the pool size here, otherwise the save will fail
2725
      _AdjustCandidatePool(self, [])
2726

    
2727
    if self.op.maintain_node_health is not None:
2728
      self.cluster.maintain_node_health = self.op.maintain_node_health
2729

    
2730
    if self.op.prealloc_wipe_disks is not None:
2731
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2732

    
2733
    if self.op.add_uids is not None:
2734
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2735

    
2736
    if self.op.remove_uids is not None:
2737
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2738

    
2739
    if self.op.uid_pool is not None:
2740
      self.cluster.uid_pool = self.op.uid_pool
2741

    
2742
    if self.op.default_iallocator is not None:
2743
      self.cluster.default_iallocator = self.op.default_iallocator
2744

    
2745
    if self.op.reserved_lvs is not None:
2746
      self.cluster.reserved_lvs = self.op.reserved_lvs
2747

    
2748
    def helper_os(aname, mods, desc):
2749
      desc += " OS list"
2750
      lst = getattr(self.cluster, aname)
2751
      for key, val in mods:
2752
        if key == constants.DDM_ADD:
2753
          if val in lst:
2754
            feedback_fn("OS %s already in %s, ignoring", val, desc)
2755
          else:
2756
            lst.append(val)
2757
        elif key == constants.DDM_REMOVE:
2758
          if val in lst:
2759
            lst.remove(val)
2760
          else:
2761
            feedback_fn("OS %s not found in %s, ignoring", val, desc)
2762
        else:
2763
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2764

    
2765
    if self.op.hidden_os:
2766
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2767

    
2768
    if self.op.blacklisted_os:
2769
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2770

    
2771
    self.cfg.Update(self.cluster, feedback_fn)
2772

    
2773

    
2774
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2775
  """Distribute additional files which are part of the cluster configuration.
2776

2777
  ConfigWriter takes care of distributing the config and ssconf files, but
2778
  there are more files which should be distributed to all nodes. This function
2779
  makes sure those are copied.
2780

2781
  @param lu: calling logical unit
2782
  @param additional_nodes: list of nodes not in the config to distribute to
2783

2784
  """
2785
  # 1. Gather target nodes
2786
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2787
  dist_nodes = lu.cfg.GetOnlineNodeList()
2788
  if additional_nodes is not None:
2789
    dist_nodes.extend(additional_nodes)
2790
  if myself.name in dist_nodes:
2791
    dist_nodes.remove(myself.name)
2792

    
2793
  # 2. Gather files to distribute
2794
  dist_files = set([constants.ETC_HOSTS,
2795
                    constants.SSH_KNOWN_HOSTS_FILE,
2796
                    constants.RAPI_CERT_FILE,
2797
                    constants.RAPI_USERS_FILE,
2798
                    constants.CONFD_HMAC_KEY,
2799
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2800
                   ])
2801

    
2802
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2803
  for hv_name in enabled_hypervisors:
2804
    hv_class = hypervisor.GetHypervisor(hv_name)
2805
    dist_files.update(hv_class.GetAncillaryFiles())
2806

    
2807
  # 3. Perform the files upload
2808
  for fname in dist_files:
2809
    if os.path.exists(fname):
2810
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2811
      for to_node, to_result in result.items():
2812
        msg = to_result.fail_msg
2813
        if msg:
2814
          msg = ("Copy of file %s to node %s failed: %s" %
2815
                 (fname, to_node, msg))
2816
          lu.proc.LogWarning(msg)
2817

    
2818

    
2819
class LURedistributeConfig(NoHooksLU):
2820
  """Force the redistribution of cluster configuration.
2821

2822
  This is a very simple LU.
2823

2824
  """
2825
  REQ_BGL = False
2826

    
2827
  def ExpandNames(self):
2828
    self.needed_locks = {
2829
      locking.LEVEL_NODE: locking.ALL_SET,
2830
    }
2831
    self.share_locks[locking.LEVEL_NODE] = 1
2832

    
2833
  def Exec(self, feedback_fn):
2834
    """Redistribute the configuration.
2835

2836
    """
2837
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2838
    _RedistributeAncillaryFiles(self)
2839

    
2840

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

2844
  """
2845
  if not instance.disks or disks is not None and not disks:
2846
    return True
2847

    
2848
  disks = _ExpandCheckDisks(instance, disks)
2849

    
2850
  if not oneshot:
2851
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2852

    
2853
  node = instance.primary_node
2854

    
2855
  for dev in disks:
2856
    lu.cfg.SetDiskID(dev, node)
2857

    
2858
  # TODO: Convert to utils.Retry
2859

    
2860
  retries = 0
2861
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2862
  while True:
2863
    max_time = 0
2864
    done = True
2865
    cumul_degraded = False
2866
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2867
    msg = rstats.fail_msg
2868
    if msg:
2869
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2870
      retries += 1
2871
      if retries >= 10:
2872
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2873
                                 " aborting." % node)
2874
      time.sleep(6)
2875
      continue
2876
    rstats = rstats.payload
2877
    retries = 0
2878
    for i, mstat in enumerate(rstats):
2879
      if mstat is None:
2880
        lu.LogWarning("Can't compute data for node %s/%s",
2881
                           node, disks[i].iv_name)
2882
        continue
2883

    
2884
      cumul_degraded = (cumul_degraded or
2885
                        (mstat.is_degraded and mstat.sync_percent is None))
2886
      if mstat.sync_percent is not None:
2887
        done = False
2888
        if mstat.estimated_time is not None:
2889
          rem_time = ("%s remaining (estimated)" %
2890
                      utils.FormatSeconds(mstat.estimated_time))
2891
          max_time = mstat.estimated_time
2892
        else:
2893
          rem_time = "no time estimate"
2894
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2895
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
2896

    
2897
    # if we're done but degraded, let's do a few small retries, to
2898
    # make sure we see a stable and not transient situation; therefore
2899
    # we force restart of the loop
2900
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2901
      logging.info("Degraded disks found, %d retries left", degr_retries)
2902
      degr_retries -= 1
2903
      time.sleep(1)
2904
      continue
2905

    
2906
    if done or oneshot:
2907
      break
2908

    
2909
    time.sleep(min(60, max_time))
2910

    
2911
  if done:
2912
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2913
  return not cumul_degraded
2914

    
2915

    
2916
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2917
  """Check that mirrors are not degraded.
2918

2919
  The ldisk parameter, if True, will change the test from the
2920
  is_degraded attribute (which represents overall non-ok status for
2921
  the device(s)) to the ldisk (representing the local storage status).
2922

2923
  """
2924
  lu.cfg.SetDiskID(dev, node)
2925

    
2926
  result = True
2927

    
2928
  if on_primary or dev.AssembleOnSecondary():
2929
    rstats = lu.rpc.call_blockdev_find(node, dev)
2930
    msg = rstats.fail_msg
2931
    if msg:
2932
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2933
      result = False
2934
    elif not rstats.payload:
2935
      lu.LogWarning("Can't find disk on node %s", node)
2936
      result = False
2937
    else:
2938
      if ldisk:
2939
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2940
      else:
2941
        result = result and not rstats.payload.is_degraded
2942

    
2943
  if dev.children:
2944
    for child in dev.children:
2945
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2946

    
2947
  return result
2948

    
2949

    
2950
class LUDiagnoseOS(NoHooksLU):
2951
  """Logical unit for OS diagnose/query.
2952

2953
  """
2954
  _OP_PARAMS = [
2955
    _POutputFields,
2956
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
2957
    ]
2958
  REQ_BGL = False
2959
  _HID = "hidden"
2960
  _BLK = "blacklisted"
2961
  _VLD = "valid"
2962
  _FIELDS_STATIC = utils.FieldSet()
2963
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
2964
                                   "parameters", "api_versions", _HID, _BLK)
2965

    
2966
  def CheckArguments(self):
2967
    if self.op.names:
2968
      raise errors.OpPrereqError("Selective OS query not supported",
2969
                                 errors.ECODE_INVAL)
2970

    
2971
    _CheckOutputFields(static=self._FIELDS_STATIC,
2972
                       dynamic=self._FIELDS_DYNAMIC,
2973
                       selected=self.op.output_fields)
2974

    
2975
  def ExpandNames(self):
2976
    # Lock all nodes, in shared mode
2977
    # Temporary removal of locks, should be reverted later
2978
    # TODO: reintroduce locks when they are lighter-weight
2979
    self.needed_locks = {}
2980
    #self.share_locks[locking.LEVEL_NODE] = 1
2981
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2982

    
2983
  @staticmethod
2984
  def _DiagnoseByOS(rlist):
2985
    """Remaps a per-node return list into an a per-os per-node dictionary
2986

2987
    @param rlist: a map with node names as keys and OS objects as values
2988

2989
    @rtype: dict
2990
    @return: a dictionary with osnames as keys and as value another
2991
        map, with nodes as keys and tuples of (path, status, diagnose,
2992
        variants, parameters, api_versions) as values, eg::
2993

2994
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
2995
                                     (/srv/..., False, "invalid api")],
2996
                           "node2": [(/srv/..., True, "", [], [])]}
2997
          }
2998

2999
    """
3000
    all_os = {}
3001
    # we build here the list of nodes that didn't fail the RPC (at RPC
3002
    # level), so that nodes with a non-responding node daemon don't
3003
    # make all OSes invalid
3004
    good_nodes = [node_name for node_name in rlist
3005
                  if not rlist[node_name].fail_msg]
3006
    for node_name, nr in rlist.items():
3007
      if nr.fail_msg or not nr.payload:
3008
        continue
3009
      for (name, path, status, diagnose, variants,
3010
           params, api_versions) in nr.payload:
3011
        if name not in all_os:
3012
          # build a list of nodes for this os containing empty lists
3013
          # for each node in node_list
3014
          all_os[name] = {}
3015
          for nname in good_nodes:
3016
            all_os[name][nname] = []
3017
        # convert params from [name, help] to (name, help)
3018
        params = [tuple(v) for v in params]
3019
        all_os[name][node_name].append((path, status, diagnose,
3020
                                        variants, params, api_versions))
3021
    return all_os
3022

    
3023
  def Exec(self, feedback_fn):
3024
    """Compute the list of OSes.
3025

3026
    """
3027
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3028
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3029
    pol = self._DiagnoseByOS(node_data)
3030
    output = []
3031
    cluster = self.cfg.GetClusterInfo()
3032

    
3033
    for os_name in utils.NiceSort(pol.keys()):
3034
      os_data = pol[os_name]
3035
      row = []
3036
      valid = True
3037
      (variants, params, api_versions) = null_state = (set(), set(), set())
3038
      for idx, osl in enumerate(os_data.values()):
3039
        valid = bool(valid and osl and osl[0][1])
3040
        if not valid:
3041
          (variants, params, api_versions) = null_state
3042
          break
3043
        node_variants, node_params, node_api = osl[0][3:6]
3044
        if idx == 0: # first entry
3045
          variants = set(node_variants)
3046
          params = set(node_params)
3047
          api_versions = set(node_api)
3048
        else: # keep consistency
3049
          variants.intersection_update(node_variants)
3050
          params.intersection_update(node_params)
3051
          api_versions.intersection_update(node_api)
3052

    
3053
      is_hid = os_name in cluster.hidden_os
3054
      is_blk = os_name in cluster.blacklisted_os
3055
      if ((self._HID not in self.op.output_fields and is_hid) or
3056
          (self._BLK not in self.op.output_fields and is_blk) or
3057
          (self._VLD not in self.op.output_fields and not valid)):
3058
        continue
3059

    
3060
      for field in self.op.output_fields:
3061
        if field == "name":
3062
          val = os_name
3063
        elif field == self._VLD:
3064
          val = valid
3065
        elif field == "node_status":
3066
          # this is just a copy of the dict
3067
          val = {}
3068
          for node_name, nos_list in os_data.items():
3069
            val[node_name] = nos_list
3070
        elif field == "variants":
3071
          val = utils.NiceSort(list(variants))
3072
        elif field == "parameters":
3073
          val = list(params)
3074
        elif field == "api_versions":
3075
          val = list(api_versions)
3076
        elif field == self._HID:
3077
          val = is_hid
3078
        elif field == self._BLK:
3079
          val = is_blk
3080
        else:
3081
          raise errors.ParameterError(field)
3082
        row.append(val)
3083
      output.append(row)
3084

    
3085
    return output
3086

    
3087

    
3088
class LURemoveNode(LogicalUnit):
3089
  """Logical unit for removing a node.
3090

3091
  """
3092
  HPATH = "node-remove"
3093
  HTYPE = constants.HTYPE_NODE
3094
  _OP_PARAMS = [
3095
    _PNodeName,
3096
    ]
3097

    
3098
  def BuildHooksEnv(self):
3099
    """Build hooks env.
3100

3101
    This doesn't run on the target node in the pre phase as a failed
3102
    node would then be impossible to remove.
3103

3104
    """
3105
    env = {
3106
      "OP_TARGET": self.op.node_name,
3107
      "NODE_NAME": self.op.node_name,
3108
      }
3109
    all_nodes = self.cfg.GetNodeList()
3110
    try:
3111
      all_nodes.remove(self.op.node_name)
3112
    except ValueError:
3113
      logging.warning("Node %s which is about to be removed not found"
3114
                      " in the all nodes list", self.op.node_name)
3115
    return env, all_nodes, all_nodes
3116

    
3117
  def CheckPrereq(self):
3118
    """Check prerequisites.
3119

3120
    This checks:
3121
     - the node exists in the configuration
3122
     - it does not have primary or secondary instances
3123
     - it's not the master
3124

3125
    Any errors are signaled by raising errors.OpPrereqError.
3126

3127
    """
3128
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3129
    node = self.cfg.GetNodeInfo(self.op.node_name)
3130
    assert node is not None
3131

    
3132
    instance_list = self.cfg.GetInstanceList()
3133

    
3134
    masternode = self.cfg.GetMasterNode()
3135
    if node.name == masternode:
3136
      raise errors.OpPrereqError("Node is the master node,"
3137
                                 " you need to failover first.",
3138
                                 errors.ECODE_INVAL)
3139

    
3140
    for instance_name in instance_list:
3141
      instance = self.cfg.GetInstanceInfo(instance_name)
3142
      if node.name in instance.all_nodes:
3143
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3144
                                   " please remove first." % instance_name,
3145
                                   errors.ECODE_INVAL)
3146
    self.op.node_name = node.name
3147
    self.node = node
3148

    
3149
  def Exec(self, feedback_fn):
3150
    """Removes the node from the cluster.
3151

3152
    """
3153
    node = self.node
3154
    logging.info("Stopping the node daemon and removing configs from node %s",
3155
                 node.name)
3156

    
3157
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3158

    
3159
    # Promote nodes to master candidate as needed
3160
    _AdjustCandidatePool(self, exceptions=[node.name])
3161
    self.context.RemoveNode(node.name)
3162

    
3163
    # Run post hooks on the node before it's removed
3164
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3165
    try:
3166
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3167
    except:
3168
      # pylint: disable-msg=W0702
3169
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3170

    
3171
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3172
    msg = result.fail_msg
3173
    if msg:
3174
      self.LogWarning("Errors encountered on the remote node while leaving"
3175
                      " the cluster: %s", msg)
3176

    
3177
    # Remove node from our /etc/hosts
3178
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3179
      master_node = self.cfg.GetMasterNode()
3180
      result = self.rpc.call_etc_hosts_modify(master_node,
3181
                                              constants.ETC_HOSTS_REMOVE,
3182
                                              node.name, None)
3183
      result.Raise("Can't update hosts file with new host data")
3184
      _RedistributeAncillaryFiles(self)
3185

    
3186

    
3187
class LUQueryNodes(NoHooksLU):
3188
  """Logical unit for querying nodes.
3189

3190
  """
3191
  # pylint: disable-msg=W0142
3192
  _OP_PARAMS = [
3193
    _POutputFields,
3194
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3195
    ("use_locking", False, ht.TBool),
3196
    ]
3197
  REQ_BGL = False
3198

    
3199
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3200
                    "master_candidate", "offline", "drained",
3201
                    "master_capable", "vm_capable"]
3202

    
3203
  _FIELDS_DYNAMIC = utils.FieldSet(
3204
    "dtotal", "dfree",
3205
    "mtotal", "mnode", "mfree",
3206
    "bootid",
3207
    "ctotal", "cnodes", "csockets",
3208
    )
3209

    
3210
  _FIELDS_STATIC = utils.FieldSet(*[
3211
    "pinst_cnt", "sinst_cnt",
3212
    "pinst_list", "sinst_list",
3213
    "pip", "sip", "tags",
3214
    "master",
3215
    "role"] + _SIMPLE_FIELDS
3216
    )
3217

    
3218
  def CheckArguments(self):
3219
    _CheckOutputFields(static=self._FIELDS_STATIC,
3220
                       dynamic=self._FIELDS_DYNAMIC,
3221
                       selected=self.op.output_fields)
3222

    
3223
  def ExpandNames(self):
3224
    self.needed_locks = {}
3225
    self.share_locks[locking.LEVEL_NODE] = 1
3226

    
3227
    if self.op.names:
3228
      self.wanted = _GetWantedNodes(self, self.op.names)
3229
    else:
3230
      self.wanted = locking.ALL_SET
3231

    
3232
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3233
    self.do_locking = self.do_node_query and self.op.use_locking
3234
    if self.do_locking:
3235
      # if we don't request only static fields, we need to lock the nodes
3236
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3237

    
3238
  def Exec(self, feedback_fn):
3239
    """Computes the list of nodes and their attributes.
3240

3241
    """
3242
    all_info = self.cfg.GetAllNodesInfo()
3243
    if self.do_locking:
3244
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3245
    elif self.wanted != locking.ALL_SET:
3246
      nodenames = self.wanted
3247
      missing = set(nodenames).difference(all_info.keys())
3248
      if missing:
3249
        raise errors.OpExecError(
3250
          "Some nodes were removed before retrieving their data: %s" % missing)
3251
    else:
3252
      nodenames = all_info.keys()
3253

    
3254
    nodenames = utils.NiceSort(nodenames)
3255
    nodelist = [all_info[name] for name in nodenames]
3256

    
3257
    # begin data gathering
3258

    
3259
    if self.do_node_query:
3260
      live_data = {}
3261
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3262
                                          self.cfg.GetHypervisorType())
3263
      for name in nodenames:
3264
        nodeinfo = node_data[name]
3265
        if not nodeinfo.fail_msg and nodeinfo.payload:
3266
          nodeinfo = nodeinfo.payload
3267
          fn = utils.TryConvert
3268
          live_data[name] = {
3269
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3270
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3271
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3272
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3273
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3274
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3275
            "bootid": nodeinfo.get('bootid', None),
3276
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3277
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3278
            }
3279
        else:
3280
          live_data[name] = {}
3281
    else:
3282
      live_data = dict.fromkeys(nodenames, {})
3283

    
3284
    node_to_primary = dict([(name, set()) for name in nodenames])
3285
    node_to_secondary = dict([(name, set()) for name in nodenames])
3286

    
3287
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3288
                             "sinst_cnt", "sinst_list"))
3289
    if inst_fields & frozenset(self.op.output_fields):
3290
      inst_data = self.cfg.GetAllInstancesInfo()
3291

    
3292
      for inst in inst_data.values():
3293
        if inst.primary_node in node_to_primary:
3294
          node_to_primary[inst.primary_node].add(inst.name)
3295
        for secnode in inst.secondary_nodes:
3296
          if secnode in node_to_secondary:
3297
            node_to_secondary[secnode].add(inst.name)
3298

    
3299
    master_node = self.cfg.GetMasterNode()
3300

    
3301
    # end data gathering
3302

    
3303
    output = []
3304
    for node in nodelist:
3305
      node_output = []
3306
      for field in self.op.output_fields:
3307
        if field in self._SIMPLE_FIELDS:
3308
          val = getattr(node, field)
3309
        elif field == "pinst_list":
3310
          val = list(node_to_primary[node.name])
3311
        elif field == "sinst_list":
3312
          val = list(node_to_secondary[node.name])
3313
        elif field == "pinst_cnt":
3314
          val = len(node_to_primary[node.name])
3315
        elif field == "sinst_cnt":
3316
          val = len(node_to_secondary[node.name])
3317
        elif field == "pip":
3318
          val = node.primary_ip
3319
        elif field == "sip":
3320
          val = node.secondary_ip
3321
        elif field == "tags":
3322
          val = list(node.GetTags())
3323
        elif field == "master":
3324
          val = node.name == master_node
3325
        elif self._FIELDS_DYNAMIC.Matches(field):
3326
          val = live_data[node.name].get(field, None)
3327
        elif field == "role":
3328
          if node.name == master_node:
3329
            val = "M"
3330
          elif node.master_candidate:
3331
            val = "C"
3332
          elif node.drained:
3333
            val = "D"
3334
          elif node.offline:
3335
            val = "O"
3336
          else:
3337
            val = "R"
3338
        else:
3339
          raise errors.ParameterError(field)
3340
        node_output.append(val)
3341
      output.append(node_output)
3342

    
3343
    return output
3344

    
3345

    
3346
class LUQueryNodeVolumes(NoHooksLU):
3347
  """Logical unit for getting volumes on node(s).
3348

3349
  """
3350
  _OP_PARAMS = [
3351
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3352
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3353
    ]
3354
  REQ_BGL = False
3355
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3356
  _FIELDS_STATIC = utils.FieldSet("node")
3357

    
3358
  def CheckArguments(self):
3359
    _CheckOutputFields(static=self._FIELDS_STATIC,
3360
                       dynamic=self._FIELDS_DYNAMIC,
3361
                       selected=self.op.output_fields)
3362

    
3363
  def ExpandNames(self):
3364
    self.needed_locks = {}
3365
    self.share_locks[locking.LEVEL_NODE] = 1
3366
    if not self.op.nodes:
3367
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3368
    else:
3369
      self.needed_locks[locking.LEVEL_NODE] = \
3370
        _GetWantedNodes(self, self.op.nodes)
3371

    
3372
  def Exec(self, feedback_fn):
3373
    """Computes the list of nodes and their attributes.
3374

3375
    """
3376
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3377
    volumes = self.rpc.call_node_volumes(nodenames)
3378

    
3379
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3380
             in self.cfg.GetInstanceList()]
3381

    
3382
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3383

    
3384
    output = []
3385
    for node in nodenames:
3386
      nresult = volumes[node]
3387
      if nresult.offline:
3388
        continue
3389
      msg = nresult.fail_msg
3390
      if msg:
3391
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3392
        continue
3393

    
3394
      node_vols = nresult.payload[:]
3395
      node_vols.sort(key=lambda vol: vol['dev'])
3396

    
3397
      for vol in node_vols:
3398
        node_output = []
3399
        for field in self.op.output_fields:
3400
          if field == "node":
3401
            val = node
3402
          elif field == "phys":
3403
            val = vol['dev']
3404
          elif field == "vg":
3405
            val = vol['vg']
3406
          elif field == "name":
3407
            val = vol['name']
3408
          elif field == "size":
3409
            val = int(float(vol['size']))
3410
          elif field == "instance":
3411
            for inst in ilist:
3412
              if node not in lv_by_node[inst]:
3413
                continue
3414
              if vol['name'] in lv_by_node[inst][node]:
3415
                val = inst.name
3416
                break
3417
            else:
3418
              val = '-'
3419
          else:
3420
            raise errors.ParameterError(field)
3421
          node_output.append(str(val))
3422

    
3423
        output.append(node_output)
3424

    
3425
    return output
3426

    
3427

    
3428
class LUQueryNodeStorage(NoHooksLU):
3429
  """Logical unit for getting information on storage units on node(s).
3430

3431
  """
3432
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3433
  _OP_PARAMS = [
3434
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3435
    ("storage_type", ht.NoDefault, _CheckStorageType),
3436
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3437
    ("name", None, ht.TMaybeString),
3438
    ]
3439
  REQ_BGL = False
3440

    
3441
  def CheckArguments(self):
3442
    _CheckOutputFields(static=self._FIELDS_STATIC,
3443
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3444
                       selected=self.op.output_fields)
3445

    
3446
  def ExpandNames(self):
3447
    self.needed_locks = {}
3448
    self.share_locks[locking.LEVEL_NODE] = 1
3449

    
3450
    if self.op.nodes:
3451
      self.needed_locks[locking.LEVEL_NODE] = \
3452
        _GetWantedNodes(self, self.op.nodes)
3453
    else:
3454
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3455

    
3456
  def Exec(self, feedback_fn):
3457
    """Computes the list of nodes and their attributes.
3458

3459
    """
3460
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3461

    
3462
    # Always get name to sort by
3463
    if constants.SF_NAME in self.op.output_fields:
3464
      fields = self.op.output_fields[:]
3465
    else:
3466
      fields = [constants.SF_NAME] + self.op.output_fields
3467

    
3468
    # Never ask for node or type as it's only known to the LU
3469
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3470
      while extra in fields:
3471
        fields.remove(extra)
3472

    
3473
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3474
    name_idx = field_idx[constants.SF_NAME]
3475

    
3476
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3477
    data = self.rpc.call_storage_list(self.nodes,
3478
                                      self.op.storage_type, st_args,
3479
                                      self.op.name, fields)
3480

    
3481
    result = []
3482

    
3483
    for node in utils.NiceSort(self.nodes):
3484
      nresult = data[node]
3485
      if nresult.offline:
3486
        continue
3487

    
3488
      msg = nresult.fail_msg
3489
      if msg:
3490
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3491
        continue
3492

    
3493
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3494

    
3495
      for name in utils.NiceSort(rows.keys()):
3496
        row = rows[name]
3497

    
3498
        out = []
3499

    
3500
        for field in self.op.output_fields:
3501
          if field == constants.SF_NODE:
3502
            val = node
3503
          elif field == constants.SF_TYPE:
3504
            val = self.op.storage_type
3505
          elif field in field_idx:
3506
            val = row[field_idx[field]]
3507
          else:
3508
            raise errors.ParameterError(field)
3509

    
3510
          out.append(val)
3511

    
3512
        result.append(out)
3513

    
3514
    return result
3515

    
3516

    
3517
class LUModifyNodeStorage(NoHooksLU):
3518
  """Logical unit for modifying a storage volume on a node.
3519

3520
  """
3521
  _OP_PARAMS = [
3522
    _PNodeName,
3523
    ("storage_type", ht.NoDefault, _CheckStorageType),
3524
    ("name", ht.NoDefault, ht.TNonEmptyString),
3525
    ("changes", ht.NoDefault, ht.TDict),
3526
    ]
3527
  REQ_BGL = False
3528

    
3529
  def CheckArguments(self):
3530
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3531

    
3532
    storage_type = self.op.storage_type
3533

    
3534
    try:
3535
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3536
    except KeyError:
3537
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3538
                                 " modified" % storage_type,
3539
                                 errors.ECODE_INVAL)
3540

    
3541
    diff = set(self.op.changes.keys()) - modifiable
3542
    if diff:
3543
      raise errors.OpPrereqError("The following fields can not be modified for"
3544
                                 " storage units of type '%s': %r" %
3545
                                 (storage_type, list(diff)),
3546
                                 errors.ECODE_INVAL)
3547

    
3548
  def ExpandNames(self):
3549
    self.needed_locks = {
3550
      locking.LEVEL_NODE: self.op.node_name,
3551
      }
3552

    
3553
  def Exec(self, feedback_fn):
3554
    """Computes the list of nodes and their attributes.
3555

3556
    """
3557
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3558
    result = self.rpc.call_storage_modify(self.op.node_name,
3559
                                          self.op.storage_type, st_args,
3560
                                          self.op.name, self.op.changes)
3561
    result.Raise("Failed to modify storage unit '%s' on %s" %
3562
                 (self.op.name, self.op.node_name))
3563

    
3564

    
3565
class LUAddNode(LogicalUnit):
3566
  """Logical unit for adding node to the cluster.
3567

3568
  """
3569
  HPATH = "node-add"
3570
  HTYPE = constants.HTYPE_NODE
3571
  _OP_PARAMS = [
3572
    _PNodeName,
3573
    ("primary_ip", None, ht.NoType),
3574
    ("secondary_ip", None, ht.TMaybeString),
3575
    ("readd", False, ht.TBool),
3576
    ("group", None, ht.TMaybeString)
3577
    ]
3578

    
3579
  def CheckArguments(self):
3580
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3581
    # validate/normalize the node name
3582
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3583
                                         family=self.primary_ip_family)
3584
    self.op.node_name = self.hostname.name
3585
    if self.op.readd and self.op.group:
3586
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3587
                                 " being readded", errors.ECODE_INVAL)
3588

    
3589
  def BuildHooksEnv(self):
3590
    """Build hooks env.
3591

3592
    This will run on all nodes before, and on all nodes + the new node after.
3593

3594
    """
3595
    env = {
3596
      "OP_TARGET": self.op.node_name,
3597
      "NODE_NAME": self.op.node_name,
3598
      "NODE_PIP": self.op.primary_ip,
3599
      "NODE_SIP": self.op.secondary_ip,
3600
      }
3601
    nodes_0 = self.cfg.GetNodeList()
3602
    nodes_1 = nodes_0 + [self.op.node_name, ]
3603
    return env, nodes_0, nodes_1
3604

    
3605
  def CheckPrereq(self):
3606
    """Check prerequisites.
3607

3608
    This checks:
3609
     - the new node is not already in the config
3610
     - it is resolvable
3611
     - its parameters (single/dual homed) matches the cluster
3612

3613
    Any errors are signaled by raising errors.OpPrereqError.
3614

3615
    """
3616
    cfg = self.cfg
3617
    hostname = self.hostname
3618
    node = hostname.name
3619
    primary_ip = self.op.primary_ip = hostname.ip
3620
    if self.op.secondary_ip is None:
3621
      if self.primary_ip_family == netutils.IP6Address.family:
3622
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3623
                                   " IPv4 address must be given as secondary",
3624
                                   errors.ECODE_INVAL)
3625
      self.op.secondary_ip = primary_ip
3626

    
3627
    secondary_ip = self.op.secondary_ip
3628
    if not netutils.IP4Address.IsValid(secondary_ip):
3629
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3630
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3631

    
3632
    node_list = cfg.GetNodeList()
3633
    if not self.op.readd and node in node_list:
3634
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3635
                                 node, errors.ECODE_EXISTS)
3636
    elif self.op.readd and node not in node_list:
3637
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3638
                                 errors.ECODE_NOENT)
3639

    
3640
    self.changed_primary_ip = False
3641

    
3642
    for existing_node_name in node_list:
3643
      existing_node = cfg.GetNodeInfo(existing_node_name)
3644

    
3645
      if self.op.readd and node == existing_node_name:
3646
        if existing_node.secondary_ip != secondary_ip:
3647
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3648
                                     " address configuration as before",
3649
                                     errors.ECODE_INVAL)
3650
        if existing_node.primary_ip != primary_ip:
3651
          self.changed_primary_ip = True
3652

    
3653
        continue
3654

    
3655
      if (existing_node.primary_ip == primary_ip or
3656
          existing_node.secondary_ip == primary_ip or
3657
          existing_node.primary_ip == secondary_ip or
3658
          existing_node.secondary_ip == secondary_ip):
3659
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3660
                                   " existing node %s" % existing_node.name,
3661
                                   errors.ECODE_NOTUNIQUE)
3662

    
3663
    # check that the type of the node (single versus dual homed) is the
3664
    # same as for the master
3665
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3666
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3667
    newbie_singlehomed = secondary_ip == primary_ip
3668
    if master_singlehomed != newbie_singlehomed:
3669
      if master_singlehomed:
3670
        raise errors.OpPrereqError("The master has no private ip but the"
3671
                                   " new node has one",
3672
                                   errors.ECODE_INVAL)
3673
      else:
3674
        raise errors.OpPrereqError("The master has a private ip but the"
3675
                                   " new node doesn't have one",
3676
                                   errors.ECODE_INVAL)
3677

    
3678
    # checks reachability
3679
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3680
      raise errors.OpPrereqError("Node not reachable by ping",
3681
                                 errors.ECODE_ENVIRON)
3682

    
3683
    if not newbie_singlehomed:
3684
      # check reachability from my secondary ip to newbie's secondary ip
3685
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3686
                           source=myself.secondary_ip):
3687
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3688
                                   " based ping to noded port",
3689
                                   errors.ECODE_ENVIRON)
3690

    
3691
    if self.op.readd:
3692
      exceptions = [node]
3693
    else:
3694
      exceptions = []
3695

    
3696
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3697

    
3698
    if self.op.readd:
3699
      self.new_node = self.cfg.GetNodeInfo(node)
3700
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3701
    else:
3702
      node_group = cfg.LookupNodeGroup(self.op.group)
3703
      self.new_node = objects.Node(name=node,
3704
                                   primary_ip=primary_ip,
3705
                                   secondary_ip=secondary_ip,
3706
                                   master_candidate=self.master_candidate,
3707
                                   master_capable=True,
3708
                                   vm_capable=True,
3709
                                   offline=False, drained=False,
3710
                                   group=node_group)
3711

    
3712
  def Exec(self, feedback_fn):
3713
    """Adds the new node to the cluster.
3714

3715
    """
3716
    new_node = self.new_node
3717
    node = new_node.name
3718

    
3719
    # for re-adds, reset the offline/drained/master-candidate flags;
3720
    # we need to reset here, otherwise offline would prevent RPC calls
3721
    # later in the procedure; this also means that if the re-add
3722
    # fails, we are left with a non-offlined, broken node
3723
    if self.op.readd:
3724
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3725
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3726
      # if we demote the node, we do cleanup later in the procedure
3727
      new_node.master_candidate = self.master_candidate
3728
      if self.changed_primary_ip:
3729
        new_node.primary_ip = self.op.primary_ip
3730

    
3731
    # notify the user about any possible mc promotion
3732
    if new_node.master_candidate:
3733
      self.LogInfo("Node will be a master candidate")
3734

    
3735
    # check connectivity
3736
    result = self.rpc.call_version([node])[node]
3737
    result.Raise("Can't get version information from node %s" % node)
3738
    if constants.PROTOCOL_VERSION == result.payload:
3739
      logging.info("Communication to node %s fine, sw version %s match",
3740
                   node, result.payload)
3741
    else:
3742
      raise errors.OpExecError("Version mismatch master version %s,"
3743
                               " node version %s" %
3744
                               (constants.PROTOCOL_VERSION, result.payload))
3745

    
3746
    # Add node to our /etc/hosts, and add key to known_hosts
3747
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3748
      master_node = self.cfg.GetMasterNode()
3749
      result = self.rpc.call_etc_hosts_modify(master_node,
3750
                                              constants.ETC_HOSTS_ADD,
3751
                                              self.hostname.name,
3752
                                              self.hostname.ip)
3753
      result.Raise("Can't update hosts file with new host data")
3754

    
3755
    if new_node.secondary_ip != new_node.primary_ip:
3756
      result = self.rpc.call_node_has_ip_address(new_node.name,
3757
                                                 new_node.secondary_ip)
3758
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3759
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3760
      if not result.payload:
3761
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3762
                                 " you gave (%s). Please fix and re-run this"
3763
                                 " command." % new_node.secondary_ip)
3764

    
3765
    node_verify_list = [self.cfg.GetMasterNode()]
3766
    node_verify_param = {
3767
      constants.NV_NODELIST: [node],
3768
      # TODO: do a node-net-test as well?
3769
    }
3770

    
3771
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3772
                                       self.cfg.GetClusterName())
3773
    for verifier in node_verify_list:
3774
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3775
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3776
      if nl_payload:
3777
        for failed in nl_payload:
3778
          feedback_fn("ssh/hostname verification failed"
3779
                      " (checking from %s): %s" %
3780
                      (verifier, nl_payload[failed]))
3781
        raise errors.OpExecError("ssh/hostname verification failed.")
3782

    
3783
    if self.op.readd:
3784
      _RedistributeAncillaryFiles(self)
3785
      self.context.ReaddNode(new_node)
3786
      # make sure we redistribute the config
3787
      self.cfg.Update(new_node, feedback_fn)
3788
      # and make sure the new node will not have old files around
3789
      if not new_node.master_candidate:
3790
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3791
        msg = result.fail_msg
3792
        if msg:
3793
          self.LogWarning("Node failed to demote itself from master"
3794
                          " candidate status: %s" % msg)
3795
    else:
3796
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3797
      self.context.AddNode(new_node, self.proc.GetECId())
3798

    
3799

    
3800
class LUSetNodeParams(LogicalUnit):
3801
  """Modifies the parameters of a node.
3802

3803
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
3804
      to the node role (as _ROLE_*)
3805
  @cvar _R2F: a dictionary from node role to tuples of flags
3806
  @cvar _FLAGS: a list of attribute names corresponding to the flags
3807

3808
  """
3809
  HPATH = "node-modify"
3810
  HTYPE = constants.HTYPE_NODE
3811
  _OP_PARAMS = [
3812
    _PNodeName,
3813
    ("master_candidate", None, ht.TMaybeBool),
3814
    ("offline", None, ht.TMaybeBool),
3815
    ("drained", None, ht.TMaybeBool),
3816
    ("auto_promote", False, ht.TBool),
3817
    ("master_capable", None, ht.TMaybeBool),
3818
    _PForce,
3819
    ]
3820
  REQ_BGL = False
3821
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
3822
  _F2R = {
3823
    (True, False, False): _ROLE_CANDIDATE,
3824
    (False, True, False): _ROLE_DRAINED,
3825
    (False, False, True): _ROLE_OFFLINE,
3826
    (False, False, False): _ROLE_REGULAR,
3827
    }
3828
  _R2F = dict((v, k) for k, v in _F2R.items())
3829
  _FLAGS = ["master_candidate", "drained", "offline"]
3830

    
3831
  def CheckArguments(self):
3832
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3833
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
3834
                self.op.master_capable]
3835
    if all_mods.count(None) == len(all_mods):
3836
      raise errors.OpPrereqError("Please pass at least one modification",
3837
                                 errors.ECODE_INVAL)
3838
    if all_mods.count(True) > 1:
3839
      raise errors.OpPrereqError("Can't set the node into more than one"
3840
                                 " state at the same time",
3841
                                 errors.ECODE_INVAL)
3842

    
3843
    # Boolean value that tells us whether we might be demoting from MC
3844
    self.might_demote = (self.op.master_candidate == False or
3845
                         self.op.offline == True or
3846
                         self.op.drained == True or
3847
                         self.op.master_capable == False)
3848

    
3849
    self.lock_all = self.op.auto_promote and self.might_demote
3850

    
3851
  def ExpandNames(self):
3852
    if self.lock_all:
3853
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3854
    else:
3855
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3856

    
3857
  def BuildHooksEnv(self):
3858
    """Build hooks env.
3859

3860
    This runs on the master node.
3861

3862
    """
3863
    env = {
3864
      "OP_TARGET": self.op.node_name,
3865
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3866
      "OFFLINE": str(self.op.offline),
3867
      "DRAINED": str(self.op.drained),
3868
      "MASTER_CAPABLE": str(self.op.master_capable),
3869
      }
3870
    nl = [self.cfg.GetMasterNode(),
3871
          self.op.node_name]
3872
    return env, nl, nl
3873

    
3874
  def CheckPrereq(self):
3875
    """Check prerequisites.
3876

3877
    This only checks the instance list against the existing names.
3878

3879
    """
3880
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3881

    
3882
    if (self.op.master_candidate is not None or
3883
        self.op.drained is not None or
3884
        self.op.offline is not None):
3885
      # we can't change the master's node flags
3886
      if self.op.node_name == self.cfg.GetMasterNode():
3887
        raise errors.OpPrereqError("The master role can be changed"
3888
                                   " only via master-failover",
3889
                                   errors.ECODE_INVAL)
3890

    
3891
    if self.op.master_candidate and not node.master_capable:
3892
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
3893
                                 " it a master candidate" % node.name,
3894
                                 errors.ECODE_STATE)
3895

    
3896
    if node.master_candidate and self.might_demote and not self.lock_all:
3897
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3898
      # check if after removing the current node, we're missing master
3899
      # candidates
3900
      (mc_remaining, mc_should, _) = \
3901
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3902
      if mc_remaining < mc_should:
3903
        raise errors.OpPrereqError("Not enough master candidates, please"
3904
                                   " pass auto_promote to allow promotion",
3905
                                   errors.ECODE_STATE)
3906

    
3907
    self.old_flags = old_flags = (node.master_candidate,
3908
                                  node.drained, node.offline)
3909
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
3910
    self.old_role = self._F2R[old_flags]
3911

    
3912
    # Check for ineffective changes
3913
    for attr in self._FLAGS:
3914
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
3915
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
3916
        setattr(self.op, attr, None)
3917

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

    
3921
    # If we're being deofflined/drained, we'll MC ourself if needed
3922
    if (self.op.drained == False or self.op.offline == False or
3923
        (self.op.master_capable and not node.master_capable)):
3924
      if _DecideSelfPromotion(self):
3925
        self.op.master_candidate = True
3926
        self.LogInfo("Auto-promoting node to master candidate")
3927

    
3928
    # If we're no longer master capable, we'll demote ourselves from MC
3929
    if self.op.master_capable == False and node.master_candidate:
3930
      self.LogInfo("Demoting from master candidate")
3931
      self.op.master_candidate = False
3932

    
3933
  def Exec(self, feedback_fn):
3934
    """Modifies a node.
3935

3936
    """
3937
    node = self.node
3938
    old_role = self.old_role
3939

    
3940
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
3941

    
3942
    # compute new flags
3943
    if self.op.master_candidate:
3944
      new_role = self._ROLE_CANDIDATE
3945
    elif self.op.drained:
3946
      new_role = self._ROLE_DRAINED
3947
    elif self.op.offline:
3948
      new_role = self._ROLE_OFFLINE
3949
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
3950
      # False is still in new flags, which means we're un-setting (the
3951
      # only) True flag
3952
      new_role = self._ROLE_REGULAR
3953
    else: # no new flags, nothing, keep old role
3954
      new_role = old_role
3955

    
3956
    result = []
3957
    changed_mc = [old_role, new_role].count(self._ROLE_CANDIDATE) == 1
3958

    
3959
    if self.op.master_capable is not None:
3960
      node.master_capable = self.op.master_capable
3961
      result.append(("master_capable", str(self.op.master_capable)))
3962

    
3963
    # Tell the node to demote itself, if no longer MC and not offline
3964
    if (old_role == self._ROLE_CANDIDATE and
3965
        new_role != self._ROLE_OFFLINE and new_role != old_role):
3966
      msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
3967
      if msg:
3968
        self.LogWarning("Node failed to demote itself: %s", msg)
3969

    
3970
    new_flags = self._R2F[new_role]
3971
    for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
3972
      if of != nf:
3973
        result.append((desc, str(nf)))
3974
    (node.master_candidate, node.drained, node.offline) = new_flags
3975

    
3976
    # we locked all nodes, we adjust the CP before updating this node
3977
    if self.lock_all:
3978
      _AdjustCandidatePool(self, [node.name])
3979

    
3980
    # this will trigger configuration file update, if needed
3981
    self.cfg.Update(node, feedback_fn)
3982

    
3983
    # this will trigger job queue propagation or cleanup
3984
    if changed_mc:
3985
      self.context.ReaddNode(node)
3986

    
3987
    return result
3988

    
3989

    
3990
class LUPowercycleNode(NoHooksLU):
3991
  """Powercycles a node.
3992

3993
  """
3994
  _OP_PARAMS = [
3995
    _PNodeName,
3996
    _PForce,
3997
    ]
3998
  REQ_BGL = False
3999

    
4000
  def CheckArguments(self):
4001
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4002
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4003
      raise errors.OpPrereqError("The node is the master and the force"
4004
                                 " parameter was not set",
4005
                                 errors.ECODE_INVAL)
4006

    
4007
  def ExpandNames(self):
4008
    """Locking for PowercycleNode.
4009

4010
    This is a last-resort option and shouldn't block on other
4011
    jobs. Therefore, we grab no locks.
4012

4013
    """
4014
    self.needed_locks = {}
4015

    
4016
  def Exec(self, feedback_fn):
4017
    """Reboots a node.
4018

4019
    """
4020
    result = self.rpc.call_node_powercycle(self.op.node_name,
4021
                                           self.cfg.GetHypervisorType())
4022
    result.Raise("Failed to schedule the reboot")
4023
    return result.payload
4024

    
4025

    
4026
class LUQueryClusterInfo(NoHooksLU):
4027
  """Query cluster configuration.
4028

4029
  """
4030
  REQ_BGL = False
4031

    
4032
  def ExpandNames(self):
4033
    self.needed_locks = {}
4034

    
4035
  def Exec(self, feedback_fn):
4036
    """Return cluster config.
4037

4038
    """
4039
    cluster = self.cfg.GetClusterInfo()
4040
    os_hvp = {}
4041

    
4042
    # Filter just for enabled hypervisors
4043
    for os_name, hv_dict in cluster.os_hvp.items():
4044
      os_hvp[os_name] = {}
4045
      for hv_name, hv_params in hv_dict.items():
4046
        if hv_name in cluster.enabled_hypervisors:
4047
          os_hvp[os_name][hv_name] = hv_params
4048

    
4049
    # Convert ip_family to ip_version
4050
    primary_ip_version = constants.IP4_VERSION
4051
    if cluster.primary_ip_family == netutils.IP6Address.family:
4052
      primary_ip_version = constants.IP6_VERSION
4053

    
4054
    result = {
4055
      "software_version": constants.RELEASE_VERSION,
4056
      "protocol_version": constants.PROTOCOL_VERSION,
4057
      "config_version": constants.CONFIG_VERSION,
4058
      "os_api_version": max(constants.OS_API_VERSIONS),
4059
      "export_version": constants.EXPORT_VERSION,
4060
      "architecture": (platform.architecture()[0], platform.machine()),
4061
      "name": cluster.cluster_name,
4062
      "master": cluster.master_node,
4063
      "default_hypervisor": cluster.enabled_hypervisors[0],
4064
      "enabled_hypervisors": cluster.enabled_hypervisors,
4065
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4066
                        for hypervisor_name in cluster.enabled_hypervisors]),
4067
      "os_hvp": os_hvp,
4068
      "beparams": cluster.beparams,
4069
      "osparams": cluster.osparams,
4070
      "nicparams": cluster.nicparams,
4071
      "candidate_pool_size": cluster.candidate_pool_size,
4072
      "master_netdev": cluster.master_netdev,
4073
      "volume_group_name": cluster.volume_group_name,
4074
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4075
      "file_storage_dir": cluster.file_storage_dir,
4076
      "maintain_node_health": cluster.maintain_node_health,
4077
      "ctime": cluster.ctime,
4078
      "mtime": cluster.mtime,
4079
      "uuid": cluster.uuid,
4080
      "tags": list(cluster.GetTags()),
4081
      "uid_pool": cluster.uid_pool,
4082
      "default_iallocator": cluster.default_iallocator,
4083
      "reserved_lvs": cluster.reserved_lvs,
4084
      "primary_ip_version": primary_ip_version,
4085
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4086
      }
4087

    
4088
    return result
4089

    
4090

    
4091
class LUQueryConfigValues(NoHooksLU):
4092
  """Return configuration values.
4093

4094
  """
4095
  _OP_PARAMS = [_POutputFields]
4096
  REQ_BGL = False
4097
  _FIELDS_DYNAMIC = utils.FieldSet()
4098
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4099
                                  "watcher_pause", "volume_group_name")
4100

    
4101
  def CheckArguments(self):
4102
    _CheckOutputFields(static=self._FIELDS_STATIC,
4103
                       dynamic=self._FIELDS_DYNAMIC,
4104
                       selected=self.op.output_fields)
4105

    
4106
  def ExpandNames(self):
4107
    self.needed_locks = {}
4108

    
4109
  def Exec(self, feedback_fn):
4110
    """Dump a representation of the cluster config to the standard output.
4111

4112
    """
4113
    values = []
4114
    for field in self.op.output_fields:
4115
      if field == "cluster_name":
4116
        entry = self.cfg.GetClusterName()
4117
      elif field == "master_node":
4118
        entry = self.cfg.GetMasterNode()
4119
      elif field == "drain_flag":
4120
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4121
      elif field == "watcher_pause":
4122
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4123
      elif field == "volume_group_name":
4124
        entry = self.cfg.GetVGName()
4125
      else:
4126
        raise errors.ParameterError(field)
4127
      values.append(entry)
4128
    return values
4129

    
4130

    
4131
class LUActivateInstanceDisks(NoHooksLU):
4132
  """Bring up an instance's disks.
4133

4134
  """
4135
  _OP_PARAMS = [
4136
    _PInstanceName,
4137
    ("ignore_size", False, ht.TBool),
4138
    ]
4139
  REQ_BGL = False
4140

    
4141
  def ExpandNames(self):
4142
    self._ExpandAndLockInstance()
4143
    self.needed_locks[locking.LEVEL_NODE] = []
4144
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4145

    
4146
  def DeclareLocks(self, level):
4147
    if level == locking.LEVEL_NODE:
4148
      self._LockInstancesNodes()
4149

    
4150
  def CheckPrereq(self):
4151
    """Check prerequisites.
4152

4153
    This checks that the instance is in the cluster.
4154

4155
    """
4156
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4157
    assert self.instance is not None, \
4158
      "Cannot retrieve locked instance %s" % self.op.instance_name
4159
    _CheckNodeOnline(self, self.instance.primary_node)
4160

    
4161
  def Exec(self, feedback_fn):
4162
    """Activate the disks.
4163

4164
    """
4165
    disks_ok, disks_info = \
4166
              _AssembleInstanceDisks(self, self.instance,
4167
                                     ignore_size=self.op.ignore_size)
4168
    if not disks_ok:
4169
      raise errors.OpExecError("Cannot activate block devices")
4170

    
4171
    return disks_info
4172

    
4173

    
4174
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4175
                           ignore_size=False):
4176
  """Prepare the block devices for an instance.
4177

4178
  This sets up the block devices on all nodes.
4179

4180
  @type lu: L{LogicalUnit}
4181
  @param lu: the logical unit on whose behalf we execute
4182
  @type instance: L{objects.Instance}
4183
  @param instance: the instance for whose disks we assemble
4184
  @type disks: list of L{objects.Disk} or None
4185
  @param disks: which disks to assemble (or all, if None)
4186
  @type ignore_secondaries: boolean
4187
  @param ignore_secondaries: if true, errors on secondary nodes
4188
      won't result in an error return from the function
4189
  @type ignore_size: boolean
4190
  @param ignore_size: if true, the current known size of the disk
4191
      will not be used during the disk activation, useful for cases
4192
      when the size is wrong
4193
  @return: False if the operation failed, otherwise a list of
4194
      (host, instance_visible_name, node_visible_name)
4195
      with the mapping from node devices to instance devices
4196

4197
  """
4198
  device_info = []
4199
  disks_ok = True
4200
  iname = instance.name
4201
  disks = _ExpandCheckDisks(instance, disks)
4202

    
4203
  # With the two passes mechanism we try to reduce the window of
4204
  # opportunity for the race condition of switching DRBD to primary
4205
  # before handshaking occured, but we do not eliminate it
4206

    
4207
  # The proper fix would be to wait (with some limits) until the
4208
  # connection has been made and drbd transitions from WFConnection
4209
  # into any other network-connected state (Connected, SyncTarget,
4210
  # SyncSource, etc.)
4211

    
4212
  # 1st pass, assemble on all nodes in secondary mode
4213
  for inst_disk in disks:
4214
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4215
      if ignore_size:
4216
        node_disk = node_disk.Copy()
4217
        node_disk.UnsetSize()
4218
      lu.cfg.SetDiskID(node_disk, node)
4219
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4220
      msg = result.fail_msg
4221
      if msg:
4222
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4223
                           " (is_primary=False, pass=1): %s",
4224
                           inst_disk.iv_name, node, msg)
4225
        if not ignore_secondaries:
4226
          disks_ok = False
4227

    
4228
  # FIXME: race condition on drbd migration to primary
4229

    
4230
  # 2nd pass, do only the primary node
4231
  for inst_disk in disks:
4232
    dev_path = None
4233

    
4234
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4235
      if node != instance.primary_node:
4236
        continue
4237
      if ignore_size:
4238
        node_disk = node_disk.Copy()
4239
        node_disk.UnsetSize()
4240
      lu.cfg.SetDiskID(node_disk, node)
4241
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4242
      msg = result.fail_msg
4243
      if msg:
4244
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4245
                           " (is_primary=True, pass=2): %s",
4246
                           inst_disk.iv_name, node, msg)
4247
        disks_ok = False
4248
      else:
4249
        dev_path = result.payload
4250

    
4251
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4252

    
4253
  # leave the disks configured for the primary node
4254
  # this is a workaround that would be fixed better by
4255
  # improving the logical/physical id handling
4256
  for disk in disks:
4257
    lu.cfg.SetDiskID(disk, instance.primary_node)
4258

    
4259
  return disks_ok, device_info
4260

    
4261

    
4262
def _StartInstanceDisks(lu, instance, force):
4263
  """Start the disks of an instance.
4264

4265
  """
4266
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4267
                                           ignore_secondaries=force)
4268
  if not disks_ok:
4269
    _ShutdownInstanceDisks(lu, instance)
4270
    if force is not None and not force:
4271
      lu.proc.LogWarning("", hint="If the message above refers to a"
4272
                         " secondary node,"
4273
                         " you can retry the operation using '--force'.")
4274
    raise errors.OpExecError("Disk consistency error")
4275

    
4276

    
4277
class LUDeactivateInstanceDisks(NoHooksLU):
4278
  """Shutdown an instance's disks.
4279

4280
  """
4281
  _OP_PARAMS = [
4282
    _PInstanceName,
4283
    ]
4284
  REQ_BGL = False
4285

    
4286
  def ExpandNames(self):
4287
    self._ExpandAndLockInstance()
4288
    self.needed_locks[locking.LEVEL_NODE] = []
4289
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4290

    
4291
  def DeclareLocks(self, level):
4292
    if level == locking.LEVEL_NODE:
4293
      self._LockInstancesNodes()
4294

    
4295
  def CheckPrereq(self):
4296
    """Check prerequisites.
4297

4298
    This checks that the instance is in the cluster.
4299

4300
    """
4301
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4302
    assert self.instance is not None, \
4303
      "Cannot retrieve locked instance %s" % self.op.instance_name
4304

    
4305
  def Exec(self, feedback_fn):
4306
    """Deactivate the disks
4307

4308
    """
4309
    instance = self.instance
4310
    _SafeShutdownInstanceDisks(self, instance)
4311

    
4312

    
4313
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4314
  """Shutdown block devices of an instance.
4315

4316
  This function checks if an instance is running, before calling
4317
  _ShutdownInstanceDisks.
4318

4319
  """
4320
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4321
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4322

    
4323

    
4324
def _ExpandCheckDisks(instance, disks):
4325
  """Return the instance disks selected by the disks list
4326

4327
  @type disks: list of L{objects.Disk} or None
4328
  @param disks: selected disks
4329
  @rtype: list of L{objects.Disk}
4330
  @return: selected instance disks to act on
4331

4332
  """
4333
  if disks is None:
4334
    return instance.disks
4335
  else:
4336
    if not set(disks).issubset(instance.disks):
4337
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4338
                                   " target instance")
4339
    return disks
4340

    
4341

    
4342
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4343
  """Shutdown block devices of an instance.
4344

4345
  This does the shutdown on all nodes of the instance.
4346

4347
  If the ignore_primary is false, errors on the primary node are
4348
  ignored.
4349

4350
  """
4351
  all_result = True
4352
  disks = _ExpandCheckDisks(instance, disks)
4353

    
4354
  for disk in disks:
4355
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4356
      lu.cfg.SetDiskID(top_disk, node)
4357
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4358
      msg = result.fail_msg
4359
      if msg:
4360
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4361
                      disk.iv_name, node, msg)
4362
        if not ignore_primary or node != instance.primary_node:
4363
          all_result = False
4364
  return all_result
4365

    
4366

    
4367
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4368
  """Checks if a node has enough free memory.
4369

4370
  This function check if a given node has the needed amount of free
4371
  memory. In case the node has less memory or we cannot get the
4372
  information from the node, this function raise an OpPrereqError
4373
  exception.
4374

4375
  @type lu: C{LogicalUnit}
4376
  @param lu: a logical unit from which we get configuration data
4377
  @type node: C{str}
4378
  @param node: the node to check
4379
  @type reason: C{str}
4380
  @param reason: string to use in the error message
4381
  @type requested: C{int}
4382
  @param requested: the amount of memory in MiB to check for
4383
  @type hypervisor_name: C{str}
4384
  @param hypervisor_name: the hypervisor to ask for memory stats
4385
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4386
      we cannot check the node
4387

4388
  """
4389
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4390
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4391
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4392
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4393
  if not isinstance(free_mem, int):
4394
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4395
                               " was '%s'" % (node, free_mem),
4396
                               errors.ECODE_ENVIRON)
4397
  if requested > free_mem:
4398
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4399
                               " needed %s MiB, available %s MiB" %
4400
                               (node, reason, requested, free_mem),
4401
                               errors.ECODE_NORES)
4402

    
4403

    
4404
def _CheckNodesFreeDisk(lu, nodenames, requested):
4405
  """Checks if nodes have enough free disk space in the default VG.
4406

4407
  This function check if all given nodes have the needed amount of
4408
  free disk. In case any node has less disk or we cannot get the
4409
  information from the node, this function raise an OpPrereqError
4410
  exception.
4411

4412
  @type lu: C{LogicalUnit}
4413
  @param lu: a logical unit from which we get configuration data
4414
  @type nodenames: C{list}
4415
  @param nodenames: the list of node names to check
4416
  @type requested: C{int}
4417
  @param requested: the amount of disk in MiB to check for
4418
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4419
      we cannot check the node
4420

4421
  """
4422
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4423
                                   lu.cfg.GetHypervisorType())
4424
  for node in nodenames:
4425
    info = nodeinfo[node]
4426
    info.Raise("Cannot get current information from node %s" % node,
4427
               prereq=True, ecode=errors.ECODE_ENVIRON)
4428
    vg_free = info.payload.get("vg_free", None)
4429
    if not isinstance(vg_free, int):
4430
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4431
                                 " result was '%s'" % (node, vg_free),
4432
                                 errors.ECODE_ENVIRON)
4433
    if requested > vg_free:
4434
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4435
                                 " required %d MiB, available %d MiB" %
4436
                                 (node, requested, vg_free),
4437
                                 errors.ECODE_NORES)
4438

    
4439

    
4440
class LUStartupInstance(LogicalUnit):
4441
  """Starts an instance.
4442

4443
  """
4444
  HPATH = "instance-start"
4445
  HTYPE = constants.HTYPE_INSTANCE
4446
  _OP_PARAMS = [
4447
    _PInstanceName,
4448
    _PForce,
4449
    _PIgnoreOfflineNodes,
4450
    ("hvparams", ht.EmptyDict, ht.TDict),
4451
    ("beparams", ht.EmptyDict, ht.TDict),
4452
    ]
4453
  REQ_BGL = False
4454

    
4455
  def CheckArguments(self):
4456
    # extra beparams
4457
    if self.op.beparams:
4458
      # fill the beparams dict
4459
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4460

    
4461
  def ExpandNames(self):
4462
    self._ExpandAndLockInstance()
4463

    
4464
  def BuildHooksEnv(self):
4465
    """Build hooks env.
4466

4467
    This runs on master, primary and secondary nodes of the instance.
4468

4469
    """
4470
    env = {
4471
      "FORCE": self.op.force,
4472
      }
4473
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4474
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4475
    return env, nl, nl
4476

    
4477
  def CheckPrereq(self):
4478
    """Check prerequisites.
4479

4480
    This checks that the instance is in the cluster.
4481

4482
    """
4483
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4484
    assert self.instance is not None, \
4485
      "Cannot retrieve locked instance %s" % self.op.instance_name
4486

    
4487
    # extra hvparams
4488
    if self.op.hvparams:
4489
      # check hypervisor parameter syntax (locally)
4490
      cluster = self.cfg.GetClusterInfo()
4491
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4492
      filled_hvp = cluster.FillHV(instance)
4493
      filled_hvp.update(self.op.hvparams)
4494
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4495
      hv_type.CheckParameterSyntax(filled_hvp)
4496
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4497

    
4498
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4499

    
4500
    if self.primary_offline and self.op.ignore_offline_nodes:
4501
      self.proc.LogWarning("Ignoring offline primary node")
4502

    
4503
      if self.op.hvparams or self.op.beparams:
4504
        self.proc.LogWarning("Overridden parameters are ignored")
4505
    else:
4506
      _CheckNodeOnline(self, instance.primary_node)
4507

    
4508
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4509

    
4510
      # check bridges existence
4511
      _CheckInstanceBridgesExist(self, instance)
4512

    
4513
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4514
                                                instance.name,
4515
                                                instance.hypervisor)
4516
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4517
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4518
      if not remote_info.payload: # not running already
4519
        _CheckNodeFreeMemory(self, instance.primary_node,
4520
                             "starting instance %s" % instance.name,
4521
                             bep[constants.BE_MEMORY], instance.hypervisor)
4522

    
4523
  def Exec(self, feedback_fn):
4524
    """Start the instance.
4525

4526
    """
4527
    instance = self.instance
4528
    force = self.op.force
4529

    
4530
    self.cfg.MarkInstanceUp(instance.name)
4531

    
4532
    if self.primary_offline:
4533
      assert self.op.ignore_offline_nodes
4534
      self.proc.LogInfo("Primary node offline, marked instance as started")
4535
    else:
4536
      node_current = instance.primary_node
4537

    
4538
      _StartInstanceDisks(self, instance, force)
4539

    
4540
      result = self.rpc.call_instance_start(node_current, instance,
4541
                                            self.op.hvparams, self.op.beparams)
4542
      msg = result.fail_msg
4543
      if msg:
4544
        _ShutdownInstanceDisks(self, instance)
4545
        raise errors.OpExecError("Could not start instance: %s" % msg)
4546

    
4547

    
4548
class LURebootInstance(LogicalUnit):
4549
  """Reboot an instance.
4550

4551
  """
4552
  HPATH = "instance-reboot"
4553
  HTYPE = constants.HTYPE_INSTANCE
4554
  _OP_PARAMS = [
4555
    _PInstanceName,
4556
    ("ignore_secondaries", False, ht.TBool),
4557
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4558
    _PShutdownTimeout,
4559
    ]
4560
  REQ_BGL = False
4561

    
4562
  def ExpandNames(self):
4563
    self._ExpandAndLockInstance()
4564

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

4568
    This runs on master, primary and secondary nodes of the instance.
4569

4570
    """
4571
    env = {
4572
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4573
      "REBOOT_TYPE": self.op.reboot_type,
4574
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4575
      }
4576
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4577
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4578
    return env, nl, nl
4579

    
4580
  def CheckPrereq(self):
4581
    """Check prerequisites.
4582

4583
    This checks that the instance is in the cluster.
4584

4585
    """
4586
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4587
    assert self.instance is not None, \
4588
      "Cannot retrieve locked instance %s" % self.op.instance_name
4589

    
4590
    _CheckNodeOnline(self, instance.primary_node)
4591

    
4592
    # check bridges existence
4593
    _CheckInstanceBridgesExist(self, instance)
4594

    
4595
  def Exec(self, feedback_fn):
4596
    """Reboot the instance.
4597

4598
    """
4599
    instance = self.instance
4600
    ignore_secondaries = self.op.ignore_secondaries
4601
    reboot_type = self.op.reboot_type
4602

    
4603
    node_current = instance.primary_node
4604

    
4605
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4606
                       constants.INSTANCE_REBOOT_HARD]:
4607
      for disk in instance.disks:
4608
        self.cfg.SetDiskID(disk, node_current)
4609
      result = self.rpc.call_instance_reboot(node_current, instance,
4610
                                             reboot_type,
4611
                                             self.op.shutdown_timeout)
4612
      result.Raise("Could not reboot instance")
4613
    else:
4614
      result = self.rpc.call_instance_shutdown(node_current, instance,
4615
                                               self.op.shutdown_timeout)
4616
      result.Raise("Could not shutdown instance for full reboot")
4617
      _ShutdownInstanceDisks(self, instance)
4618
      _StartInstanceDisks(self, instance, ignore_secondaries)
4619
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4620
      msg = result.fail_msg
4621
      if msg:
4622
        _ShutdownInstanceDisks(self, instance)
4623
        raise errors.OpExecError("Could not start instance for"
4624
                                 " full reboot: %s" % msg)
4625

    
4626
    self.cfg.MarkInstanceUp(instance.name)
4627

    
4628

    
4629
class LUShutdownInstance(LogicalUnit):
4630
  """Shutdown an instance.
4631

4632
  """
4633
  HPATH = "instance-stop"
4634
  HTYPE = constants.HTYPE_INSTANCE
4635
  _OP_PARAMS = [
4636
    _PInstanceName,
4637
    _PIgnoreOfflineNodes,
4638
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
4639
    ]
4640
  REQ_BGL = False
4641

    
4642
  def ExpandNames(self):
4643
    self._ExpandAndLockInstance()
4644

    
4645
  def BuildHooksEnv(self):
4646
    """Build hooks env.
4647

4648
    This runs on master, primary and secondary nodes of the instance.
4649

4650
    """
4651
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4652
    env["TIMEOUT"] = self.op.timeout
4653
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4654
    return env, nl, nl
4655

    
4656
  def CheckPrereq(self):
4657
    """Check prerequisites.
4658

4659
    This checks that the instance is in the cluster.
4660

4661
    """
4662
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4663
    assert self.instance is not None, \
4664
      "Cannot retrieve locked instance %s" % self.op.instance_name
4665

    
4666
    self.primary_offline = \
4667
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
4668

    
4669
    if self.primary_offline and self.op.ignore_offline_nodes:
4670
      self.proc.LogWarning("Ignoring offline primary node")
4671
    else:
4672
      _CheckNodeOnline(self, self.instance.primary_node)
4673

    
4674
  def Exec(self, feedback_fn):
4675
    """Shutdown the instance.
4676

4677
    """
4678
    instance = self.instance
4679
    node_current = instance.primary_node
4680
    timeout = self.op.timeout
4681

    
4682
    self.cfg.MarkInstanceDown(instance.name)
4683

    
4684
    if self.primary_offline:
4685
      assert self.op.ignore_offline_nodes
4686
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
4687
    else:
4688
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4689
      msg = result.fail_msg
4690
      if msg:
4691
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4692

    
4693
      _ShutdownInstanceDisks(self, instance)
4694

    
4695

    
4696
class LUReinstallInstance(LogicalUnit):
4697
  """Reinstall an instance.
4698

4699
  """
4700
  HPATH = "instance-reinstall"
4701
  HTYPE = constants.HTYPE_INSTANCE
4702
  _OP_PARAMS = [
4703
    _PInstanceName,
4704
    ("os_type", None, ht.TMaybeString),
4705
    ("force_variant", False, ht.TBool),
4706
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
4707
    ]
4708
  REQ_BGL = False
4709

    
4710
  def ExpandNames(self):
4711
    self._ExpandAndLockInstance()
4712

    
4713
  def BuildHooksEnv(self):
4714
    """Build hooks env.
4715

4716
    This runs on master, primary and secondary nodes of the instance.
4717

4718
    """
4719
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4720
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4721
    return env, nl, nl
4722

    
4723
  def CheckPrereq(self):
4724
    """Check prerequisites.
4725

4726
    This checks that the instance is in the cluster and is not running.
4727

4728
    """
4729
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4730
    assert instance is not None, \
4731
      "Cannot retrieve locked instance %s" % self.op.instance_name
4732
    _CheckNodeOnline(self, instance.primary_node)
4733

    
4734
    if instance.disk_template == constants.DT_DISKLESS:
4735
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4736
                                 self.op.instance_name,
4737
                                 errors.ECODE_INVAL)
4738
    _CheckInstanceDown(self, instance, "cannot reinstall")
4739

    
4740
    if self.op.os_type is not None:
4741
      # OS verification
4742
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4743
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4744
      instance_os = self.op.os_type
4745
    else:
4746
      instance_os = instance.os
4747

    
4748
    nodelist = list(instance.all_nodes)
4749

    
4750
    if self.op.osparams:
4751
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
4752
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
4753
      self.os_inst = i_osdict # the new dict (without defaults)
4754
    else:
4755
      self.os_inst = None
4756

    
4757
    self.instance = instance
4758

    
4759
  def Exec(self, feedback_fn):
4760
    """Reinstall the instance.
4761

4762
    """
4763
    inst = self.instance
4764

    
4765
    if self.op.os_type is not None:
4766
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4767
      inst.os = self.op.os_type
4768
      # Write to configuration
4769
      self.cfg.Update(inst, feedback_fn)
4770

    
4771
    _StartInstanceDisks(self, inst, None)
4772
    try:
4773
      feedback_fn("Running the instance OS create scripts...")
4774
      # FIXME: pass debug option from opcode to backend
4775
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4776
                                             self.op.debug_level,
4777
                                             osparams=self.os_inst)
4778
      result.Raise("Could not install OS for instance %s on node %s" %
4779
                   (inst.name, inst.primary_node))
4780
    finally:
4781
      _ShutdownInstanceDisks(self, inst)
4782

    
4783

    
4784
class LURecreateInstanceDisks(LogicalUnit):
4785
  """Recreate an instance's missing disks.
4786

4787
  """
4788
  HPATH = "instance-recreate-disks"
4789
  HTYPE = constants.HTYPE_INSTANCE
4790
  _OP_PARAMS = [
4791
    _PInstanceName,
4792
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
4793
    ]
4794
  REQ_BGL = False
4795

    
4796
  def ExpandNames(self):
4797
    self._ExpandAndLockInstance()
4798

    
4799
  def BuildHooksEnv(self):
4800
    """Build hooks env.
4801

4802
    This runs on master, primary and secondary nodes of the instance.
4803

4804
    """
4805
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4806
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4807
    return env, nl, nl
4808

    
4809
  def CheckPrereq(self):
4810
    """Check prerequisites.
4811

4812
    This checks that the instance is in the cluster and is not running.
4813

4814
    """
4815
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4816
    assert instance is not None, \
4817
      "Cannot retrieve locked instance %s" % self.op.instance_name
4818
    _CheckNodeOnline(self, instance.primary_node)
4819

    
4820
    if instance.disk_template == constants.DT_DISKLESS:
4821
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4822
                                 self.op.instance_name, errors.ECODE_INVAL)
4823
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4824

    
4825
    if not self.op.disks:
4826
      self.op.disks = range(len(instance.disks))
4827
    else:
4828
      for idx in self.op.disks:
4829
        if idx >= len(instance.disks):
4830
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4831
                                     errors.ECODE_INVAL)
4832

    
4833
    self.instance = instance
4834

    
4835
  def Exec(self, feedback_fn):
4836
    """Recreate the disks.
4837

4838
    """
4839
    to_skip = []
4840
    for idx, _ in enumerate(self.instance.disks):
4841
      if idx not in self.op.disks: # disk idx has not been passed in
4842
        to_skip.append(idx)
4843
        continue
4844

    
4845
    _CreateDisks(self, self.instance, to_skip=to_skip)
4846

    
4847

    
4848
class LURenameInstance(LogicalUnit):
4849
  """Rename an instance.
4850

4851
  """
4852
  HPATH = "instance-rename"
4853
  HTYPE = constants.HTYPE_INSTANCE
4854
  _OP_PARAMS = [
4855
    _PInstanceName,
4856
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
4857
    ("ip_check", False, ht.TBool),
4858
    ("name_check", True, ht.TBool),
4859
    ]
4860

    
4861
  def CheckArguments(self):
4862
    """Check arguments.
4863

4864
    """
4865
    if self.op.ip_check and not self.op.name_check:
4866
      # TODO: make the ip check more flexible and not depend on the name check
4867
      raise errors.OpPrereqError("Cannot do ip check without a name check",
4868
                                 errors.ECODE_INVAL)
4869

    
4870
  def BuildHooksEnv(self):
4871
    """Build hooks env.
4872

4873
    This runs on master, primary and secondary nodes of the instance.
4874

4875
    """
4876
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4877
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4878
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4879
    return env, nl, nl
4880

    
4881
  def CheckPrereq(self):
4882
    """Check prerequisites.
4883

4884
    This checks that the instance is in the cluster and is not running.
4885

4886
    """
4887
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4888
                                                self.op.instance_name)
4889
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4890
    assert instance is not None
4891
    _CheckNodeOnline(self, instance.primary_node)
4892
    _CheckInstanceDown(self, instance, "cannot rename")
4893
    self.instance = instance
4894

    
4895
    new_name = self.op.new_name
4896
    if self.op.name_check:
4897
      hostname = netutils.GetHostname(name=new_name)
4898
      new_name = self.op.new_name = hostname.name
4899
      if (self.op.ip_check and
4900
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
4901
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4902
                                   (hostname.ip, new_name),
4903
                                   errors.ECODE_NOTUNIQUE)
4904

    
4905
    instance_list = self.cfg.GetInstanceList()
4906
    if new_name in instance_list:
4907
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4908
                                 new_name, errors.ECODE_EXISTS)
4909

    
4910
  def Exec(self, feedback_fn):
4911
    """Reinstall the instance.
4912

4913
    """
4914
    inst = self.instance
4915
    old_name = inst.name
4916

    
4917
    if inst.disk_template == constants.DT_FILE:
4918
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4919

    
4920
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4921
    # Change the instance lock. This is definitely safe while we hold the BGL
4922
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4923
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4924

    
4925
    # re-read the instance from the configuration after rename
4926
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4927

    
4928
    if inst.disk_template == constants.DT_FILE:
4929
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4930
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4931
                                                     old_file_storage_dir,
4932
                                                     new_file_storage_dir)
4933
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4934
                   " (but the instance has been renamed in Ganeti)" %
4935
                   (inst.primary_node, old_file_storage_dir,
4936
                    new_file_storage_dir))
4937

    
4938
    _StartInstanceDisks(self, inst, None)
4939
    try:
4940
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4941
                                                 old_name, self.op.debug_level)
4942
      msg = result.fail_msg
4943
      if msg:
4944
        msg = ("Could not run OS rename script for instance %s on node %s"
4945
               " (but the instance has been renamed in Ganeti): %s" %
4946
               (inst.name, inst.primary_node, msg))
4947
        self.proc.LogWarning(msg)
4948
    finally:
4949
      _ShutdownInstanceDisks(self, inst)
4950

    
4951
    return inst.name
4952

    
4953

    
4954
class LURemoveInstance(LogicalUnit):
4955
  """Remove an instance.
4956

4957
  """
4958
  HPATH = "instance-remove"
4959
  HTYPE = constants.HTYPE_INSTANCE
4960
  _OP_PARAMS = [
4961
    _PInstanceName,
4962
    ("ignore_failures", False, ht.TBool),
4963
    _PShutdownTimeout,
4964
    ]
4965
  REQ_BGL = False
4966

    
4967
  def ExpandNames(self):
4968
    self._ExpandAndLockInstance()
4969
    self.needed_locks[locking.LEVEL_NODE] = []
4970
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4971

    
4972
  def DeclareLocks(self, level):
4973
    if level == locking.LEVEL_NODE:
4974
      self._LockInstancesNodes()
4975

    
4976
  def BuildHooksEnv(self):
4977
    """Build hooks env.
4978

4979
    This runs on master, primary and secondary nodes of the instance.
4980

4981
    """
4982
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4983
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4984
    nl = [self.cfg.GetMasterNode()]
4985
    nl_post = list(self.instance.all_nodes) + nl
4986
    return env, nl, nl_post
4987

    
4988
  def CheckPrereq(self):
4989
    """Check prerequisites.
4990

4991
    This checks that the instance is in the cluster.
4992

4993
    """
4994
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4995
    assert self.instance is not None, \
4996
      "Cannot retrieve locked instance %s" % self.op.instance_name
4997

    
4998
  def Exec(self, feedback_fn):
4999
    """Remove the instance.
5000

5001
    """
5002
    instance = self.instance
5003
    logging.info("Shutting down instance %s on node %s",
5004
                 instance.name, instance.primary_node)
5005

    
5006
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5007
                                             self.op.shutdown_timeout)
5008
    msg = result.fail_msg
5009
    if msg:
5010
      if self.op.ignore_failures:
5011
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5012
      else:
5013
        raise errors.OpExecError("Could not shutdown instance %s on"
5014
                                 " node %s: %s" %
5015
                                 (instance.name, instance.primary_node, msg))
5016

    
5017
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5018

    
5019

    
5020
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5021
  """Utility function to remove an instance.
5022

5023
  """
5024
  logging.info("Removing block devices for instance %s", instance.name)
5025

    
5026
  if not _RemoveDisks(lu, instance):
5027
    if not ignore_failures:
5028
      raise errors.OpExecError("Can't remove instance's disks")
5029
    feedback_fn("Warning: can't remove instance's disks")
5030

    
5031
  logging.info("Removing instance %s out of cluster config", instance.name)
5032

    
5033
  lu.cfg.RemoveInstance(instance.name)
5034

    
5035
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5036
    "Instance lock removal conflict"
5037

    
5038
  # Remove lock for the instance
5039
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5040

    
5041

    
5042
class LUQueryInstances(NoHooksLU):
5043
  """Logical unit for querying instances.
5044

5045
  """
5046
  # pylint: disable-msg=W0142
5047
  _OP_PARAMS = [
5048
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
5049
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
5050
    ("use_locking", False, ht.TBool),
5051
    ]
5052
  REQ_BGL = False
5053
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5054
                    "serial_no", "ctime", "mtime", "uuid"]
5055
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5056
                                    "admin_state",
5057
                                    "disk_template", "ip", "mac", "bridge",
5058
                                    "nic_mode", "nic_link",
5059
                                    "sda_size", "sdb_size", "vcpus", "tags",
5060
                                    "network_port", "beparams",
5061
                                    r"(disk)\.(size)/([0-9]+)",
5062
                                    r"(disk)\.(sizes)", "disk_usage",
5063
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5064
                                    r"(nic)\.(bridge)/([0-9]+)",
5065
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5066
                                    r"(disk|nic)\.(count)",
5067
                                    "hvparams", "custom_hvparams",
5068
                                    "custom_beparams", "custom_nicparams",
5069
                                    ] + _SIMPLE_FIELDS +
5070
                                  ["hv/%s" % name
5071
                                   for name in constants.HVS_PARAMETERS
5072
                                   if name not in constants.HVC_GLOBALS] +
5073
                                  ["be/%s" % name
5074
                                   for name in constants.BES_PARAMETERS])
5075
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5076
                                   "oper_ram",
5077
                                   "oper_vcpus",
5078
                                   "status")
5079

    
5080

    
5081
  def CheckArguments(self):
5082
    _CheckOutputFields(static=self._FIELDS_STATIC,
5083
                       dynamic=self._FIELDS_DYNAMIC,
5084
                       selected=self.op.output_fields)
5085

    
5086
  def ExpandNames(self):
5087
    self.needed_locks = {}
5088
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5089
    self.share_locks[locking.LEVEL_NODE] = 1
5090

    
5091
    if self.op.names:
5092
      self.wanted = _GetWantedInstances(self, self.op.names)
5093
    else:
5094
      self.wanted = locking.ALL_SET
5095

    
5096
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5097
    self.do_locking = self.do_node_query and self.op.use_locking
5098
    if self.do_locking:
5099
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5100
      self.needed_locks[locking.LEVEL_NODE] = []
5101
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5102

    
5103
  def DeclareLocks(self, level):
5104
    if level == locking.LEVEL_NODE and self.do_locking:
5105
      self._LockInstancesNodes()
5106

    
5107
  def Exec(self, feedback_fn):
5108
    """Computes the list of nodes and their attributes.
5109

5110
    """
5111
    # pylint: disable-msg=R0912
5112
    # way too many branches here
5113
    all_info = self.cfg.GetAllInstancesInfo()
5114
    if self.wanted == locking.ALL_SET:
5115
      # caller didn't specify instance names, so ordering is not important
5116
      if self.do_locking:
5117
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5118
      else:
5119
        instance_names = all_info.keys()
5120
      instance_names = utils.NiceSort(instance_names)
5121
    else:
5122
      # caller did specify names, so we must keep the ordering
5123
      if self.do_locking:
5124
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5125
      else:
5126
        tgt_set = all_info.keys()
5127
      missing = set(self.wanted).difference(tgt_set)
5128
      if missing:
5129
        raise errors.OpExecError("Some instances were removed before"
5130
                                 " retrieving their data: %s" % missing)
5131
      instance_names = self.wanted
5132

    
5133
    instance_list = [all_info[iname] for iname in instance_names]
5134

    
5135
    # begin data gathering
5136

    
5137
    nodes = frozenset([inst.primary_node for inst in instance_list])
5138
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5139

    
5140
    bad_nodes = []
5141
    off_nodes = []
5142
    if self.do_node_query:
5143
      live_data = {}
5144
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5145
      for name in nodes:
5146
        result = node_data[name]
5147
        if result.offline:
5148
          # offline nodes will be in both lists
5149
          off_nodes.append(name)
5150
        if result.fail_msg:
5151
          bad_nodes.append(name)
5152
        else:
5153
          if result.payload:
5154
            live_data.update(result.payload)
5155
          # else no instance is alive
5156
    else:
5157
      live_data = dict([(name, {}) for name in instance_names])
5158

    
5159
    # end data gathering
5160

    
5161
    HVPREFIX = "hv/"
5162
    BEPREFIX = "be/"
5163
    output = []
5164
    cluster = self.cfg.GetClusterInfo()
5165
    for instance in instance_list:
5166
      iout = []
5167
      i_hv = cluster.FillHV(instance, skip_globals=True)
5168
      i_be = cluster.FillBE(instance)
5169
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5170
      for field in self.op.output_fields:
5171
        st_match = self._FIELDS_STATIC.Matches(field)
5172
        if field in self._SIMPLE_FIELDS:
5173
          val = getattr(instance, field)
5174
        elif field == "pnode":
5175
          val = instance.primary_node
5176
        elif field == "snodes":
5177
          val = list(instance.secondary_nodes)
5178
        elif field == "admin_state":
5179
          val = instance.admin_up
5180
        elif field == "oper_state":
5181
          if instance.primary_node in bad_nodes:
5182
            val = None
5183
          else:
5184
            val = bool(live_data.get(instance.name))
5185
        elif field == "status":
5186
          if instance.primary_node in off_nodes:
5187
            val = "ERROR_nodeoffline"
5188
          elif instance.primary_node in bad_nodes:
5189
            val = "ERROR_nodedown"
5190
          else:
5191
            running = bool(live_data.get(instance.name))
5192
            if running:
5193
              if instance.admin_up:
5194
                val = "running"
5195
              else:
5196
                val = "ERROR_up"
5197
            else:
5198
              if instance.admin_up:
5199
                val = "ERROR_down"
5200
              else:
5201
                val = "ADMIN_down"
5202
        elif field == "oper_ram":
5203
          if instance.primary_node in bad_nodes:
5204
            val = None
5205
          elif instance.name in live_data:
5206
            val = live_data[instance.name].get("memory", "?")
5207
          else:
5208
            val = "-"
5209
        elif field == "oper_vcpus":
5210
          if instance.primary_node in bad_nodes:
5211
            val = None
5212
          elif instance.name in live_data:
5213
            val = live_data[instance.name].get("vcpus", "?")
5214
          else:
5215
            val = "-"
5216
        elif field == "vcpus":
5217
          val = i_be[constants.BE_VCPUS]
5218
        elif field == "disk_template":
5219
          val = instance.disk_template
5220
        elif field == "ip":
5221
          if instance.nics:
5222
            val = instance.nics[0].ip
5223
          else:
5224
            val = None
5225
        elif field == "nic_mode":
5226
          if instance.nics:
5227
            val = i_nicp[0][constants.NIC_MODE]
5228
          else:
5229
            val = None
5230
        elif field == "nic_link":
5231
          if instance.nics:
5232
            val = i_nicp[0][constants.NIC_LINK]
5233
          else:
5234
            val = None
5235
        elif field == "bridge":
5236
          if (instance.nics and
5237
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5238
            val = i_nicp[0][constants.NIC_LINK]
5239
          else:
5240
            val = None
5241
        elif field == "mac":
5242
          if instance.nics:
5243
            val = instance.nics[0].mac
5244
          else:
5245
            val = None
5246
        elif field == "custom_nicparams":
5247
          val = [nic.nicparams for nic in instance.nics]
5248
        elif field == "sda_size" or field == "sdb_size":
5249
          idx = ord(field[2]) - ord('a')
5250
          try:
5251
            val = instance.FindDisk(idx).size
5252
          except errors.OpPrereqError:
5253
            val = None
5254
        elif field == "disk_usage": # total disk usage per node
5255
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5256
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5257
        elif field == "tags":
5258
          val = list(instance.GetTags())
5259
        elif field == "custom_hvparams":
5260
          val = instance.hvparams # not filled!
5261
        elif field == "hvparams":
5262
          val = i_hv
5263
        elif (field.startswith(HVPREFIX) and
5264
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5265
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5266
          val = i_hv.get(field[len(HVPREFIX):], None)
5267
        elif field == "custom_beparams":
5268
          val = instance.beparams
5269
        elif field == "beparams":
5270
          val = i_be
5271
        elif (field.startswith(BEPREFIX) and
5272
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5273
          val = i_be.get(field[len(BEPREFIX):], None)
5274
        elif st_match and st_match.groups():
5275
          # matches a variable list
5276
          st_groups = st_match.groups()
5277
          if st_groups and st_groups[0] == "disk":
5278
            if st_groups[1] == "count":
5279
              val = len(instance.disks)
5280
            elif st_groups[1] == "sizes":
5281
              val = [disk.size for disk in instance.disks]
5282
            elif st_groups[1] == "size":
5283
              try:
5284
                val = instance.FindDisk(st_groups[2]).size
5285
              except errors.OpPrereqError:
5286
                val = None
5287
            else:
5288
              assert False, "Unhandled disk parameter"
5289
          elif st_groups[0] == "nic":
5290
            if st_groups[1] == "count":
5291
              val = len(instance.nics)
5292
            elif st_groups[1] == "macs":
5293
              val = [nic.mac for nic in instance.nics]
5294
            elif st_groups[1] == "ips":
5295
              val = [nic.ip for nic in instance.nics]
5296
            elif st_groups[1] == "modes":
5297
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5298
            elif st_groups[1] == "links":
5299
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5300
            elif st_groups[1] == "bridges":
5301
              val = []
5302
              for nicp in i_nicp:
5303
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5304
                  val.append(nicp[constants.NIC_LINK])
5305
                else:
5306
                  val.append(None)
5307
            else:
5308
              # index-based item
5309
              nic_idx = int(st_groups[2])
5310
              if nic_idx >= len(instance.nics):
5311
                val = None
5312
              else:
5313
                if st_groups[1] == "mac":
5314
                  val = instance.nics[nic_idx].mac
5315
                elif st_groups[1] == "ip":
5316
                  val = instance.nics[nic_idx].ip
5317
                elif st_groups[1] == "mode":
5318
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5319
                elif st_groups[1] == "link":
5320
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5321
                elif st_groups[1] == "bridge":
5322
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5323
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5324
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5325
                  else:
5326
                    val = None
5327
                else:
5328
                  assert False, "Unhandled NIC parameter"
5329
          else:
5330
            assert False, ("Declared but unhandled variable parameter '%s'" %
5331
                           field)
5332
        else:
5333
          assert False, "Declared but unhandled parameter '%s'" % field
5334
        iout.append(val)
5335
      output.append(iout)
5336

    
5337
    return output
5338

    
5339

    
5340
class LUFailoverInstance(LogicalUnit):
5341
  """Failover an instance.
5342

5343
  """
5344
  HPATH = "instance-failover"
5345
  HTYPE = constants.HTYPE_INSTANCE
5346
  _OP_PARAMS = [
5347
    _PInstanceName,
5348
    ("ignore_consistency", False, ht.TBool),
5349
    _PShutdownTimeout,
5350
    ]
5351
  REQ_BGL = False
5352

    
5353
  def ExpandNames(self):
5354
    self._ExpandAndLockInstance()
5355
    self.needed_locks[locking.LEVEL_NODE] = []
5356
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5357

    
5358
  def DeclareLocks(self, level):
5359
    if level == locking.LEVEL_NODE:
5360
      self._LockInstancesNodes()
5361

    
5362
  def BuildHooksEnv(self):
5363
    """Build hooks env.
5364

5365
    This runs on master, primary and secondary nodes of the instance.
5366

5367
    """
5368
    instance = self.instance
5369
    source_node = instance.primary_node
5370
    target_node = instance.secondary_nodes[0]
5371
    env = {
5372
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5373
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5374
      "OLD_PRIMARY": source_node,
5375
      "OLD_SECONDARY": target_node,
5376
      "NEW_PRIMARY": target_node,
5377
      "NEW_SECONDARY": source_node,
5378
      }
5379
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5380
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5381
    nl_post = list(nl)
5382
    nl_post.append(source_node)
5383
    return env, nl, nl_post
5384

    
5385
  def CheckPrereq(self):
5386
    """Check prerequisites.
5387

5388
    This checks that the instance is in the cluster.
5389

5390
    """
5391
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5392
    assert self.instance is not None, \
5393
      "Cannot retrieve locked instance %s" % self.op.instance_name
5394

    
5395
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5396
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5397
      raise errors.OpPrereqError("Instance's disk layout is not"
5398
                                 " network mirrored, cannot failover.",
5399
                                 errors.ECODE_STATE)
5400

    
5401
    secondary_nodes = instance.secondary_nodes
5402
    if not secondary_nodes:
5403
      raise errors.ProgrammerError("no secondary node but using "
5404
                                   "a mirrored disk template")
5405

    
5406
    target_node = secondary_nodes[0]
5407
    _CheckNodeOnline(self, target_node)
5408
    _CheckNodeNotDrained(self, target_node)
5409
    if instance.admin_up:
5410
      # check memory requirements on the secondary node
5411
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5412
                           instance.name, bep[constants.BE_MEMORY],
5413
                           instance.hypervisor)
5414
    else:
5415
      self.LogInfo("Not checking memory on the secondary node as"
5416
                   " instance will not be started")
5417

    
5418
    # check bridge existance
5419
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5420

    
5421
  def Exec(self, feedback_fn):
5422
    """Failover an instance.
5423

5424
    The failover is done by shutting it down on its present node and
5425
    starting it on the secondary.
5426

5427
    """
5428
    instance = self.instance
5429
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5430

    
5431
    source_node = instance.primary_node
5432
    target_node = instance.secondary_nodes[0]
5433

    
5434
    if instance.admin_up:
5435
      feedback_fn("* checking disk consistency between source and target")
5436
      for dev in instance.disks:
5437
        # for drbd, these are drbd over lvm
5438
        if not _CheckDiskConsistency(self, dev, target_node, False):
5439
          if not self.op.ignore_consistency:
5440
            raise errors.OpExecError("Disk %s is degraded on target node,"
5441
                                     " aborting failover." % dev.iv_name)
5442
    else:
5443
      feedback_fn("* not checking disk consistency as instance is not running")
5444

    
5445
    feedback_fn("* shutting down instance on source node")
5446
    logging.info("Shutting down instance %s on node %s",
5447
                 instance.name, source_node)
5448

    
5449
    result = self.rpc.call_instance_shutdown(source_node, instance,
5450
                                             self.op.shutdown_timeout)
5451
    msg = result.fail_msg
5452
    if msg:
5453
      if self.op.ignore_consistency or primary_node.offline:
5454
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5455
                             " Proceeding anyway. Please make sure node"
5456
                             " %s is down. Error details: %s",
5457
                             instance.name, source_node, source_node, msg)
5458
      else:
5459
        raise errors.OpExecError("Could not shutdown instance %s on"
5460
                                 " node %s: %s" %
5461
                                 (instance.name, source_node, msg))
5462

    
5463
    feedback_fn("* deactivating the instance's disks on source node")
5464
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5465
      raise errors.OpExecError("Can't shut down the instance's disks.")
5466

    
5467
    instance.primary_node = target_node
5468
    # distribute new instance config to the other nodes
5469
    self.cfg.Update(instance, feedback_fn)
5470

    
5471
    # Only start the instance if it's marked as up
5472
    if instance.admin_up:
5473
      feedback_fn("* activating the instance's disks on target node")
5474
      logging.info("Starting instance %s on node %s",
5475
                   instance.name, target_node)
5476

    
5477
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5478
                                           ignore_secondaries=True)
5479
      if not disks_ok:
5480
        _ShutdownInstanceDisks(self, instance)
5481
        raise errors.OpExecError("Can't activate the instance's disks")
5482

    
5483
      feedback_fn("* starting the instance on the target node")
5484
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5485
      msg = result.fail_msg
5486
      if msg:
5487
        _ShutdownInstanceDisks(self, instance)
5488
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5489
                                 (instance.name, target_node, msg))
5490

    
5491

    
5492
class LUMigrateInstance(LogicalUnit):
5493
  """Migrate an instance.
5494

5495
  This is migration without shutting down, compared to the failover,
5496
  which is done with shutdown.
5497

5498
  """
5499
  HPATH = "instance-migrate"
5500
  HTYPE = constants.HTYPE_INSTANCE
5501
  _OP_PARAMS = [
5502
    _PInstanceName,
5503
    _PMigrationMode,
5504
    _PMigrationLive,
5505
    ("cleanup", False, ht.TBool),
5506
    ]
5507

    
5508
  REQ_BGL = False
5509

    
5510
  def ExpandNames(self):
5511
    self._ExpandAndLockInstance()
5512

    
5513
    self.needed_locks[locking.LEVEL_NODE] = []
5514
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5515

    
5516
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5517
                                       self.op.cleanup)
5518
    self.tasklets = [self._migrater]
5519

    
5520
  def DeclareLocks(self, level):
5521
    if level == locking.LEVEL_NODE:
5522
      self._LockInstancesNodes()
5523

    
5524
  def BuildHooksEnv(self):
5525
    """Build hooks env.
5526

5527
    This runs on master, primary and secondary nodes of the instance.
5528

5529
    """
5530
    instance = self._migrater.instance
5531
    source_node = instance.primary_node
5532
    target_node = instance.secondary_nodes[0]
5533
    env = _BuildInstanceHookEnvByObject(self, instance)
5534
    env["MIGRATE_LIVE"] = self._migrater.live
5535
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5536
    env.update({
5537
        "OLD_PRIMARY": source_node,
5538
        "OLD_SECONDARY": target_node,
5539
        "NEW_PRIMARY": target_node,
5540
        "NEW_SECONDARY": source_node,
5541
        })
5542
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5543
    nl_post = list(nl)
5544
    nl_post.append(source_node)
5545
    return env, nl, nl_post
5546

    
5547

    
5548
class LUMoveInstance(LogicalUnit):
5549
  """Move an instance by data-copying.
5550

5551
  """
5552
  HPATH = "instance-move"
5553
  HTYPE = constants.HTYPE_INSTANCE
5554
  _OP_PARAMS = [
5555
    _PInstanceName,
5556
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5557
    _PShutdownTimeout,
5558
    ]
5559
  REQ_BGL = False
5560

    
5561
  def ExpandNames(self):
5562
    self._ExpandAndLockInstance()
5563
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5564
    self.op.target_node = target_node
5565
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5566
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5567

    
5568
  def DeclareLocks(self, level):
5569
    if level == locking.LEVEL_NODE:
5570
      self._LockInstancesNodes(primary_only=True)
5571

    
5572
  def BuildHooksEnv(self):
5573
    """Build hooks env.
5574

5575
    This runs on master, primary and secondary nodes of the instance.
5576

5577
    """
5578
    env = {
5579
      "TARGET_NODE": self.op.target_node,
5580
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5581
      }
5582
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5583
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5584
                                       self.op.target_node]
5585
    return env, nl, nl
5586

    
5587
  def CheckPrereq(self):
5588
    """Check prerequisites.
5589

5590
    This checks that the instance is in the cluster.
5591

5592
    """
5593
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5594
    assert self.instance is not None, \
5595
      "Cannot retrieve locked instance %s" % self.op.instance_name
5596

    
5597
    node = self.cfg.GetNodeInfo(self.op.target_node)
5598
    assert node is not None, \
5599
      "Cannot retrieve locked node %s" % self.op.target_node
5600

    
5601
    self.target_node = target_node = node.name
5602

    
5603
    if target_node == instance.primary_node:
5604
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5605
                                 (instance.name, target_node),
5606
                                 errors.ECODE_STATE)
5607

    
5608
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5609

    
5610
    for idx, dsk in enumerate(instance.disks):
5611
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5612
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5613
                                   " cannot copy" % idx, errors.ECODE_STATE)
5614

    
5615
    _CheckNodeOnline(self, target_node)
5616
    _CheckNodeNotDrained(self, target_node)
5617

    
5618
    if instance.admin_up:
5619
      # check memory requirements on the secondary node
5620
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5621
                           instance.name, bep[constants.BE_MEMORY],
5622
                           instance.hypervisor)
5623
    else:
5624
      self.LogInfo("Not checking memory on the secondary node as"
5625
                   " instance will not be started")
5626

    
5627
    # check bridge existance
5628
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5629

    
5630
  def Exec(self, feedback_fn):
5631
    """Move an instance.
5632

5633
    The move is done by shutting it down on its present node, copying
5634
    the data over (slow) and starting it on the new node.
5635

5636
    """
5637
    instance = self.instance
5638

    
5639
    source_node = instance.primary_node
5640
    target_node = self.target_node
5641

    
5642
    self.LogInfo("Shutting down instance %s on source node %s",
5643
                 instance.name, source_node)
5644

    
5645
    result = self.rpc.call_instance_shutdown(source_node, instance,
5646
                                             self.op.shutdown_timeout)
5647
    msg = result.fail_msg
5648
    if msg:
5649
      if self.op.ignore_consistency:
5650
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5651
                             " Proceeding anyway. Please make sure node"
5652
                             " %s is down. Error details: %s",
5653
                             instance.name, source_node, source_node, msg)
5654
      else:
5655
        raise errors.OpExecError("Could not shutdown instance %s on"
5656
                                 " node %s: %s" %
5657
                                 (instance.name, source_node, msg))
5658

    
5659
    # create the target disks
5660
    try:
5661
      _CreateDisks(self, instance, target_node=target_node)
5662
    except errors.OpExecError:
5663
      self.LogWarning("Device creation failed, reverting...")
5664
      try:
5665
        _RemoveDisks(self, instance, target_node=target_node)
5666
      finally:
5667
        self.cfg.ReleaseDRBDMinors(instance.name)
5668
        raise
5669

    
5670
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5671

    
5672
    errs = []
5673
    # activate, get path, copy the data over
5674
    for idx, disk in enumerate(instance.disks):
5675
      self.LogInfo("Copying data for disk %d", idx)
5676
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5677
                                               instance.name, True)
5678
      if result.fail_msg:
5679
        self.LogWarning("Can't assemble newly created disk %d: %s",
5680
                        idx, result.fail_msg)
5681
        errs.append(result.fail_msg)
5682
        break
5683
      dev_path = result.payload
5684
      result = self.rpc.call_blockdev_export(source_node, disk,
5685
                                             target_node, dev_path,
5686
                                             cluster_name)
5687
      if result.fail_msg:
5688
        self.LogWarning("Can't copy data over for disk %d: %s",
5689
                        idx, result.fail_msg)
5690
        errs.append(result.fail_msg)
5691
        break
5692

    
5693
    if errs:
5694
      self.LogWarning("Some disks failed to copy, aborting")
5695
      try:
5696
        _RemoveDisks(self, instance, target_node=target_node)
5697
      finally:
5698
        self.cfg.ReleaseDRBDMinors(instance.name)
5699
        raise errors.OpExecError("Errors during disk copy: %s" %
5700
                                 (",".join(errs),))
5701

    
5702
    instance.primary_node = target_node
5703
    self.cfg.Update(instance, feedback_fn)
5704

    
5705
    self.LogInfo("Removing the disks on the original node")
5706
    _RemoveDisks(self, instance, target_node=source_node)
5707

    
5708
    # Only start the instance if it's marked as up
5709
    if instance.admin_up:
5710
      self.LogInfo("Starting instance %s on node %s",
5711
                   instance.name, target_node)
5712

    
5713
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5714
                                           ignore_secondaries=True)
5715
      if not disks_ok:
5716
        _ShutdownInstanceDisks(self, instance)
5717
        raise errors.OpExecError("Can't activate the instance's disks")
5718

    
5719
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5720
      msg = result.fail_msg
5721
      if msg:
5722
        _ShutdownInstanceDisks(self, instance)
5723
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5724
                                 (instance.name, target_node, msg))
5725

    
5726

    
5727
class LUMigrateNode(LogicalUnit):
5728
  """Migrate all instances from a node.
5729

5730
  """
5731
  HPATH = "node-migrate"
5732
  HTYPE = constants.HTYPE_NODE
5733
  _OP_PARAMS = [
5734
    _PNodeName,
5735
    _PMigrationMode,
5736
    _PMigrationLive,
5737
    ]
5738
  REQ_BGL = False
5739

    
5740
  def ExpandNames(self):
5741
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5742

    
5743
    self.needed_locks = {
5744
      locking.LEVEL_NODE: [self.op.node_name],
5745
      }
5746

    
5747
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5748

    
5749
    # Create tasklets for migrating instances for all instances on this node
5750
    names = []
5751
    tasklets = []
5752

    
5753
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5754
      logging.debug("Migrating instance %s", inst.name)
5755
      names.append(inst.name)
5756

    
5757
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5758

    
5759
    self.tasklets = tasklets
5760

    
5761
    # Declare instance locks
5762
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5763

    
5764
  def DeclareLocks(self, level):
5765
    if level == locking.LEVEL_NODE:
5766
      self._LockInstancesNodes()
5767

    
5768
  def BuildHooksEnv(self):
5769
    """Build hooks env.
5770

5771
    This runs on the master, the primary and all the secondaries.
5772

5773
    """
5774
    env = {
5775
      "NODE_NAME": self.op.node_name,
5776
      }
5777

    
5778
    nl = [self.cfg.GetMasterNode()]
5779

    
5780
    return (env, nl, nl)
5781

    
5782

    
5783
class TLMigrateInstance(Tasklet):
5784
  """Tasklet class for instance migration.
5785

5786
  @type live: boolean
5787
  @ivar live: whether the migration will be done live or non-live;
5788
      this variable is initalized only after CheckPrereq has run
5789

5790
  """
5791
  def __init__(self, lu, instance_name, cleanup):
5792
    """Initializes this class.
5793

5794
    """
5795
    Tasklet.__init__(self, lu)
5796

    
5797
    # Parameters
5798
    self.instance_name = instance_name
5799
    self.cleanup = cleanup
5800
    self.live = False # will be overridden later
5801

    
5802
  def CheckPrereq(self):
5803
    """Check prerequisites.
5804

5805
    This checks that the instance is in the cluster.
5806

5807
    """
5808
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5809
    instance = self.cfg.GetInstanceInfo(instance_name)
5810
    assert instance is not None
5811

    
5812
    if instance.disk_template != constants.DT_DRBD8:
5813
      raise errors.OpPrereqError("Instance's disk layout is not"
5814
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5815

    
5816
    secondary_nodes = instance.secondary_nodes
5817
    if not secondary_nodes:
5818
      raise errors.ConfigurationError("No secondary node but using"
5819
                                      " drbd8 disk template")
5820

    
5821
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5822

    
5823
    target_node = secondary_nodes[0]
5824
    # check memory requirements on the secondary node
5825
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5826
                         instance.name, i_be[constants.BE_MEMORY],
5827
                         instance.hypervisor)
5828

    
5829
    # check bridge existance
5830
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5831

    
5832
    if not self.cleanup:
5833
      _CheckNodeNotDrained(self.lu, target_node)
5834
      result = self.rpc.call_instance_migratable(instance.primary_node,
5835
                                                 instance)
5836
      result.Raise("Can't migrate, please use failover",
5837
                   prereq=True, ecode=errors.ECODE_STATE)
5838

    
5839
    self.instance = instance
5840

    
5841
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5842
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5843
                                 " parameters are accepted",
5844
                                 errors.ECODE_INVAL)
5845
    if self.lu.op.live is not None:
5846
      if self.lu.op.live:
5847
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5848
      else:
5849
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
5850
      # reset the 'live' parameter to None so that repeated
5851
      # invocations of CheckPrereq do not raise an exception
5852
      self.lu.op.live = None
5853
    elif self.lu.op.mode is None:
5854
      # read the default value from the hypervisor
5855
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5856
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5857

    
5858
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5859

    
5860
  def _WaitUntilSync(self):
5861
    """Poll with custom rpc for disk sync.
5862

5863
    This uses our own step-based rpc call.
5864

5865
    """
5866
    self.feedback_fn("* wait until resync is done")
5867
    all_done = False
5868
    while not all_done:
5869
      all_done = True
5870
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5871
                                            self.nodes_ip,
5872
                                            self.instance.disks)
5873
      min_percent = 100
5874
      for node, nres in result.items():
5875
        nres.Raise("Cannot resync disks on node %s" % node)
5876
        node_done, node_percent = nres.payload
5877
        all_done = all_done and node_done
5878
        if node_percent is not None:
5879
          min_percent = min(min_percent, node_percent)
5880
      if not all_done:
5881
        if min_percent < 100:
5882
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5883
        time.sleep(2)
5884

    
5885
  def _EnsureSecondary(self, node):
5886
    """Demote a node to secondary.
5887

5888
    """
5889
    self.feedback_fn("* switching node %s to secondary mode" % node)
5890

    
5891
    for dev in self.instance.disks:
5892
      self.cfg.SetDiskID(dev, node)
5893

    
5894
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5895
                                          self.instance.disks)
5896
    result.Raise("Cannot change disk to secondary on node %s" % node)
5897

    
5898
  def _GoStandalone(self):
5899
    """Disconnect from the network.
5900

5901
    """
5902
    self.feedback_fn("* changing into standalone mode")
5903
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5904
                                               self.instance.disks)
5905
    for node, nres in result.items():
5906
      nres.Raise("Cannot disconnect disks node %s" % node)
5907

    
5908
  def _GoReconnect(self, multimaster):
5909
    """Reconnect to the network.
5910

5911
    """
5912
    if multimaster:
5913
      msg = "dual-master"
5914
    else:
5915
      msg = "single-master"
5916
    self.feedback_fn("* changing disks into %s mode" % msg)
5917
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5918
                                           self.instance.disks,
5919
                                           self.instance.name, multimaster)
5920
    for node, nres in result.items():
5921
      nres.Raise("Cannot change disks config on node %s" % node)
5922

    
5923
  def _ExecCleanup(self):
5924
    """Try to cleanup after a failed migration.
5925

5926
    The cleanup is done by:
5927
      - check that the instance is running only on one node
5928
        (and update the config if needed)
5929
      - change disks on its secondary node to secondary
5930
      - wait until disks are fully synchronized
5931
      - disconnect from the network
5932
      - change disks into single-master mode
5933
      - wait again until disks are fully synchronized
5934

5935
    """
5936
    instance = self.instance
5937
    target_node = self.target_node
5938
    source_node = self.source_node
5939

    
5940
    # check running on only one node
5941
    self.feedback_fn("* checking where the instance actually runs"
5942
                     " (if this hangs, the hypervisor might be in"
5943
                     " a bad state)")
5944
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5945
    for node, result in ins_l.items():
5946
      result.Raise("Can't contact node %s" % node)
5947

    
5948
    runningon_source = instance.name in ins_l[source_node].payload
5949
    runningon_target = instance.name in ins_l[target_node].payload
5950

    
5951
    if runningon_source and runningon_target:
5952
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5953
                               " or the hypervisor is confused. You will have"
5954
                               " to ensure manually that it runs only on one"
5955
                               " and restart this operation.")
5956

    
5957
    if not (runningon_source or runningon_target):
5958
      raise errors.OpExecError("Instance does not seem to be running at all."
5959
                               " In this case, it's safer to repair by"
5960
                               " running 'gnt-instance stop' to ensure disk"
5961
                               " shutdown, and then restarting it.")
5962

    
5963
    if runningon_target:
5964
      # the migration has actually succeeded, we need to update the config
5965
      self.feedback_fn("* instance running on secondary node (%s),"
5966
                       " updating config" % target_node)
5967
      instance.primary_node = target_node
5968
      self.cfg.Update(instance, self.feedback_fn)
5969
      demoted_node = source_node
5970
    else:
5971
      self.feedback_fn("* instance confirmed to be running on its"
5972
                       " primary node (%s)" % source_node)
5973
      demoted_node = target_node
5974

    
5975
    self._EnsureSecondary(demoted_node)
5976
    try:
5977
      self._WaitUntilSync()
5978
    except errors.OpExecError:
5979
      # we ignore here errors, since if the device is standalone, it
5980
      # won't be able to sync
5981
      pass
5982
    self._GoStandalone()
5983
    self._GoReconnect(False)
5984
    self._WaitUntilSync()
5985

    
5986
    self.feedback_fn("* done")
5987

    
5988
  def _RevertDiskStatus(self):
5989
    """Try to revert the disk status after a failed migration.
5990

5991
    """
5992
    target_node = self.target_node
5993
    try:
5994
      self._EnsureSecondary(target_node)
5995
      self._GoStandalone()
5996
      self._GoReconnect(False)
5997
      self._WaitUntilSync()
5998
    except errors.OpExecError, err:
5999
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6000
                         " drives: error '%s'\n"
6001
                         "Please look and recover the instance status" %
6002
                         str(err))
6003

    
6004
  def _AbortMigration(self):
6005
    """Call the hypervisor code to abort a started migration.
6006

6007
    """
6008
    instance = self.instance
6009
    target_node = self.target_node
6010
    migration_info = self.migration_info
6011

    
6012
    abort_result = self.rpc.call_finalize_migration(target_node,
6013
                                                    instance,
6014
                                                    migration_info,
6015
                                                    False)
6016
    abort_msg = abort_result.fail_msg
6017
    if abort_msg:
6018
      logging.error("Aborting migration failed on target node %s: %s",
6019
                    target_node, abort_msg)
6020
      # Don't raise an exception here, as we stil have to try to revert the
6021
      # disk status, even if this step failed.
6022

    
6023
  def _ExecMigration(self):
6024
    """Migrate an instance.
6025

6026
    The migrate is done by:
6027
      - change the disks into dual-master mode
6028
      - wait until disks are fully synchronized again
6029
      - migrate the instance
6030
      - change disks on the new secondary node (the old primary) to secondary
6031
      - wait until disks are fully synchronized
6032
      - change disks into single-master mode
6033

6034
    """
6035
    instance = self.instance
6036
    target_node = self.target_node
6037
    source_node = self.source_node
6038

    
6039
    self.feedback_fn("* checking disk consistency between source and target")
6040
    for dev in instance.disks:
6041
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6042
        raise errors.OpExecError("Disk %s is degraded or not fully"
6043
                                 " synchronized on target node,"
6044
                                 " aborting migrate." % dev.iv_name)
6045

    
6046
    # First get the migration information from the remote node
6047
    result = self.rpc.call_migration_info(source_node, instance)
6048
    msg = result.fail_msg
6049
    if msg:
6050
      log_err = ("Failed fetching source migration information from %s: %s" %
6051
                 (source_node, msg))
6052
      logging.error(log_err)
6053
      raise errors.OpExecError(log_err)
6054

    
6055
    self.migration_info = migration_info = result.payload
6056

    
6057
    # Then switch the disks to master/master mode
6058
    self._EnsureSecondary(target_node)
6059
    self._GoStandalone()
6060
    self._GoReconnect(True)
6061
    self._WaitUntilSync()
6062

    
6063
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6064
    result = self.rpc.call_accept_instance(target_node,
6065
                                           instance,
6066
                                           migration_info,
6067
                                           self.nodes_ip[target_node])
6068

    
6069
    msg = result.fail_msg
6070
    if msg:
6071
      logging.error("Instance pre-migration failed, trying to revert"
6072
                    " disk status: %s", msg)
6073
      self.feedback_fn("Pre-migration failed, aborting")
6074
      self._AbortMigration()
6075
      self._RevertDiskStatus()
6076
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6077
                               (instance.name, msg))
6078

    
6079
    self.feedback_fn("* migrating instance to %s" % target_node)
6080
    time.sleep(10)
6081
    result = self.rpc.call_instance_migrate(source_node, instance,
6082
                                            self.nodes_ip[target_node],
6083
                                            self.live)
6084
    msg = result.fail_msg
6085
    if msg:
6086
      logging.error("Instance migration failed, trying to revert"
6087
                    " disk status: %s", msg)
6088
      self.feedback_fn("Migration failed, aborting")
6089
      self._AbortMigration()
6090
      self._RevertDiskStatus()
6091
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6092
                               (instance.name, msg))
6093
    time.sleep(10)
6094

    
6095
    instance.primary_node = target_node
6096
    # distribute new instance config to the other nodes
6097
    self.cfg.Update(instance, self.feedback_fn)
6098

    
6099
    result = self.rpc.call_finalize_migration(target_node,
6100
                                              instance,
6101
                                              migration_info,
6102
                                              True)
6103
    msg = result.fail_msg
6104
    if msg:
6105
      logging.error("Instance migration succeeded, but finalization failed:"
6106
                    " %s", msg)
6107
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6108
                               msg)
6109

    
6110
    self._EnsureSecondary(source_node)
6111
    self._WaitUntilSync()
6112
    self._GoStandalone()
6113
    self._GoReconnect(False)
6114
    self._WaitUntilSync()
6115

    
6116
    self.feedback_fn("* done")
6117

    
6118
  def Exec(self, feedback_fn):
6119
    """Perform the migration.
6120

6121
    """
6122
    feedback_fn("Migrating instance %s" % self.instance.name)
6123

    
6124
    self.feedback_fn = feedback_fn
6125

    
6126
    self.source_node = self.instance.primary_node
6127
    self.target_node = self.instance.secondary_nodes[0]
6128
    self.all_nodes = [self.source_node, self.target_node]
6129
    self.nodes_ip = {
6130
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6131
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6132
      }
6133

    
6134
    if self.cleanup:
6135
      return self._ExecCleanup()
6136
    else:
6137
      return self._ExecMigration()
6138

    
6139

    
6140
def _CreateBlockDev(lu, node, instance, device, force_create,
6141
                    info, force_open):
6142
  """Create a tree of block devices on a given node.
6143

6144
  If this device type has to be created on secondaries, create it and
6145
  all its children.
6146

6147
  If not, just recurse to children keeping the same 'force' value.
6148

6149
  @param lu: the lu on whose behalf we execute
6150
  @param node: the node on which to create the device
6151
  @type instance: L{objects.Instance}
6152
  @param instance: the instance which owns the device
6153
  @type device: L{objects.Disk}
6154
  @param device: the device to create
6155
  @type force_create: boolean
6156
  @param force_create: whether to force creation of this device; this
6157
      will be change to True whenever we find a device which has
6158
      CreateOnSecondary() attribute
6159
  @param info: the extra 'metadata' we should attach to the device
6160
      (this will be represented as a LVM tag)
6161
  @type force_open: boolean
6162
  @param force_open: this parameter will be passes to the
6163
      L{backend.BlockdevCreate} function where it specifies
6164
      whether we run on primary or not, and it affects both
6165
      the child assembly and the device own Open() execution
6166

6167
  """
6168
  if device.CreateOnSecondary():
6169
    force_create = True
6170

    
6171
  if device.children:
6172
    for child in device.children:
6173
      _CreateBlockDev(lu, node, instance, child, force_create,
6174
                      info, force_open)
6175

    
6176
  if not force_create:
6177
    return
6178

    
6179
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6180

    
6181

    
6182
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6183
  """Create a single block device on a given node.
6184

6185
  This will not recurse over children of the device, so they must be
6186
  created in advance.
6187

6188
  @param lu: the lu on whose behalf we execute
6189
  @param node: the node on which to create the device
6190
  @type instance: L{objects.Instance}
6191
  @param instance: the instance which owns the device
6192
  @type device: L{objects.Disk}
6193
  @param device: the device to create
6194
  @param info: the extra 'metadata' we should attach to the device
6195
      (this will be represented as a LVM tag)
6196
  @type force_open: boolean
6197
  @param force_open: this parameter will be passes to the
6198
      L{backend.BlockdevCreate} function where it specifies
6199
      whether we run on primary or not, and it affects both
6200
      the child assembly and the device own Open() execution
6201

6202
  """
6203
  lu.cfg.SetDiskID(device, node)
6204
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6205
                                       instance.name, force_open, info)
6206
  result.Raise("Can't create block device %s on"
6207
               " node %s for instance %s" % (device, node, instance.name))
6208
  if device.physical_id is None:
6209
    device.physical_id = result.payload
6210

    
6211

    
6212
def _GenerateUniqueNames(lu, exts):
6213
  """Generate a suitable LV name.
6214

6215
  This will generate a logical volume name for the given instance.
6216

6217
  """
6218
  results = []
6219
  for val in exts:
6220
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6221
    results.append("%s%s" % (new_id, val))
6222
  return results
6223

    
6224

    
6225
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6226
                         p_minor, s_minor):
6227
  """Generate a drbd8 device complete with its children.
6228

6229
  """
6230
  port = lu.cfg.AllocatePort()
6231
  vgname = lu.cfg.GetVGName()
6232
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6233
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6234
                          logical_id=(vgname, names[0]))
6235
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6236
                          logical_id=(vgname, names[1]))
6237
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6238
                          logical_id=(primary, secondary, port,
6239
                                      p_minor, s_minor,
6240
                                      shared_secret),
6241
                          children=[dev_data, dev_meta],
6242
                          iv_name=iv_name)
6243
  return drbd_dev
6244

    
6245

    
6246
def _GenerateDiskTemplate(lu, template_name,
6247
                          instance_name, primary_node,
6248
                          secondary_nodes, disk_info,
6249
                          file_storage_dir, file_driver,
6250
                          base_index):
6251
  """Generate the entire disk layout for a given template type.
6252

6253
  """
6254
  #TODO: compute space requirements
6255

    
6256
  vgname = lu.cfg.GetVGName()
6257
  disk_count = len(disk_info)
6258
  disks = []
6259
  if template_name == constants.DT_DISKLESS:
6260
    pass
6261
  elif template_name == constants.DT_PLAIN:
6262
    if len(secondary_nodes) != 0:
6263
      raise errors.ProgrammerError("Wrong template configuration")
6264

    
6265
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6266
                                      for i in range(disk_count)])
6267
    for idx, disk in enumerate(disk_info):
6268
      disk_index = idx + base_index
6269
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6270
                              logical_id=(vgname, names[idx]),
6271
                              iv_name="disk/%d" % disk_index,
6272
                              mode=disk["mode"])
6273
      disks.append(disk_dev)
6274
  elif template_name == constants.DT_DRBD8:
6275
    if len(secondary_nodes) != 1:
6276
      raise errors.ProgrammerError("Wrong template configuration")
6277
    remote_node = secondary_nodes[0]
6278
    minors = lu.cfg.AllocateDRBDMinor(
6279
      [primary_node, remote_node] * len(disk_info), instance_name)
6280

    
6281
    names = []
6282
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6283
                                               for i in range(disk_count)]):
6284
      names.append(lv_prefix + "_data")
6285
      names.append(lv_prefix + "_meta")
6286
    for idx, disk in enumerate(disk_info):
6287
      disk_index = idx + base_index
6288
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6289
                                      disk["size"], names[idx*2:idx*2+2],
6290
                                      "disk/%d" % disk_index,
6291
                                      minors[idx*2], minors[idx*2+1])
6292
      disk_dev.mode = disk["mode"]
6293
      disks.append(disk_dev)
6294
  elif template_name == constants.DT_FILE:
6295
    if len(secondary_nodes) != 0:
6296
      raise errors.ProgrammerError("Wrong template configuration")
6297

    
6298
    _RequireFileStorage()
6299

    
6300
    for idx, disk in enumerate(disk_info):
6301
      disk_index = idx + base_index
6302
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6303
                              iv_name="disk/%d" % disk_index,
6304
                              logical_id=(file_driver,
6305
                                          "%s/disk%d" % (file_storage_dir,
6306
                                                         disk_index)),
6307
                              mode=disk["mode"])
6308
      disks.append(disk_dev)
6309
  else:
6310
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6311
  return disks
6312

    
6313

    
6314
def _GetInstanceInfoText(instance):
6315
  """Compute that text that should be added to the disk's metadata.
6316

6317
  """
6318
  return "originstname+%s" % instance.name
6319

    
6320

    
6321
def _CalcEta(time_taken, written, total_size):
6322
  """Calculates the ETA based on size written and total size.
6323

6324
  @param time_taken: The time taken so far
6325
  @param written: amount written so far
6326
  @param total_size: The total size of data to be written
6327
  @return: The remaining time in seconds
6328

6329
  """
6330
  avg_time = time_taken / float(written)
6331
  return (total_size - written) * avg_time
6332

    
6333

    
6334
def _WipeDisks(lu, instance):
6335
  """Wipes instance disks.
6336

6337
  @type lu: L{LogicalUnit}
6338
  @param lu: the logical unit on whose behalf we execute
6339
  @type instance: L{objects.Instance}
6340
  @param instance: the instance whose disks we should create
6341
  @return: the success of the wipe
6342

6343
  """
6344
  node = instance.primary_node
6345
  for idx, device in enumerate(instance.disks):
6346
    lu.LogInfo("* Wiping disk %d", idx)
6347
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6348

    
6349
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6350
    # MAX_WIPE_CHUNK at max
6351
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6352
                          constants.MIN_WIPE_CHUNK_PERCENT)
6353

    
6354
    offset = 0
6355
    size = device.size
6356
    last_output = 0
6357
    start_time = time.time()
6358

    
6359
    while offset < size:
6360
      wipe_size = min(wipe_chunk_size, size - offset)
6361
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6362
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6363
                   (idx, offset, wipe_size))
6364
      now = time.time()
6365
      offset += wipe_size
6366
      if now - last_output >= 60:
6367
        eta = _CalcEta(now - start_time, offset, size)
6368
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6369
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6370
        last_output = now
6371

    
6372

    
6373
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6374
  """Create all disks for an instance.
6375

6376
  This abstracts away some work from AddInstance.
6377

6378
  @type lu: L{LogicalUnit}
6379
  @param lu: the logical unit on whose behalf we execute
6380
  @type instance: L{objects.Instance}
6381
  @param instance: the instance whose disks we should create
6382
  @type to_skip: list
6383
  @param to_skip: list of indices to skip
6384
  @type target_node: string
6385
  @param target_node: if passed, overrides the target node for creation
6386
  @rtype: boolean
6387
  @return: the success of the creation
6388

6389
  """
6390
  info = _GetInstanceInfoText(instance)
6391
  if target_node is None:
6392
    pnode = instance.primary_node
6393
    all_nodes = instance.all_nodes
6394
  else:
6395
    pnode = target_node
6396
    all_nodes = [pnode]
6397

    
6398
  if instance.disk_template == constants.DT_FILE:
6399
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6400
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6401

    
6402
    result.Raise("Failed to create directory '%s' on"
6403
                 " node %s" % (file_storage_dir, pnode))
6404

    
6405
  # Note: this needs to be kept in sync with adding of disks in
6406
  # LUSetInstanceParams
6407
  for idx, device in enumerate(instance.disks):
6408
    if to_skip and idx in to_skip:
6409
      continue
6410
    logging.info("Creating volume %s for instance %s",
6411
                 device.iv_name, instance.name)
6412
    #HARDCODE
6413
    for node in all_nodes:
6414
      f_create = node == pnode
6415
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6416

    
6417

    
6418
def _RemoveDisks(lu, instance, target_node=None):
6419
  """Remove all disks for an instance.
6420

6421
  This abstracts away some work from `AddInstance()` and
6422
  `RemoveInstance()`. Note that in case some of the devices couldn't
6423
  be removed, the removal will continue with the other ones (compare
6424
  with `_CreateDisks()`).
6425

6426
  @type lu: L{LogicalUnit}
6427
  @param lu: the logical unit on whose behalf we execute
6428
  @type instance: L{objects.Instance}
6429
  @param instance: the instance whose disks we should remove
6430
  @type target_node: string
6431
  @param target_node: used to override the node on which to remove the disks
6432
  @rtype: boolean
6433
  @return: the success of the removal
6434

6435
  """
6436
  logging.info("Removing block devices for instance %s", instance.name)
6437

    
6438
  all_result = True
6439
  for device in instance.disks:
6440
    if target_node:
6441
      edata = [(target_node, device)]
6442
    else:
6443
      edata = device.ComputeNodeTree(instance.primary_node)
6444
    for node, disk in edata:
6445
      lu.cfg.SetDiskID(disk, node)
6446
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6447
      if msg:
6448
        lu.LogWarning("Could not remove block device %s on node %s,"
6449
                      " continuing anyway: %s", device.iv_name, node, msg)
6450
        all_result = False
6451

    
6452
  if instance.disk_template == constants.DT_FILE:
6453
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6454
    if target_node:
6455
      tgt = target_node
6456
    else:
6457
      tgt = instance.primary_node
6458
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6459
    if result.fail_msg:
6460
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6461
                    file_storage_dir, instance.primary_node, result.fail_msg)
6462
      all_result = False
6463

    
6464
  return all_result
6465

    
6466

    
6467
def _ComputeDiskSize(disk_template, disks):
6468
  """Compute disk size requirements in the volume group
6469

6470
  """
6471
  # Required free disk space as a function of disk and swap space
6472
  req_size_dict = {
6473
    constants.DT_DISKLESS: None,
6474
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6475
    # 128 MB are added for drbd metadata for each disk
6476
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6477
    constants.DT_FILE: None,
6478
  }
6479

    
6480
  if disk_template not in req_size_dict:
6481
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6482
                                 " is unknown" %  disk_template)
6483

    
6484
  return req_size_dict[disk_template]
6485

    
6486

    
6487
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6488
  """Hypervisor parameter validation.
6489

6490
  This function abstract the hypervisor parameter validation to be
6491
  used in both instance create and instance modify.
6492

6493
  @type lu: L{LogicalUnit}
6494
  @param lu: the logical unit for which we check
6495
  @type nodenames: list
6496
  @param nodenames: the list of nodes on which we should check
6497
  @type hvname: string
6498
  @param hvname: the name of the hypervisor we should use
6499
  @type hvparams: dict
6500
  @param hvparams: the parameters which we need to check
6501
  @raise errors.OpPrereqError: if the parameters are not valid
6502

6503
  """
6504
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6505
                                                  hvname,
6506
                                                  hvparams)
6507
  for node in nodenames:
6508
    info = hvinfo[node]
6509
    if info.offline:
6510
      continue
6511
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6512

    
6513

    
6514
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6515
  """OS parameters validation.
6516

6517
  @type lu: L{LogicalUnit}
6518
  @param lu: the logical unit for which we check
6519
  @type required: boolean
6520
  @param required: whether the validation should fail if the OS is not
6521
      found
6522
  @type nodenames: list
6523
  @param nodenames: the list of nodes on which we should check
6524
  @type osname: string
6525
  @param osname: the name of the hypervisor we should use
6526
  @type osparams: dict
6527
  @param osparams: the parameters which we need to check
6528
  @raise errors.OpPrereqError: if the parameters are not valid
6529

6530
  """
6531
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6532
                                   [constants.OS_VALIDATE_PARAMETERS],
6533
                                   osparams)
6534
  for node, nres in result.items():
6535
    # we don't check for offline cases since this should be run only
6536
    # against the master node and/or an instance's nodes
6537
    nres.Raise("OS Parameters validation failed on node %s" % node)
6538
    if not nres.payload:
6539
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6540
                 osname, node)
6541

    
6542

    
6543
class LUCreateInstance(LogicalUnit):
6544
  """Create an instance.
6545

6546
  """
6547
  HPATH = "instance-add"
6548
  HTYPE = constants.HTYPE_INSTANCE
6549
  _OP_PARAMS = [
6550
    _PInstanceName,
6551
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6552
    ("start", True, ht.TBool),
6553
    ("wait_for_sync", True, ht.TBool),
6554
    ("ip_check", True, ht.TBool),
6555
    ("name_check", True, ht.TBool),
6556
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6557
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6558
    ("hvparams", ht.EmptyDict, ht.TDict),
6559
    ("beparams", ht.EmptyDict, ht.TDict),
6560
    ("osparams", ht.EmptyDict, ht.TDict),
6561
    ("no_install", None, ht.TMaybeBool),
6562
    ("os_type", None, ht.TMaybeString),
6563
    ("force_variant", False, ht.TBool),
6564
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6565
    ("source_x509_ca", None, ht.TMaybeString),
6566
    ("source_instance_name", None, ht.TMaybeString),
6567
    ("src_node", None, ht.TMaybeString),
6568
    ("src_path", None, ht.TMaybeString),
6569
    ("pnode", None, ht.TMaybeString),
6570
    ("snode", None, ht.TMaybeString),
6571
    ("iallocator", None, ht.TMaybeString),
6572
    ("hypervisor", None, ht.TMaybeString),
6573
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6574
    ("identify_defaults", False, ht.TBool),
6575
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6576
    ("file_storage_dir", None, ht.TMaybeString),
6577
    ]
6578
  REQ_BGL = False
6579

    
6580
  def CheckArguments(self):
6581
    """Check arguments.
6582

6583
    """
6584
    # do not require name_check to ease forward/backward compatibility
6585
    # for tools
6586
    if self.op.no_install and self.op.start:
6587
      self.LogInfo("No-installation mode selected, disabling startup")
6588
      self.op.start = False
6589
    # validate/normalize the instance name
6590
    self.op.instance_name = \
6591
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6592

    
6593
    if self.op.ip_check and not self.op.name_check:
6594
      # TODO: make the ip check more flexible and not depend on the name check
6595
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6596
                                 errors.ECODE_INVAL)
6597

    
6598
    # check nics' parameter names
6599
    for nic in self.op.nics:
6600
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6601

    
6602
    # check disks. parameter names and consistent adopt/no-adopt strategy
6603
    has_adopt = has_no_adopt = False
6604
    for disk in self.op.disks:
6605
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6606
      if "adopt" in disk:
6607
        has_adopt = True
6608
      else:
6609
        has_no_adopt = True
6610
    if has_adopt and has_no_adopt:
6611
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6612
                                 errors.ECODE_INVAL)
6613
    if has_adopt:
6614
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6615
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6616
                                   " '%s' disk template" %
6617
                                   self.op.disk_template,
6618
                                   errors.ECODE_INVAL)
6619
      if self.op.iallocator is not None:
6620
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6621
                                   " iallocator script", errors.ECODE_INVAL)
6622
      if self.op.mode == constants.INSTANCE_IMPORT:
6623
        raise errors.OpPrereqError("Disk adoption not allowed for"
6624
                                   " instance import", errors.ECODE_INVAL)
6625

    
6626
    self.adopt_disks = has_adopt
6627

    
6628
    # instance name verification
6629
    if self.op.name_check:
6630
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6631
      self.op.instance_name = self.hostname1.name
6632
      # used in CheckPrereq for ip ping check
6633
      self.check_ip = self.hostname1.ip
6634
    else:
6635
      self.check_ip = None
6636

    
6637
    # file storage checks
6638
    if (self.op.file_driver and
6639
        not self.op.file_driver in constants.FILE_DRIVER):
6640
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6641
                                 self.op.file_driver, errors.ECODE_INVAL)
6642

    
6643
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6644
      raise errors.OpPrereqError("File storage directory path not absolute",
6645
                                 errors.ECODE_INVAL)
6646

    
6647
    ### Node/iallocator related checks
6648
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6649

    
6650
    if self.op.pnode is not None:
6651
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6652
        if self.op.snode is None:
6653
          raise errors.OpPrereqError("The networked disk templates need"
6654
                                     " a mirror node", errors.ECODE_INVAL)
6655
      elif self.op.snode:
6656
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6657
                        " template")
6658
        self.op.snode = None
6659

    
6660
    self._cds = _GetClusterDomainSecret()
6661

    
6662
    if self.op.mode == constants.INSTANCE_IMPORT:
6663
      # On import force_variant must be True, because if we forced it at
6664
      # initial install, our only chance when importing it back is that it
6665
      # works again!
6666
      self.op.force_variant = True
6667

    
6668
      if self.op.no_install:
6669
        self.LogInfo("No-installation mode has no effect during import")
6670

    
6671
    elif self.op.mode == constants.INSTANCE_CREATE:
6672
      if self.op.os_type is None:
6673
        raise errors.OpPrereqError("No guest OS specified",
6674
                                   errors.ECODE_INVAL)
6675
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6676
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6677
                                   " installation" % self.op.os_type,
6678
                                   errors.ECODE_STATE)
6679
      if self.op.disk_template is None:
6680
        raise errors.OpPrereqError("No disk template specified",
6681
                                   errors.ECODE_INVAL)
6682

    
6683
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6684
      # Check handshake to ensure both clusters have the same domain secret
6685
      src_handshake = self.op.source_handshake
6686
      if not src_handshake:
6687
        raise errors.OpPrereqError("Missing source handshake",
6688
                                   errors.ECODE_INVAL)
6689

    
6690
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6691
                                                           src_handshake)
6692
      if errmsg:
6693
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6694
                                   errors.ECODE_INVAL)
6695

    
6696
      # Load and check source CA
6697
      self.source_x509_ca_pem = self.op.source_x509_ca
6698
      if not self.source_x509_ca_pem:
6699
        raise errors.OpPrereqError("Missing source X509 CA",
6700
                                   errors.ECODE_INVAL)
6701

    
6702
      try:
6703
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6704
                                                    self._cds)
6705
      except OpenSSL.crypto.Error, err:
6706
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6707
                                   (err, ), errors.ECODE_INVAL)
6708

    
6709
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6710
      if errcode is not None:
6711
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6712
                                   errors.ECODE_INVAL)
6713

    
6714
      self.source_x509_ca = cert
6715

    
6716
      src_instance_name = self.op.source_instance_name
6717
      if not src_instance_name:
6718
        raise errors.OpPrereqError("Missing source instance name",
6719
                                   errors.ECODE_INVAL)
6720

    
6721
      self.source_instance_name = \
6722
          netutils.GetHostname(name=src_instance_name).name
6723

    
6724
    else:
6725
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6726
                                 self.op.mode, errors.ECODE_INVAL)
6727

    
6728
  def ExpandNames(self):
6729
    """ExpandNames for CreateInstance.
6730

6731
    Figure out the right locks for instance creation.
6732

6733
    """
6734
    self.needed_locks = {}
6735

    
6736
    instance_name = self.op.instance_name
6737
    # this is just a preventive check, but someone might still add this
6738
    # instance in the meantime, and creation will fail at lock-add time
6739
    if instance_name in self.cfg.GetInstanceList():
6740
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6741
                                 instance_name, errors.ECODE_EXISTS)
6742

    
6743
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6744

    
6745
    if self.op.iallocator:
6746
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6747
    else:
6748
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6749
      nodelist = [self.op.pnode]
6750
      if self.op.snode is not None:
6751
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6752
        nodelist.append(self.op.snode)
6753
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6754

    
6755
    # in case of import lock the source node too
6756
    if self.op.mode == constants.INSTANCE_IMPORT:
6757
      src_node = self.op.src_node
6758
      src_path = self.op.src_path
6759

    
6760
      if src_path is None:
6761
        self.op.src_path = src_path = self.op.instance_name
6762

    
6763
      if src_node is None:
6764
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6765
        self.op.src_node = None
6766
        if os.path.isabs(src_path):
6767
          raise errors.OpPrereqError("Importing an instance from an absolute"
6768
                                     " path requires a source node option.",
6769
                                     errors.ECODE_INVAL)
6770
      else:
6771
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6772
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6773
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6774
        if not os.path.isabs(src_path):
6775
          self.op.src_path = src_path = \
6776
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6777

    
6778
  def _RunAllocator(self):
6779
    """Run the allocator based on input opcode.
6780

6781
    """
6782
    nics = [n.ToDict() for n in self.nics]
6783
    ial = IAllocator(self.cfg, self.rpc,
6784
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6785
                     name=self.op.instance_name,
6786
                     disk_template=self.op.disk_template,
6787
                     tags=[],
6788
                     os=self.op.os_type,
6789
                     vcpus=self.be_full[constants.BE_VCPUS],
6790
                     mem_size=self.be_full[constants.BE_MEMORY],
6791
                     disks=self.disks,
6792
                     nics=nics,
6793
                     hypervisor=self.op.hypervisor,
6794
                     )
6795

    
6796
    ial.Run(self.op.iallocator)
6797

    
6798
    if not ial.success:
6799
      raise errors.OpPrereqError("Can't compute nodes using"
6800
                                 " iallocator '%s': %s" %
6801
                                 (self.op.iallocator, ial.info),
6802
                                 errors.ECODE_NORES)
6803
    if len(ial.result) != ial.required_nodes:
6804
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6805
                                 " of nodes (%s), required %s" %
6806
                                 (self.op.iallocator, len(ial.result),
6807
                                  ial.required_nodes), errors.ECODE_FAULT)
6808
    self.op.pnode = ial.result[0]
6809
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6810
                 self.op.instance_name, self.op.iallocator,
6811
                 utils.CommaJoin(ial.result))
6812
    if ial.required_nodes == 2:
6813
      self.op.snode = ial.result[1]
6814

    
6815
  def BuildHooksEnv(self):
6816
    """Build hooks env.
6817

6818
    This runs on master, primary and secondary nodes of the instance.
6819

6820
    """
6821
    env = {
6822
      "ADD_MODE": self.op.mode,
6823
      }
6824
    if self.op.mode == constants.INSTANCE_IMPORT:
6825
      env["SRC_NODE"] = self.op.src_node
6826
      env["SRC_PATH"] = self.op.src_path
6827
      env["SRC_IMAGES"] = self.src_images
6828

    
6829
    env.update(_BuildInstanceHookEnv(
6830
      name=self.op.instance_name,
6831
      primary_node=self.op.pnode,
6832
      secondary_nodes=self.secondaries,
6833
      status=self.op.start,
6834
      os_type=self.op.os_type,
6835
      memory=self.be_full[constants.BE_MEMORY],
6836
      vcpus=self.be_full[constants.BE_VCPUS],
6837
      nics=_NICListToTuple(self, self.nics),
6838
      disk_template=self.op.disk_template,
6839
      disks=[(d["size"], d["mode"]) for d in self.disks],
6840
      bep=self.be_full,
6841
      hvp=self.hv_full,
6842
      hypervisor_name=self.op.hypervisor,
6843
    ))
6844

    
6845
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6846
          self.secondaries)
6847
    return env, nl, nl
6848

    
6849
  def _ReadExportInfo(self):
6850
    """Reads the export information from disk.
6851

6852
    It will override the opcode source node and path with the actual
6853
    information, if these two were not specified before.
6854

6855
    @return: the export information
6856

6857
    """
6858
    assert self.op.mode == constants.INSTANCE_IMPORT
6859

    
6860
    src_node = self.op.src_node
6861
    src_path = self.op.src_path
6862

    
6863
    if src_node is None:
6864
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6865
      exp_list = self.rpc.call_export_list(locked_nodes)
6866
      found = False
6867
      for node in exp_list:
6868
        if exp_list[node].fail_msg:
6869
          continue
6870
        if src_path in exp_list[node].payload:
6871
          found = True
6872
          self.op.src_node = src_node = node
6873
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6874
                                                       src_path)
6875
          break
6876
      if not found:
6877
        raise errors.OpPrereqError("No export found for relative path %s" %
6878
                                    src_path, errors.ECODE_INVAL)
6879

    
6880
    _CheckNodeOnline(self, src_node)
6881
    result = self.rpc.call_export_info(src_node, src_path)
6882
    result.Raise("No export or invalid export found in dir %s" % src_path)
6883

    
6884
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6885
    if not export_info.has_section(constants.INISECT_EXP):
6886
      raise errors.ProgrammerError("Corrupted export config",
6887
                                   errors.ECODE_ENVIRON)
6888

    
6889
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6890
    if (int(ei_version) != constants.EXPORT_VERSION):
6891
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6892
                                 (ei_version, constants.EXPORT_VERSION),
6893
                                 errors.ECODE_ENVIRON)
6894
    return export_info
6895

    
6896
  def _ReadExportParams(self, einfo):
6897
    """Use export parameters as defaults.
6898

6899
    In case the opcode doesn't specify (as in override) some instance
6900
    parameters, then try to use them from the export information, if
6901
    that declares them.
6902

6903
    """
6904
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6905

    
6906
    if self.op.disk_template is None:
6907
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6908
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6909
                                          "disk_template")
6910
      else:
6911
        raise errors.OpPrereqError("No disk template specified and the export"
6912
                                   " is missing the disk_template information",
6913
                                   errors.ECODE_INVAL)
6914

    
6915
    if not self.op.disks:
6916
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6917
        disks = []
6918
        # TODO: import the disk iv_name too
6919
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6920
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6921
          disks.append({"size": disk_sz})
6922
        self.op.disks = disks
6923
      else:
6924
        raise errors.OpPrereqError("No disk info specified and the export"
6925
                                   " is missing the disk information",
6926
                                   errors.ECODE_INVAL)
6927

    
6928
    if (not self.op.nics and
6929
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6930
      nics = []
6931
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6932
        ndict = {}
6933
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6934
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6935
          ndict[name] = v
6936
        nics.append(ndict)
6937
      self.op.nics = nics
6938

    
6939
    if (self.op.hypervisor is None and
6940
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6941
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6942
    if einfo.has_section(constants.INISECT_HYP):
6943
      # use the export parameters but do not override the ones
6944
      # specified by the user
6945
      for name, value in einfo.items(constants.INISECT_HYP):
6946
        if name not in self.op.hvparams:
6947
          self.op.hvparams[name] = value
6948

    
6949
    if einfo.has_section(constants.INISECT_BEP):
6950
      # use the parameters, without overriding
6951
      for name, value in einfo.items(constants.INISECT_BEP):
6952
        if name not in self.op.beparams:
6953
          self.op.beparams[name] = value
6954
    else:
6955
      # try to read the parameters old style, from the main section
6956
      for name in constants.BES_PARAMETERS:
6957
        if (name not in self.op.beparams and
6958
            einfo.has_option(constants.INISECT_INS, name)):
6959
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6960

    
6961
    if einfo.has_section(constants.INISECT_OSP):
6962
      # use the parameters, without overriding
6963
      for name, value in einfo.items(constants.INISECT_OSP):
6964
        if name not in self.op.osparams:
6965
          self.op.osparams[name] = value
6966

    
6967
  def _RevertToDefaults(self, cluster):
6968
    """Revert the instance parameters to the default values.
6969

6970
    """
6971
    # hvparams
6972
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6973
    for name in self.op.hvparams.keys():
6974
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6975
        del self.op.hvparams[name]
6976
    # beparams
6977
    be_defs = cluster.SimpleFillBE({})
6978
    for name in self.op.beparams.keys():
6979
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6980
        del self.op.beparams[name]
6981
    # nic params
6982
    nic_defs = cluster.SimpleFillNIC({})
6983
    for nic in self.op.nics:
6984
      for name in constants.NICS_PARAMETERS:
6985
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6986
          del nic[name]
6987
    # osparams
6988
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6989
    for name in self.op.osparams.keys():
6990
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6991
        del self.op.osparams[name]
6992

    
6993
  def CheckPrereq(self):
6994
    """Check prerequisites.
6995

6996
    """
6997
    if self.op.mode == constants.INSTANCE_IMPORT:
6998
      export_info = self._ReadExportInfo()
6999
      self._ReadExportParams(export_info)
7000

    
7001
    _CheckDiskTemplate(self.op.disk_template)
7002

    
7003
    if (not self.cfg.GetVGName() and
7004
        self.op.disk_template not in constants.DTS_NOT_LVM):
7005
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7006
                                 " instances", errors.ECODE_STATE)
7007

    
7008
    if self.op.hypervisor is None:
7009
      self.op.hypervisor = self.cfg.GetHypervisorType()
7010

    
7011
    cluster = self.cfg.GetClusterInfo()
7012
    enabled_hvs = cluster.enabled_hypervisors
7013
    if self.op.hypervisor not in enabled_hvs:
7014
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7015
                                 " cluster (%s)" % (self.op.hypervisor,
7016
                                  ",".join(enabled_hvs)),
7017
                                 errors.ECODE_STATE)
7018

    
7019
    # check hypervisor parameter syntax (locally)
7020
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7021
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7022
                                      self.op.hvparams)
7023
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7024
    hv_type.CheckParameterSyntax(filled_hvp)
7025
    self.hv_full = filled_hvp
7026
    # check that we don't specify global parameters on an instance
7027
    _CheckGlobalHvParams(self.op.hvparams)
7028

    
7029
    # fill and remember the beparams dict
7030
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7031
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7032

    
7033
    # build os parameters
7034
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7035

    
7036
    # now that hvp/bep are in final format, let's reset to defaults,
7037
    # if told to do so
7038
    if self.op.identify_defaults:
7039
      self._RevertToDefaults(cluster)
7040

    
7041
    # NIC buildup
7042
    self.nics = []
7043
    for idx, nic in enumerate(self.op.nics):
7044
      nic_mode_req = nic.get("mode", None)
7045
      nic_mode = nic_mode_req
7046
      if nic_mode is None:
7047
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7048

    
7049
      # in routed mode, for the first nic, the default ip is 'auto'
7050
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7051
        default_ip_mode = constants.VALUE_AUTO
7052
      else:
7053
        default_ip_mode = constants.VALUE_NONE
7054

    
7055
      # ip validity checks
7056
      ip = nic.get("ip", default_ip_mode)
7057
      if ip is None or ip.lower() == constants.VALUE_NONE:
7058
        nic_ip = None
7059
      elif ip.lower() == constants.VALUE_AUTO:
7060
        if not self.op.name_check:
7061
          raise errors.OpPrereqError("IP address set to auto but name checks"
7062
                                     " have been skipped",
7063
                                     errors.ECODE_INVAL)
7064
        nic_ip = self.hostname1.ip
7065
      else:
7066
        if not netutils.IPAddress.IsValid(ip):
7067
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7068
                                     errors.ECODE_INVAL)
7069
        nic_ip = ip
7070

    
7071
      # TODO: check the ip address for uniqueness
7072
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7073
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7074
                                   errors.ECODE_INVAL)
7075

    
7076
      # MAC address verification
7077
      mac = nic.get("mac", constants.VALUE_AUTO)
7078
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7079
        mac = utils.NormalizeAndValidateMac(mac)
7080

    
7081
        try:
7082
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7083
        except errors.ReservationError:
7084
          raise errors.OpPrereqError("MAC address %s already in use"
7085
                                     " in cluster" % mac,
7086
                                     errors.ECODE_NOTUNIQUE)
7087

    
7088
      # bridge verification
7089
      bridge = nic.get("bridge", None)
7090
      link = nic.get("link", None)
7091
      if bridge and link:
7092
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7093
                                   " at the same time", errors.ECODE_INVAL)
7094
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7095
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7096
                                   errors.ECODE_INVAL)
7097
      elif bridge:
7098
        link = bridge
7099

    
7100
      nicparams = {}
7101
      if nic_mode_req:
7102
        nicparams[constants.NIC_MODE] = nic_mode_req
7103
      if link:
7104
        nicparams[constants.NIC_LINK] = link
7105

    
7106
      check_params = cluster.SimpleFillNIC(nicparams)
7107
      objects.NIC.CheckParameterSyntax(check_params)
7108
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7109

    
7110
    # disk checks/pre-build
7111
    self.disks = []
7112
    for disk in self.op.disks:
7113
      mode = disk.get("mode", constants.DISK_RDWR)
7114
      if mode not in constants.DISK_ACCESS_SET:
7115
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7116
                                   mode, errors.ECODE_INVAL)
7117
      size = disk.get("size", None)
7118
      if size is None:
7119
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7120
      try:
7121
        size = int(size)
7122
      except (TypeError, ValueError):
7123
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7124
                                   errors.ECODE_INVAL)
7125
      new_disk = {"size": size, "mode": mode}
7126
      if "adopt" in disk:
7127
        new_disk["adopt"] = disk["adopt"]
7128
      self.disks.append(new_disk)
7129

    
7130
    if self.op.mode == constants.INSTANCE_IMPORT:
7131

    
7132
      # Check that the new instance doesn't have less disks than the export
7133
      instance_disks = len(self.disks)
7134
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7135
      if instance_disks < export_disks:
7136
        raise errors.OpPrereqError("Not enough disks to import."
7137
                                   " (instance: %d, export: %d)" %
7138
                                   (instance_disks, export_disks),
7139
                                   errors.ECODE_INVAL)
7140

    
7141
      disk_images = []
7142
      for idx in range(export_disks):
7143
        option = 'disk%d_dump' % idx
7144
        if export_info.has_option(constants.INISECT_INS, option):
7145
          # FIXME: are the old os-es, disk sizes, etc. useful?
7146
          export_name = export_info.get(constants.INISECT_INS, option)
7147
          image = utils.PathJoin(self.op.src_path, export_name)
7148
          disk_images.append(image)
7149
        else:
7150
          disk_images.append(False)
7151

    
7152
      self.src_images = disk_images
7153

    
7154
      old_name = export_info.get(constants.INISECT_INS, 'name')
7155
      try:
7156
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7157
      except (TypeError, ValueError), err:
7158
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7159
                                   " an integer: %s" % str(err),
7160
                                   errors.ECODE_STATE)
7161
      if self.op.instance_name == old_name:
7162
        for idx, nic in enumerate(self.nics):
7163
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7164
            nic_mac_ini = 'nic%d_mac' % idx
7165
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7166

    
7167
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7168

    
7169
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7170
    if self.op.ip_check:
7171
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7172
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7173
                                   (self.check_ip, self.op.instance_name),
7174
                                   errors.ECODE_NOTUNIQUE)
7175

    
7176
    #### mac address generation
7177
    # By generating here the mac address both the allocator and the hooks get
7178
    # the real final mac address rather than the 'auto' or 'generate' value.
7179
    # There is a race condition between the generation and the instance object
7180
    # creation, which means that we know the mac is valid now, but we're not
7181
    # sure it will be when we actually add the instance. If things go bad
7182
    # adding the instance will abort because of a duplicate mac, and the
7183
    # creation job will fail.
7184
    for nic in self.nics:
7185
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7186
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7187

    
7188
    #### allocator run
7189

    
7190
    if self.op.iallocator is not None:
7191
      self._RunAllocator()
7192

    
7193
    #### node related checks
7194

    
7195
    # check primary node
7196
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7197
    assert self.pnode is not None, \
7198
      "Cannot retrieve locked node %s" % self.op.pnode
7199
    if pnode.offline:
7200
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7201
                                 pnode.name, errors.ECODE_STATE)
7202
    if pnode.drained:
7203
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7204
                                 pnode.name, errors.ECODE_STATE)
7205

    
7206
    self.secondaries = []
7207

    
7208
    # mirror node verification
7209
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7210
      if self.op.snode == pnode.name:
7211
        raise errors.OpPrereqError("The secondary node cannot be the"
7212
                                   " primary node.", errors.ECODE_INVAL)
7213
      _CheckNodeOnline(self, self.op.snode)
7214
      _CheckNodeNotDrained(self, self.op.snode)
7215
      self.secondaries.append(self.op.snode)
7216

    
7217
    nodenames = [pnode.name] + self.secondaries
7218

    
7219
    req_size = _ComputeDiskSize(self.op.disk_template,
7220
                                self.disks)
7221

    
7222
    # Check lv size requirements, if not adopting
7223
    if req_size is not None and not self.adopt_disks:
7224
      _CheckNodesFreeDisk(self, nodenames, req_size)
7225

    
7226
    if self.adopt_disks: # instead, we must check the adoption data
7227
      all_lvs = set([i["adopt"] for i in self.disks])
7228
      if len(all_lvs) != len(self.disks):
7229
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7230
                                   errors.ECODE_INVAL)
7231
      for lv_name in all_lvs:
7232
        try:
7233
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7234
        except errors.ReservationError:
7235
          raise errors.OpPrereqError("LV named %s used by another instance" %
7236
                                     lv_name, errors.ECODE_NOTUNIQUE)
7237

    
7238
      node_lvs = self.rpc.call_lv_list([pnode.name],
7239
                                       self.cfg.GetVGName())[pnode.name]
7240
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7241
      node_lvs = node_lvs.payload
7242
      delta = all_lvs.difference(node_lvs.keys())
7243
      if delta:
7244
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7245
                                   utils.CommaJoin(delta),
7246
                                   errors.ECODE_INVAL)
7247
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7248
      if online_lvs:
7249
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7250
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7251
                                   errors.ECODE_STATE)
7252
      # update the size of disk based on what is found
7253
      for dsk in self.disks:
7254
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7255

    
7256
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7257

    
7258
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7259
    # check OS parameters (remotely)
7260
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7261

    
7262
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7263

    
7264
    # memory check on primary node
7265
    if self.op.start:
7266
      _CheckNodeFreeMemory(self, self.pnode.name,
7267
                           "creating instance %s" % self.op.instance_name,
7268
                           self.be_full[constants.BE_MEMORY],
7269
                           self.op.hypervisor)
7270

    
7271
    self.dry_run_result = list(nodenames)
7272

    
7273
  def Exec(self, feedback_fn):
7274
    """Create and add the instance to the cluster.
7275

7276
    """
7277
    instance = self.op.instance_name
7278
    pnode_name = self.pnode.name
7279

    
7280
    ht_kind = self.op.hypervisor
7281
    if ht_kind in constants.HTS_REQ_PORT:
7282
      network_port = self.cfg.AllocatePort()
7283
    else:
7284
      network_port = None
7285

    
7286
    if constants.ENABLE_FILE_STORAGE:
7287
      # this is needed because os.path.join does not accept None arguments
7288
      if self.op.file_storage_dir is None:
7289
        string_file_storage_dir = ""
7290
      else:
7291
        string_file_storage_dir = self.op.file_storage_dir
7292

    
7293
      # build the full file storage dir path
7294
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7295
                                        string_file_storage_dir, instance)
7296
    else:
7297
      file_storage_dir = ""
7298

    
7299
    disks = _GenerateDiskTemplate(self,
7300
                                  self.op.disk_template,
7301
                                  instance, pnode_name,
7302
                                  self.secondaries,
7303
                                  self.disks,
7304
                                  file_storage_dir,
7305
                                  self.op.file_driver,
7306
                                  0)
7307

    
7308
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7309
                            primary_node=pnode_name,
7310
                            nics=self.nics, disks=disks,
7311
                            disk_template=self.op.disk_template,
7312
                            admin_up=False,
7313
                            network_port=network_port,
7314
                            beparams=self.op.beparams,
7315
                            hvparams=self.op.hvparams,
7316
                            hypervisor=self.op.hypervisor,
7317
                            osparams=self.op.osparams,
7318
                            )
7319

    
7320
    if self.adopt_disks:
7321
      # rename LVs to the newly-generated names; we need to construct
7322
      # 'fake' LV disks with the old data, plus the new unique_id
7323
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7324
      rename_to = []
7325
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7326
        rename_to.append(t_dsk.logical_id)
7327
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7328
        self.cfg.SetDiskID(t_dsk, pnode_name)
7329
      result = self.rpc.call_blockdev_rename(pnode_name,
7330
                                             zip(tmp_disks, rename_to))
7331
      result.Raise("Failed to rename adoped LVs")
7332
    else:
7333
      feedback_fn("* creating instance disks...")
7334
      try:
7335
        _CreateDisks(self, iobj)
7336
      except errors.OpExecError:
7337
        self.LogWarning("Device creation failed, reverting...")
7338
        try:
7339
          _RemoveDisks(self, iobj)
7340
        finally:
7341
          self.cfg.ReleaseDRBDMinors(instance)
7342
          raise
7343

    
7344
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7345
        feedback_fn("* wiping instance disks...")
7346
        try:
7347
          _WipeDisks(self, iobj)
7348
        except errors.OpExecError:
7349
          self.LogWarning("Device wiping failed, reverting...")
7350
          try:
7351
            _RemoveDisks(self, iobj)
7352
          finally:
7353
            self.cfg.ReleaseDRBDMinors(instance)
7354
            raise
7355

    
7356
    feedback_fn("adding instance %s to cluster config" % instance)
7357

    
7358
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7359

    
7360
    # Declare that we don't want to remove the instance lock anymore, as we've
7361
    # added the instance to the config
7362
    del self.remove_locks[locking.LEVEL_INSTANCE]
7363
    # Unlock all the nodes
7364
    if self.op.mode == constants.INSTANCE_IMPORT:
7365
      nodes_keep = [self.op.src_node]
7366
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7367
                       if node != self.op.src_node]
7368
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7369
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7370
    else:
7371
      self.context.glm.release(locking.LEVEL_NODE)
7372
      del self.acquired_locks[locking.LEVEL_NODE]
7373

    
7374
    if self.op.wait_for_sync:
7375
      disk_abort = not _WaitForSync(self, iobj)
7376
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7377
      # make sure the disks are not degraded (still sync-ing is ok)
7378
      time.sleep(15)
7379
      feedback_fn("* checking mirrors status")
7380
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7381
    else:
7382
      disk_abort = False
7383

    
7384
    if disk_abort:
7385
      _RemoveDisks(self, iobj)
7386
      self.cfg.RemoveInstance(iobj.name)
7387
      # Make sure the instance lock gets removed
7388
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7389
      raise errors.OpExecError("There are some degraded disks for"
7390
                               " this instance")
7391

    
7392
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7393
      if self.op.mode == constants.INSTANCE_CREATE:
7394
        if not self.op.no_install:
7395
          feedback_fn("* running the instance OS create scripts...")
7396
          # FIXME: pass debug option from opcode to backend
7397
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7398
                                                 self.op.debug_level)
7399
          result.Raise("Could not add os for instance %s"
7400
                       " on node %s" % (instance, pnode_name))
7401

    
7402
      elif self.op.mode == constants.INSTANCE_IMPORT:
7403
        feedback_fn("* running the instance OS import scripts...")
7404

    
7405
        transfers = []
7406

    
7407
        for idx, image in enumerate(self.src_images):
7408
          if not image:
7409
            continue
7410

    
7411
          # FIXME: pass debug option from opcode to backend
7412
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7413
                                             constants.IEIO_FILE, (image, ),
7414
                                             constants.IEIO_SCRIPT,
7415
                                             (iobj.disks[idx], idx),
7416
                                             None)
7417
          transfers.append(dt)
7418

    
7419
        import_result = \
7420
          masterd.instance.TransferInstanceData(self, feedback_fn,
7421
                                                self.op.src_node, pnode_name,
7422
                                                self.pnode.secondary_ip,
7423
                                                iobj, transfers)
7424
        if not compat.all(import_result):
7425
          self.LogWarning("Some disks for instance %s on node %s were not"
7426
                          " imported successfully" % (instance, pnode_name))
7427

    
7428
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7429
        feedback_fn("* preparing remote import...")
7430
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7431
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7432

    
7433
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7434
                                                     self.source_x509_ca,
7435
                                                     self._cds, timeouts)
7436
        if not compat.all(disk_results):
7437
          # TODO: Should the instance still be started, even if some disks
7438
          # failed to import (valid for local imports, too)?
7439
          self.LogWarning("Some disks for instance %s on node %s were not"
7440
                          " imported successfully" % (instance, pnode_name))
7441

    
7442
        # Run rename script on newly imported instance
7443
        assert iobj.name == instance
7444
        feedback_fn("Running rename script for %s" % instance)
7445
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7446
                                                   self.source_instance_name,
7447
                                                   self.op.debug_level)
7448
        if result.fail_msg:
7449
          self.LogWarning("Failed to run rename script for %s on node"
7450
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7451

    
7452
      else:
7453
        # also checked in the prereq part
7454
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7455
                                     % self.op.mode)
7456

    
7457
    if self.op.start:
7458
      iobj.admin_up = True
7459
      self.cfg.Update(iobj, feedback_fn)
7460
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7461
      feedback_fn("* starting instance...")
7462
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7463
      result.Raise("Could not start instance")
7464

    
7465
    return list(iobj.all_nodes)
7466

    
7467

    
7468
class LUConnectConsole(NoHooksLU):
7469
  """Connect to an instance's console.
7470

7471
  This is somewhat special in that it returns the command line that
7472
  you need to run on the master node in order to connect to the
7473
  console.
7474

7475
  """
7476
  _OP_PARAMS = [
7477
    _PInstanceName
7478
    ]
7479
  REQ_BGL = False
7480

    
7481
  def ExpandNames(self):
7482
    self._ExpandAndLockInstance()
7483

    
7484
  def CheckPrereq(self):
7485
    """Check prerequisites.
7486

7487
    This checks that the instance is in the cluster.
7488

7489
    """
7490
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7491
    assert self.instance is not None, \
7492
      "Cannot retrieve locked instance %s" % self.op.instance_name
7493
    _CheckNodeOnline(self, self.instance.primary_node)
7494

    
7495
  def Exec(self, feedback_fn):
7496
    """Connect to the console of an instance
7497

7498
    """
7499
    instance = self.instance
7500
    node = instance.primary_node
7501

    
7502
    node_insts = self.rpc.call_instance_list([node],
7503
                                             [instance.hypervisor])[node]
7504
    node_insts.Raise("Can't get node information from %s" % node)
7505

    
7506
    if instance.name not in node_insts.payload:
7507
      if instance.admin_up:
7508
        state = "ERROR_down"
7509
      else:
7510
        state = "ADMIN_down"
7511
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7512
                               (instance.name, state))
7513

    
7514
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7515

    
7516
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7517
    cluster = self.cfg.GetClusterInfo()
7518
    # beparams and hvparams are passed separately, to avoid editing the
7519
    # instance and then saving the defaults in the instance itself.
7520
    hvparams = cluster.FillHV(instance)
7521
    beparams = cluster.FillBE(instance)
7522
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7523

    
7524
    # build ssh cmdline
7525
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7526

    
7527

    
7528
class LUReplaceDisks(LogicalUnit):
7529
  """Replace the disks of an instance.
7530

7531
  """
7532
  HPATH = "mirrors-replace"
7533
  HTYPE = constants.HTYPE_INSTANCE
7534
  _OP_PARAMS = [
7535
    _PInstanceName,
7536
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7537
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7538
    ("remote_node", None, ht.TMaybeString),
7539
    ("iallocator", None, ht.TMaybeString),
7540
    ("early_release", False, ht.TBool),
7541
    ]
7542
  REQ_BGL = False
7543

    
7544
  def CheckArguments(self):
7545
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7546
                                  self.op.iallocator)
7547

    
7548
  def ExpandNames(self):
7549
    self._ExpandAndLockInstance()
7550

    
7551
    if self.op.iallocator is not None:
7552
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7553

    
7554
    elif self.op.remote_node is not None:
7555
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7556
      self.op.remote_node = remote_node
7557

    
7558
      # Warning: do not remove the locking of the new secondary here
7559
      # unless DRBD8.AddChildren is changed to work in parallel;
7560
      # currently it doesn't since parallel invocations of
7561
      # FindUnusedMinor will conflict
7562
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7563
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7564

    
7565
    else:
7566
      self.needed_locks[locking.LEVEL_NODE] = []
7567
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7568

    
7569
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7570
                                   self.op.iallocator, self.op.remote_node,
7571
                                   self.op.disks, False, self.op.early_release)
7572

    
7573
    self.tasklets = [self.replacer]
7574

    
7575
  def DeclareLocks(self, level):
7576
    # If we're not already locking all nodes in the set we have to declare the
7577
    # instance's primary/secondary nodes.
7578
    if (level == locking.LEVEL_NODE and
7579
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7580
      self._LockInstancesNodes()
7581

    
7582
  def BuildHooksEnv(self):
7583
    """Build hooks env.
7584

7585
    This runs on the master, the primary and all the secondaries.
7586

7587
    """
7588
    instance = self.replacer.instance
7589
    env = {
7590
      "MODE": self.op.mode,
7591
      "NEW_SECONDARY": self.op.remote_node,
7592
      "OLD_SECONDARY": instance.secondary_nodes[0],
7593
      }
7594
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7595
    nl = [
7596
      self.cfg.GetMasterNode(),
7597
      instance.primary_node,
7598
      ]
7599
    if self.op.remote_node is not None:
7600
      nl.append(self.op.remote_node)
7601
    return env, nl, nl
7602

    
7603

    
7604
class TLReplaceDisks(Tasklet):
7605
  """Replaces disks for an instance.
7606

7607
  Note: Locking is not within the scope of this class.
7608

7609
  """
7610
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7611
               disks, delay_iallocator, early_release):
7612
    """Initializes this class.
7613

7614
    """
7615
    Tasklet.__init__(self, lu)
7616

    
7617
    # Parameters
7618
    self.instance_name = instance_name
7619
    self.mode = mode
7620
    self.iallocator_name = iallocator_name
7621
    self.remote_node = remote_node
7622
    self.disks = disks
7623
    self.delay_iallocator = delay_iallocator
7624
    self.early_release = early_release
7625

    
7626
    # Runtime data
7627
    self.instance = None
7628
    self.new_node = None
7629
    self.target_node = None
7630
    self.other_node = None
7631
    self.remote_node_info = None
7632
    self.node_secondary_ip = None
7633

    
7634
  @staticmethod
7635
  def CheckArguments(mode, remote_node, iallocator):
7636
    """Helper function for users of this class.
7637

7638
    """
7639
    # check for valid parameter combination
7640
    if mode == constants.REPLACE_DISK_CHG:
7641
      if remote_node is None and iallocator is None:
7642
        raise errors.OpPrereqError("When changing the secondary either an"
7643
                                   " iallocator script must be used or the"
7644
                                   " new node given", errors.ECODE_INVAL)
7645

    
7646
      if remote_node is not None and iallocator is not None:
7647
        raise errors.OpPrereqError("Give either the iallocator or the new"
7648
                                   " secondary, not both", errors.ECODE_INVAL)
7649

    
7650
    elif remote_node is not None or iallocator is not None:
7651
      # Not replacing the secondary
7652
      raise errors.OpPrereqError("The iallocator and new node options can"
7653
                                 " only be used when changing the"
7654
                                 " secondary node", errors.ECODE_INVAL)
7655

    
7656
  @staticmethod
7657
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7658
    """Compute a new secondary node using an IAllocator.
7659

7660
    """
7661
    ial = IAllocator(lu.cfg, lu.rpc,
7662
                     mode=constants.IALLOCATOR_MODE_RELOC,
7663
                     name=instance_name,
7664
                     relocate_from=relocate_from)
7665

    
7666
    ial.Run(iallocator_name)
7667

    
7668
    if not ial.success:
7669
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7670
                                 " %s" % (iallocator_name, ial.info),
7671
                                 errors.ECODE_NORES)
7672

    
7673
    if len(ial.result) != ial.required_nodes:
7674
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7675
                                 " of nodes (%s), required %s" %
7676
                                 (iallocator_name,
7677
                                  len(ial.result), ial.required_nodes),
7678
                                 errors.ECODE_FAULT)
7679

    
7680
    remote_node_name = ial.result[0]
7681

    
7682
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7683
               instance_name, remote_node_name)
7684

    
7685
    return remote_node_name
7686

    
7687
  def _FindFaultyDisks(self, node_name):
7688
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7689
                                    node_name, True)
7690

    
7691
  def CheckPrereq(self):
7692
    """Check prerequisites.
7693

7694
    This checks that the instance is in the cluster.
7695

7696
    """
7697
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7698
    assert instance is not None, \
7699
      "Cannot retrieve locked instance %s" % self.instance_name
7700

    
7701
    if instance.disk_template != constants.DT_DRBD8:
7702
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7703
                                 " instances", errors.ECODE_INVAL)
7704

    
7705
    if len(instance.secondary_nodes) != 1:
7706
      raise errors.OpPrereqError("The instance has a strange layout,"
7707
                                 " expected one secondary but found %d" %
7708
                                 len(instance.secondary_nodes),
7709
                                 errors.ECODE_FAULT)
7710

    
7711
    if not self.delay_iallocator:
7712
      self._CheckPrereq2()
7713

    
7714
  def _CheckPrereq2(self):
7715
    """Check prerequisites, second part.
7716

7717
    This function should always be part of CheckPrereq. It was separated and is
7718
    now called from Exec because during node evacuation iallocator was only
7719
    called with an unmodified cluster model, not taking planned changes into
7720
    account.
7721

7722
    """
7723
    instance = self.instance
7724
    secondary_node = instance.secondary_nodes[0]
7725

    
7726
    if self.iallocator_name is None:
7727
      remote_node = self.remote_node
7728
    else:
7729
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7730
                                       instance.name, instance.secondary_nodes)
7731

    
7732
    if remote_node is not None:
7733
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7734
      assert self.remote_node_info is not None, \
7735
        "Cannot retrieve locked node %s" % remote_node
7736
    else:
7737
      self.remote_node_info = None
7738

    
7739
    if remote_node == self.instance.primary_node:
7740
      raise errors.OpPrereqError("The specified node is the primary node of"
7741
                                 " the instance.", errors.ECODE_INVAL)
7742

    
7743
    if remote_node == secondary_node:
7744
      raise errors.OpPrereqError("The specified node is already the"
7745
                                 " secondary node of the instance.",
7746
                                 errors.ECODE_INVAL)
7747

    
7748
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7749
                                    constants.REPLACE_DISK_CHG):
7750
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7751
                                 errors.ECODE_INVAL)
7752

    
7753
    if self.mode == constants.REPLACE_DISK_AUTO:
7754
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7755
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7756

    
7757
      if faulty_primary and faulty_secondary:
7758
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7759
                                   " one node and can not be repaired"
7760
                                   " automatically" % self.instance_name,
7761
                                   errors.ECODE_STATE)
7762

    
7763
      if faulty_primary:
7764
        self.disks = faulty_primary
7765
        self.target_node = instance.primary_node
7766
        self.other_node = secondary_node
7767
        check_nodes = [self.target_node, self.other_node]
7768
      elif faulty_secondary:
7769
        self.disks = faulty_secondary
7770
        self.target_node = secondary_node
7771
        self.other_node = instance.primary_node
7772
        check_nodes = [self.target_node, self.other_node]
7773
      else:
7774
        self.disks = []
7775
        check_nodes = []
7776

    
7777
    else:
7778
      # Non-automatic modes
7779
      if self.mode == constants.REPLACE_DISK_PRI:
7780
        self.target_node = instance.primary_node
7781
        self.other_node = secondary_node
7782
        check_nodes = [self.target_node, self.other_node]
7783

    
7784
      elif self.mode == constants.REPLACE_DISK_SEC:
7785
        self.target_node = secondary_node
7786
        self.other_node = instance.primary_node
7787
        check_nodes = [self.target_node, self.other_node]
7788

    
7789
      elif self.mode == constants.REPLACE_DISK_CHG:
7790
        self.new_node = remote_node
7791
        self.other_node = instance.primary_node
7792
        self.target_node = secondary_node
7793
        check_nodes = [self.new_node, self.other_node]
7794

    
7795
        _CheckNodeNotDrained(self.lu, remote_node)
7796

    
7797
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7798
        assert old_node_info is not None
7799
        if old_node_info.offline and not self.early_release:
7800
          # doesn't make sense to delay the release
7801
          self.early_release = True
7802
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7803
                          " early-release mode", secondary_node)
7804

    
7805
      else:
7806
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7807
                                     self.mode)
7808

    
7809
      # If not specified all disks should be replaced
7810
      if not self.disks:
7811
        self.disks = range(len(self.instance.disks))
7812

    
7813
    for node in check_nodes:
7814
      _CheckNodeOnline(self.lu, node)
7815

    
7816
    # Check whether disks are valid
7817
    for disk_idx in self.disks:
7818
      instance.FindDisk(disk_idx)
7819

    
7820
    # Get secondary node IP addresses
7821
    node_2nd_ip = {}
7822

    
7823
    for node_name in [self.target_node, self.other_node, self.new_node]:
7824
      if node_name is not None:
7825
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7826

    
7827
    self.node_secondary_ip = node_2nd_ip
7828

    
7829
  def Exec(self, feedback_fn):
7830
    """Execute disk replacement.
7831

7832
    This dispatches the disk replacement to the appropriate handler.
7833

7834
    """
7835
    if self.delay_iallocator:
7836
      self._CheckPrereq2()
7837

    
7838
    if not self.disks:
7839
      feedback_fn("No disks need replacement")
7840
      return
7841

    
7842
    feedback_fn("Replacing disk(s) %s for %s" %
7843
                (utils.CommaJoin(self.disks), self.instance.name))
7844

    
7845
    activate_disks = (not self.instance.admin_up)
7846

    
7847
    # Activate the instance disks if we're replacing them on a down instance
7848
    if activate_disks:
7849
      _StartInstanceDisks(self.lu, self.instance, True)
7850

    
7851
    try:
7852
      # Should we replace the secondary node?
7853
      if self.new_node is not None:
7854
        fn = self._ExecDrbd8Secondary
7855
      else:
7856
        fn = self._ExecDrbd8DiskOnly
7857

    
7858
      return fn(feedback_fn)
7859

    
7860
    finally:
7861
      # Deactivate the instance disks if we're replacing them on a
7862
      # down instance
7863
      if activate_disks:
7864
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7865

    
7866
  def _CheckVolumeGroup(self, nodes):
7867
    self.lu.LogInfo("Checking volume groups")
7868

    
7869
    vgname = self.cfg.GetVGName()
7870

    
7871
    # Make sure volume group exists on all involved nodes
7872
    results = self.rpc.call_vg_list(nodes)
7873
    if not results:
7874
      raise errors.OpExecError("Can't list volume groups on the nodes")
7875

    
7876
    for node in nodes:
7877
      res = results[node]
7878
      res.Raise("Error checking node %s" % node)
7879
      if vgname not in res.payload:
7880
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7881
                                 (vgname, node))
7882

    
7883
  def _CheckDisksExistence(self, nodes):
7884
    # Check disk existence
7885
    for idx, dev in enumerate(self.instance.disks):
7886
      if idx not in self.disks:
7887
        continue
7888

    
7889
      for node in nodes:
7890
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7891
        self.cfg.SetDiskID(dev, node)
7892

    
7893
        result = self.rpc.call_blockdev_find(node, dev)
7894

    
7895
        msg = result.fail_msg
7896
        if msg or not result.payload:
7897
          if not msg:
7898
            msg = "disk not found"
7899
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7900
                                   (idx, node, msg))
7901

    
7902
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7903
    for idx, dev in enumerate(self.instance.disks):
7904
      if idx not in self.disks:
7905
        continue
7906

    
7907
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7908
                      (idx, node_name))
7909

    
7910
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7911
                                   ldisk=ldisk):
7912
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7913
                                 " replace disks for instance %s" %
7914
                                 (node_name, self.instance.name))
7915

    
7916
  def _CreateNewStorage(self, node_name):
7917
    vgname = self.cfg.GetVGName()
7918
    iv_names = {}
7919

    
7920
    for idx, dev in enumerate(self.instance.disks):
7921
      if idx not in self.disks:
7922
        continue
7923

    
7924
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7925

    
7926
      self.cfg.SetDiskID(dev, node_name)
7927

    
7928
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7929
      names = _GenerateUniqueNames(self.lu, lv_names)
7930

    
7931
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7932
                             logical_id=(vgname, names[0]))
7933
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7934
                             logical_id=(vgname, names[1]))
7935

    
7936
      new_lvs = [lv_data, lv_meta]
7937
      old_lvs = dev.children
7938
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7939

    
7940
      # we pass force_create=True to force the LVM creation
7941
      for new_lv in new_lvs:
7942
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7943
                        _GetInstanceInfoText(self.instance), False)
7944

    
7945
    return iv_names
7946

    
7947
  def _CheckDevices(self, node_name, iv_names):
7948
    for name, (dev, _, _) in iv_names.iteritems():
7949
      self.cfg.SetDiskID(dev, node_name)
7950

    
7951
      result = self.rpc.call_blockdev_find(node_name, dev)
7952

    
7953
      msg = result.fail_msg
7954
      if msg or not result.payload:
7955
        if not msg:
7956
          msg = "disk not found"
7957
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7958
                                 (name, msg))
7959

    
7960
      if result.payload.is_degraded:
7961
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7962

    
7963
  def _RemoveOldStorage(self, node_name, iv_names):
7964
    for name, (_, old_lvs, _) in iv_names.iteritems():
7965
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7966

    
7967
      for lv in old_lvs:
7968
        self.cfg.SetDiskID(lv, node_name)
7969

    
7970
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7971
        if msg:
7972
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7973
                             hint="remove unused LVs manually")
7974

    
7975
  def _ReleaseNodeLock(self, node_name):
7976
    """Releases the lock for a given node."""
7977
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7978

    
7979
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7980
    """Replace a disk on the primary or secondary for DRBD 8.
7981

7982
    The algorithm for replace is quite complicated:
7983

7984
      1. for each disk to be replaced:
7985

7986
        1. create new LVs on the target node with unique names
7987
        1. detach old LVs from the drbd device
7988
        1. rename old LVs to name_replaced.<time_t>
7989
        1. rename new LVs to old LVs
7990
        1. attach the new LVs (with the old names now) to the drbd device
7991

7992
      1. wait for sync across all devices
7993

7994
      1. for each modified disk:
7995

7996
        1. remove old LVs (which have the name name_replaces.<time_t>)
7997

7998
    Failures are not very well handled.
7999

8000
    """
8001
    steps_total = 6
8002

    
8003
    # Step: check device activation
8004
    self.lu.LogStep(1, steps_total, "Check device existence")
8005
    self._CheckDisksExistence([self.other_node, self.target_node])
8006
    self._CheckVolumeGroup([self.target_node, self.other_node])
8007

    
8008
    # Step: check other node consistency
8009
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8010
    self._CheckDisksConsistency(self.other_node,
8011
                                self.other_node == self.instance.primary_node,
8012
                                False)
8013

    
8014
    # Step: create new storage
8015
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8016
    iv_names = self._CreateNewStorage(self.target_node)
8017

    
8018
    # Step: for each lv, detach+rename*2+attach
8019
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8020
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8021
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8022

    
8023
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8024
                                                     old_lvs)
8025
      result.Raise("Can't detach drbd from local storage on node"
8026
                   " %s for device %s" % (self.target_node, dev.iv_name))
8027
      #dev.children = []
8028
      #cfg.Update(instance)
8029

    
8030
      # ok, we created the new LVs, so now we know we have the needed
8031
      # storage; as such, we proceed on the target node to rename
8032
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8033
      # using the assumption that logical_id == physical_id (which in
8034
      # turn is the unique_id on that node)
8035

    
8036
      # FIXME(iustin): use a better name for the replaced LVs
8037
      temp_suffix = int(time.time())
8038
      ren_fn = lambda d, suff: (d.physical_id[0],
8039
                                d.physical_id[1] + "_replaced-%s" % suff)
8040

    
8041
      # Build the rename list based on what LVs exist on the node
8042
      rename_old_to_new = []
8043
      for to_ren in old_lvs:
8044
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8045
        if not result.fail_msg and result.payload:
8046
          # device exists
8047
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8048

    
8049
      self.lu.LogInfo("Renaming the old LVs on the target node")
8050
      result = self.rpc.call_blockdev_rename(self.target_node,
8051
                                             rename_old_to_new)
8052
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8053

    
8054
      # Now we rename the new LVs to the old LVs
8055
      self.lu.LogInfo("Renaming the new LVs on the target node")
8056
      rename_new_to_old = [(new, old.physical_id)
8057
                           for old, new in zip(old_lvs, new_lvs)]
8058
      result = self.rpc.call_blockdev_rename(self.target_node,
8059
                                             rename_new_to_old)
8060
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8061

    
8062
      for old, new in zip(old_lvs, new_lvs):
8063
        new.logical_id = old.logical_id
8064
        self.cfg.SetDiskID(new, self.target_node)
8065

    
8066
      for disk in old_lvs:
8067
        disk.logical_id = ren_fn(disk, temp_suffix)
8068
        self.cfg.SetDiskID(disk, self.target_node)
8069

    
8070
      # Now that the new lvs have the old name, we can add them to the device
8071
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8072
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8073
                                                  new_lvs)
8074
      msg = result.fail_msg
8075
      if msg:
8076
        for new_lv in new_lvs:
8077
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8078
                                               new_lv).fail_msg
8079
          if msg2:
8080
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8081
                               hint=("cleanup manually the unused logical"
8082
                                     "volumes"))
8083
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8084

    
8085
      dev.children = new_lvs
8086

    
8087
      self.cfg.Update(self.instance, feedback_fn)
8088

    
8089
    cstep = 5
8090
    if self.early_release:
8091
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8092
      cstep += 1
8093
      self._RemoveOldStorage(self.target_node, iv_names)
8094
      # WARNING: we release both node locks here, do not do other RPCs
8095
      # than WaitForSync to the primary node
8096
      self._ReleaseNodeLock([self.target_node, self.other_node])
8097

    
8098
    # Wait for sync
8099
    # This can fail as the old devices are degraded and _WaitForSync
8100
    # does a combined result over all disks, so we don't check its return value
8101
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8102
    cstep += 1
8103
    _WaitForSync(self.lu, self.instance)
8104

    
8105
    # Check all devices manually
8106
    self._CheckDevices(self.instance.primary_node, iv_names)
8107

    
8108
    # Step: remove old storage
8109
    if not self.early_release:
8110
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8111
      cstep += 1
8112
      self._RemoveOldStorage(self.target_node, iv_names)
8113

    
8114
  def _ExecDrbd8Secondary(self, feedback_fn):
8115
    """Replace the secondary node for DRBD 8.
8116

8117
    The algorithm for replace is quite complicated:
8118
      - for all disks of the instance:
8119
        - create new LVs on the new node with same names
8120
        - shutdown the drbd device on the old secondary
8121
        - disconnect the drbd network on the primary
8122
        - create the drbd device on the new secondary
8123
        - network attach the drbd on the primary, using an artifice:
8124
          the drbd code for Attach() will connect to the network if it
8125
          finds a device which is connected to the good local disks but
8126
          not network enabled
8127
      - wait for sync across all devices
8128
      - remove all disks from the old secondary
8129

8130
    Failures are not very well handled.
8131

8132
    """
8133
    steps_total = 6
8134

    
8135
    # Step: check device activation
8136
    self.lu.LogStep(1, steps_total, "Check device existence")
8137
    self._CheckDisksExistence([self.instance.primary_node])
8138
    self._CheckVolumeGroup([self.instance.primary_node])
8139

    
8140
    # Step: check other node consistency
8141
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8142
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8143

    
8144
    # Step: create new storage
8145
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8146
    for idx, dev in enumerate(self.instance.disks):
8147
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8148
                      (self.new_node, idx))
8149
      # we pass force_create=True to force LVM creation
8150
      for new_lv in dev.children:
8151
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8152
                        _GetInstanceInfoText(self.instance), False)
8153

    
8154
    # Step 4: dbrd minors and drbd setups changes
8155
    # after this, we must manually remove the drbd minors on both the
8156
    # error and the success paths
8157
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8158
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8159
                                         for dev in self.instance.disks],
8160
                                        self.instance.name)
8161
    logging.debug("Allocated minors %r", minors)
8162

    
8163
    iv_names = {}
8164
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8165
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8166
                      (self.new_node, idx))
8167
      # create new devices on new_node; note that we create two IDs:
8168
      # one without port, so the drbd will be activated without
8169
      # networking information on the new node at this stage, and one
8170
      # with network, for the latter activation in step 4
8171
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8172
      if self.instance.primary_node == o_node1:
8173
        p_minor = o_minor1
8174
      else:
8175
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8176
        p_minor = o_minor2
8177

    
8178
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8179
                      p_minor, new_minor, o_secret)
8180
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8181
                    p_minor, new_minor, o_secret)
8182

    
8183
      iv_names[idx] = (dev, dev.children, new_net_id)
8184
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8185
                    new_net_id)
8186
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8187
                              logical_id=new_alone_id,
8188
                              children=dev.children,
8189
                              size=dev.size)
8190
      try:
8191
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8192
                              _GetInstanceInfoText(self.instance), False)
8193
      except errors.GenericError:
8194
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8195
        raise
8196

    
8197
    # We have new devices, shutdown the drbd on the old secondary
8198
    for idx, dev in enumerate(self.instance.disks):
8199
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8200
      self.cfg.SetDiskID(dev, self.target_node)
8201
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8202
      if msg:
8203
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8204
                           "node: %s" % (idx, msg),
8205
                           hint=("Please cleanup this device manually as"
8206
                                 " soon as possible"))
8207

    
8208
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8209
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8210
                                               self.node_secondary_ip,
8211
                                               self.instance.disks)\
8212
                                              [self.instance.primary_node]
8213

    
8214
    msg = result.fail_msg
8215
    if msg:
8216
      # detaches didn't succeed (unlikely)
8217
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8218
      raise errors.OpExecError("Can't detach the disks from the network on"
8219
                               " old node: %s" % (msg,))
8220

    
8221
    # if we managed to detach at least one, we update all the disks of
8222
    # the instance to point to the new secondary
8223
    self.lu.LogInfo("Updating instance configuration")
8224
    for dev, _, new_logical_id in iv_names.itervalues():
8225
      dev.logical_id = new_logical_id
8226
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8227

    
8228
    self.cfg.Update(self.instance, feedback_fn)
8229

    
8230
    # and now perform the drbd attach
8231
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8232
                    " (standalone => connected)")
8233
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8234
                                            self.new_node],
8235
                                           self.node_secondary_ip,
8236
                                           self.instance.disks,
8237
                                           self.instance.name,
8238
                                           False)
8239
    for to_node, to_result in result.items():
8240
      msg = to_result.fail_msg
8241
      if msg:
8242
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8243
                           to_node, msg,
8244
                           hint=("please do a gnt-instance info to see the"
8245
                                 " status of disks"))
8246
    cstep = 5
8247
    if self.early_release:
8248
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8249
      cstep += 1
8250
      self._RemoveOldStorage(self.target_node, iv_names)
8251
      # WARNING: we release all node locks here, do not do other RPCs
8252
      # than WaitForSync to the primary node
8253
      self._ReleaseNodeLock([self.instance.primary_node,
8254
                             self.target_node,
8255
                             self.new_node])
8256

    
8257
    # Wait for sync
8258
    # This can fail as the old devices are degraded and _WaitForSync
8259
    # does a combined result over all disks, so we don't check its return value
8260
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8261
    cstep += 1
8262
    _WaitForSync(self.lu, self.instance)
8263

    
8264
    # Check all devices manually
8265
    self._CheckDevices(self.instance.primary_node, iv_names)
8266

    
8267
    # Step: remove old storage
8268
    if not self.early_release:
8269
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8270
      self._RemoveOldStorage(self.target_node, iv_names)
8271

    
8272

    
8273
class LURepairNodeStorage(NoHooksLU):
8274
  """Repairs the volume group on a node.
8275

8276
  """
8277
  _OP_PARAMS = [
8278
    _PNodeName,
8279
    ("storage_type", ht.NoDefault, _CheckStorageType),
8280
    ("name", ht.NoDefault, ht.TNonEmptyString),
8281
    ("ignore_consistency", False, ht.TBool),
8282
    ]
8283
  REQ_BGL = False
8284

    
8285
  def CheckArguments(self):
8286
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8287

    
8288
    storage_type = self.op.storage_type
8289

    
8290
    if (constants.SO_FIX_CONSISTENCY not in
8291
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8292
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8293
                                 " repaired" % storage_type,
8294
                                 errors.ECODE_INVAL)
8295

    
8296
  def ExpandNames(self):
8297
    self.needed_locks = {
8298
      locking.LEVEL_NODE: [self.op.node_name],
8299
      }
8300

    
8301
  def _CheckFaultyDisks(self, instance, node_name):
8302
    """Ensure faulty disks abort the opcode or at least warn."""
8303
    try:
8304
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8305
                                  node_name, True):
8306
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8307
                                   " node '%s'" % (instance.name, node_name),
8308
                                   errors.ECODE_STATE)
8309
    except errors.OpPrereqError, err:
8310
      if self.op.ignore_consistency:
8311
        self.proc.LogWarning(str(err.args[0]))
8312
      else:
8313
        raise
8314

    
8315
  def CheckPrereq(self):
8316
    """Check prerequisites.
8317

8318
    """
8319
    # Check whether any instance on this node has faulty disks
8320
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8321
      if not inst.admin_up:
8322
        continue
8323
      check_nodes = set(inst.all_nodes)
8324
      check_nodes.discard(self.op.node_name)
8325
      for inst_node_name in check_nodes:
8326
        self._CheckFaultyDisks(inst, inst_node_name)
8327

    
8328
  def Exec(self, feedback_fn):
8329
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8330
                (self.op.name, self.op.node_name))
8331

    
8332
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8333
    result = self.rpc.call_storage_execute(self.op.node_name,
8334
                                           self.op.storage_type, st_args,
8335
                                           self.op.name,
8336
                                           constants.SO_FIX_CONSISTENCY)
8337
    result.Raise("Failed to repair storage unit '%s' on %s" %
8338
                 (self.op.name, self.op.node_name))
8339

    
8340

    
8341
class LUNodeEvacuationStrategy(NoHooksLU):
8342
  """Computes the node evacuation strategy.
8343

8344
  """
8345
  _OP_PARAMS = [
8346
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8347
    ("remote_node", None, ht.TMaybeString),
8348
    ("iallocator", None, ht.TMaybeString),
8349
    ]
8350
  REQ_BGL = False
8351

    
8352
  def CheckArguments(self):
8353
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8354

    
8355
  def ExpandNames(self):
8356
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8357
    self.needed_locks = locks = {}
8358
    if self.op.remote_node is None:
8359
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8360
    else:
8361
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8362
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8363

    
8364
  def Exec(self, feedback_fn):
8365
    if self.op.remote_node is not None:
8366
      instances = []
8367
      for node in self.op.nodes:
8368
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8369
      result = []
8370
      for i in instances:
8371
        if i.primary_node == self.op.remote_node:
8372
          raise errors.OpPrereqError("Node %s is the primary node of"
8373
                                     " instance %s, cannot use it as"
8374
                                     " secondary" %
8375
                                     (self.op.remote_node, i.name),
8376
                                     errors.ECODE_INVAL)
8377
        result.append([i.name, self.op.remote_node])
8378
    else:
8379
      ial = IAllocator(self.cfg, self.rpc,
8380
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8381
                       evac_nodes=self.op.nodes)
8382
      ial.Run(self.op.iallocator, validate=True)
8383
      if not ial.success:
8384
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8385
                                 errors.ECODE_NORES)
8386
      result = ial.result
8387
    return result
8388

    
8389

    
8390
class LUGrowDisk(LogicalUnit):
8391
  """Grow a disk of an instance.
8392

8393
  """
8394
  HPATH = "disk-grow"
8395
  HTYPE = constants.HTYPE_INSTANCE
8396
  _OP_PARAMS = [
8397
    _PInstanceName,
8398
    ("disk", ht.NoDefault, ht.TInt),
8399
    ("amount", ht.NoDefault, ht.TInt),
8400
    ("wait_for_sync", True, ht.TBool),
8401
    ]
8402
  REQ_BGL = False
8403

    
8404
  def ExpandNames(self):
8405
    self._ExpandAndLockInstance()
8406
    self.needed_locks[locking.LEVEL_NODE] = []
8407
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8408

    
8409
  def DeclareLocks(self, level):
8410
    if level == locking.LEVEL_NODE:
8411
      self._LockInstancesNodes()
8412

    
8413
  def BuildHooksEnv(self):
8414
    """Build hooks env.
8415

8416
    This runs on the master, the primary and all the secondaries.
8417

8418
    """
8419
    env = {
8420
      "DISK": self.op.disk,
8421
      "AMOUNT": self.op.amount,
8422
      }
8423
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8424
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8425
    return env, nl, nl
8426

    
8427
  def CheckPrereq(self):
8428
    """Check prerequisites.
8429

8430
    This checks that the instance is in the cluster.
8431

8432
    """
8433
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8434
    assert instance is not None, \
8435
      "Cannot retrieve locked instance %s" % self.op.instance_name
8436
    nodenames = list(instance.all_nodes)
8437
    for node in nodenames:
8438
      _CheckNodeOnline(self, node)
8439

    
8440
    self.instance = instance
8441

    
8442
    if instance.disk_template not in constants.DTS_GROWABLE:
8443
      raise errors.OpPrereqError("Instance's disk layout does not support"
8444
                                 " growing.", errors.ECODE_INVAL)
8445

    
8446
    self.disk = instance.FindDisk(self.op.disk)
8447

    
8448
    if instance.disk_template != constants.DT_FILE:
8449
      # TODO: check the free disk space for file, when that feature will be
8450
      # supported
8451
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8452

    
8453
  def Exec(self, feedback_fn):
8454
    """Execute disk grow.
8455

8456
    """
8457
    instance = self.instance
8458
    disk = self.disk
8459

    
8460
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8461
    if not disks_ok:
8462
      raise errors.OpExecError("Cannot activate block device to grow")
8463

    
8464
    for node in instance.all_nodes:
8465
      self.cfg.SetDiskID(disk, node)
8466
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8467
      result.Raise("Grow request failed to node %s" % node)
8468

    
8469
      # TODO: Rewrite code to work properly
8470
      # DRBD goes into sync mode for a short amount of time after executing the
8471
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8472
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8473
      # time is a work-around.
8474
      time.sleep(5)
8475

    
8476
    disk.RecordGrow(self.op.amount)
8477
    self.cfg.Update(instance, feedback_fn)
8478
    if self.op.wait_for_sync:
8479
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8480
      if disk_abort:
8481
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8482
                             " status.\nPlease check the instance.")
8483
      if not instance.admin_up:
8484
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8485
    elif not instance.admin_up:
8486
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8487
                           " not supposed to be running because no wait for"
8488
                           " sync mode was requested.")
8489

    
8490

    
8491
class LUQueryInstanceData(NoHooksLU):
8492
  """Query runtime instance data.
8493

8494
  """
8495
  _OP_PARAMS = [
8496
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8497
    ("static", False, ht.TBool),
8498
    ]
8499
  REQ_BGL = False
8500

    
8501
  def ExpandNames(self):
8502
    self.needed_locks = {}
8503
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8504

    
8505
    if self.op.instances:
8506
      self.wanted_names = []
8507
      for name in self.op.instances:
8508
        full_name = _ExpandInstanceName(self.cfg, name)
8509
        self.wanted_names.append(full_name)
8510
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8511
    else:
8512
      self.wanted_names = None
8513
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8514

    
8515
    self.needed_locks[locking.LEVEL_NODE] = []
8516
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8517

    
8518
  def DeclareLocks(self, level):
8519
    if level == locking.LEVEL_NODE:
8520
      self._LockInstancesNodes()
8521

    
8522
  def CheckPrereq(self):
8523
    """Check prerequisites.
8524

8525
    This only checks the optional instance list against the existing names.
8526

8527
    """
8528
    if self.wanted_names is None:
8529
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8530

    
8531
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8532
                             in self.wanted_names]
8533

    
8534
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8535
    """Returns the status of a block device
8536

8537
    """
8538
    if self.op.static or not node:
8539
      return None
8540

    
8541
    self.cfg.SetDiskID(dev, node)
8542

    
8543
    result = self.rpc.call_blockdev_find(node, dev)
8544
    if result.offline:
8545
      return None
8546

    
8547
    result.Raise("Can't compute disk status for %s" % instance_name)
8548

    
8549
    status = result.payload
8550
    if status is None:
8551
      return None
8552

    
8553
    return (status.dev_path, status.major, status.minor,
8554
            status.sync_percent, status.estimated_time,
8555
            status.is_degraded, status.ldisk_status)
8556

    
8557
  def _ComputeDiskStatus(self, instance, snode, dev):
8558
    """Compute block device status.
8559

8560
    """
8561
    if dev.dev_type in constants.LDS_DRBD:
8562
      # we change the snode then (otherwise we use the one passed in)
8563
      if dev.logical_id[0] == instance.primary_node:
8564
        snode = dev.logical_id[1]
8565
      else:
8566
        snode = dev.logical_id[0]
8567

    
8568
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8569
                                              instance.name, dev)
8570
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8571

    
8572
    if dev.children:
8573
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8574
                      for child in dev.children]
8575
    else:
8576
      dev_children = []
8577

    
8578
    data = {
8579
      "iv_name": dev.iv_name,
8580
      "dev_type": dev.dev_type,
8581
      "logical_id": dev.logical_id,
8582
      "physical_id": dev.physical_id,
8583
      "pstatus": dev_pstatus,
8584
      "sstatus": dev_sstatus,
8585
      "children": dev_children,
8586
      "mode": dev.mode,
8587
      "size": dev.size,
8588
      }
8589

    
8590
    return data
8591

    
8592
  def Exec(self, feedback_fn):
8593
    """Gather and return data"""
8594
    result = {}
8595

    
8596
    cluster = self.cfg.GetClusterInfo()
8597

    
8598
    for instance in self.wanted_instances:
8599
      if not self.op.static:
8600
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8601
                                                  instance.name,
8602
                                                  instance.hypervisor)
8603
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8604
        remote_info = remote_info.payload
8605
        if remote_info and "state" in remote_info:
8606
          remote_state = "up"
8607
        else:
8608
          remote_state = "down"
8609
      else:
8610
        remote_state = None
8611
      if instance.admin_up:
8612
        config_state = "up"
8613
      else:
8614
        config_state = "down"
8615

    
8616
      disks = [self._ComputeDiskStatus(instance, None, device)
8617
               for device in instance.disks]
8618

    
8619
      idict = {
8620
        "name": instance.name,
8621
        "config_state": config_state,
8622
        "run_state": remote_state,
8623
        "pnode": instance.primary_node,
8624
        "snodes": instance.secondary_nodes,
8625
        "os": instance.os,
8626
        # this happens to be the same format used for hooks
8627
        "nics": _NICListToTuple(self, instance.nics),
8628
        "disk_template": instance.disk_template,
8629
        "disks": disks,
8630
        "hypervisor": instance.hypervisor,
8631
        "network_port": instance.network_port,
8632
        "hv_instance": instance.hvparams,
8633
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8634
        "be_instance": instance.beparams,
8635
        "be_actual": cluster.FillBE(instance),
8636
        "os_instance": instance.osparams,
8637
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8638
        "serial_no": instance.serial_no,
8639
        "mtime": instance.mtime,
8640
        "ctime": instance.ctime,
8641
        "uuid": instance.uuid,
8642
        }
8643

    
8644
      result[instance.name] = idict
8645

    
8646
    return result
8647

    
8648

    
8649
class LUSetInstanceParams(LogicalUnit):
8650
  """Modifies an instances's parameters.
8651

8652
  """
8653
  HPATH = "instance-modify"
8654
  HTYPE = constants.HTYPE_INSTANCE
8655
  _OP_PARAMS = [
8656
    _PInstanceName,
8657
    ("nics", ht.EmptyList, ht.TList),
8658
    ("disks", ht.EmptyList, ht.TList),
8659
    ("beparams", ht.EmptyDict, ht.TDict),
8660
    ("hvparams", ht.EmptyDict, ht.TDict),
8661
    ("disk_template", None, ht.TMaybeString),
8662
    ("remote_node", None, ht.TMaybeString),
8663
    ("os_name", None, ht.TMaybeString),
8664
    ("force_variant", False, ht.TBool),
8665
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8666
    _PForce,
8667
    ]
8668
  REQ_BGL = False
8669

    
8670
  def CheckArguments(self):
8671
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8672
            self.op.hvparams or self.op.beparams or self.op.os_name):
8673
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8674

    
8675
    if self.op.hvparams:
8676
      _CheckGlobalHvParams(self.op.hvparams)
8677

    
8678
    # Disk validation
8679
    disk_addremove = 0
8680
    for disk_op, disk_dict in self.op.disks:
8681
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8682
      if disk_op == constants.DDM_REMOVE:
8683
        disk_addremove += 1
8684
        continue
8685
      elif disk_op == constants.DDM_ADD:
8686
        disk_addremove += 1
8687
      else:
8688
        if not isinstance(disk_op, int):
8689
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8690
        if not isinstance(disk_dict, dict):
8691
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8692
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8693

    
8694
      if disk_op == constants.DDM_ADD:
8695
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8696
        if mode not in constants.DISK_ACCESS_SET:
8697
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8698
                                     errors.ECODE_INVAL)
8699
        size = disk_dict.get('size', None)
8700
        if size is None:
8701
          raise errors.OpPrereqError("Required disk parameter size missing",
8702
                                     errors.ECODE_INVAL)
8703
        try:
8704
          size = int(size)
8705
        except (TypeError, ValueError), err:
8706
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8707
                                     str(err), errors.ECODE_INVAL)
8708
        disk_dict['size'] = size
8709
      else:
8710
        # modification of disk
8711
        if 'size' in disk_dict:
8712
          raise errors.OpPrereqError("Disk size change not possible, use"
8713
                                     " grow-disk", errors.ECODE_INVAL)
8714

    
8715
    if disk_addremove > 1:
8716
      raise errors.OpPrereqError("Only one disk add or remove operation"
8717
                                 " supported at a time", errors.ECODE_INVAL)
8718

    
8719
    if self.op.disks and self.op.disk_template is not None:
8720
      raise errors.OpPrereqError("Disk template conversion and other disk"
8721
                                 " changes not supported at the same time",
8722
                                 errors.ECODE_INVAL)
8723

    
8724
    if self.op.disk_template:
8725
      _CheckDiskTemplate(self.op.disk_template)
8726
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8727
          self.op.remote_node is None):
8728
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8729
                                   " one requires specifying a secondary node",
8730
                                   errors.ECODE_INVAL)
8731

    
8732
    # NIC validation
8733
    nic_addremove = 0
8734
    for nic_op, nic_dict in self.op.nics:
8735
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8736
      if nic_op == constants.DDM_REMOVE:
8737
        nic_addremove += 1
8738
        continue
8739
      elif nic_op == constants.DDM_ADD:
8740
        nic_addremove += 1
8741
      else:
8742
        if not isinstance(nic_op, int):
8743
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8744
        if not isinstance(nic_dict, dict):
8745
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8746
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8747

    
8748
      # nic_dict should be a dict
8749
      nic_ip = nic_dict.get('ip', None)
8750
      if nic_ip is not None:
8751
        if nic_ip.lower() == constants.VALUE_NONE:
8752
          nic_dict['ip'] = None
8753
        else:
8754
          if not netutils.IPAddress.IsValid(nic_ip):
8755
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8756
                                       errors.ECODE_INVAL)
8757

    
8758
      nic_bridge = nic_dict.get('bridge', None)
8759
      nic_link = nic_dict.get('link', None)
8760
      if nic_bridge and nic_link:
8761
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8762
                                   " at the same time", errors.ECODE_INVAL)
8763
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8764
        nic_dict['bridge'] = None
8765
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8766
        nic_dict['link'] = None
8767

    
8768
      if nic_op == constants.DDM_ADD:
8769
        nic_mac = nic_dict.get('mac', None)
8770
        if nic_mac is None:
8771
          nic_dict['mac'] = constants.VALUE_AUTO
8772

    
8773
      if 'mac' in nic_dict:
8774
        nic_mac = nic_dict['mac']
8775
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8776
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8777

    
8778
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8779
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8780
                                     " modifying an existing nic",
8781
                                     errors.ECODE_INVAL)
8782

    
8783
    if nic_addremove > 1:
8784
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8785
                                 " supported at a time", errors.ECODE_INVAL)
8786

    
8787
  def ExpandNames(self):
8788
    self._ExpandAndLockInstance()
8789
    self.needed_locks[locking.LEVEL_NODE] = []
8790
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8791

    
8792
  def DeclareLocks(self, level):
8793
    if level == locking.LEVEL_NODE:
8794
      self._LockInstancesNodes()
8795
      if self.op.disk_template and self.op.remote_node:
8796
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8797
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8798

    
8799
  def BuildHooksEnv(self):
8800
    """Build hooks env.
8801

8802
    This runs on the master, primary and secondaries.
8803

8804
    """
8805
    args = dict()
8806
    if constants.BE_MEMORY in self.be_new:
8807
      args['memory'] = self.be_new[constants.BE_MEMORY]
8808
    if constants.BE_VCPUS in self.be_new:
8809
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8810
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8811
    # information at all.
8812
    if self.op.nics:
8813
      args['nics'] = []
8814
      nic_override = dict(self.op.nics)
8815
      for idx, nic in enumerate(self.instance.nics):
8816
        if idx in nic_override:
8817
          this_nic_override = nic_override[idx]
8818
        else:
8819
          this_nic_override = {}
8820
        if 'ip' in this_nic_override:
8821
          ip = this_nic_override['ip']
8822
        else:
8823
          ip = nic.ip
8824
        if 'mac' in this_nic_override:
8825
          mac = this_nic_override['mac']
8826
        else:
8827
          mac = nic.mac
8828
        if idx in self.nic_pnew:
8829
          nicparams = self.nic_pnew[idx]
8830
        else:
8831
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8832
        mode = nicparams[constants.NIC_MODE]
8833
        link = nicparams[constants.NIC_LINK]
8834
        args['nics'].append((ip, mac, mode, link))
8835
      if constants.DDM_ADD in nic_override:
8836
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8837
        mac = nic_override[constants.DDM_ADD]['mac']
8838
        nicparams = self.nic_pnew[constants.DDM_ADD]
8839
        mode = nicparams[constants.NIC_MODE]
8840
        link = nicparams[constants.NIC_LINK]
8841
        args['nics'].append((ip, mac, mode, link))
8842
      elif constants.DDM_REMOVE in nic_override:
8843
        del args['nics'][-1]
8844

    
8845
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8846
    if self.op.disk_template:
8847
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8848
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8849
    return env, nl, nl
8850

    
8851
  def CheckPrereq(self):
8852
    """Check prerequisites.
8853

8854
    This only checks the instance list against the existing names.
8855

8856
    """
8857
    # checking the new params on the primary/secondary nodes
8858

    
8859
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8860
    cluster = self.cluster = self.cfg.GetClusterInfo()
8861
    assert self.instance is not None, \
8862
      "Cannot retrieve locked instance %s" % self.op.instance_name
8863
    pnode = instance.primary_node
8864
    nodelist = list(instance.all_nodes)
8865

    
8866
    # OS change
8867
    if self.op.os_name and not self.op.force:
8868
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8869
                      self.op.force_variant)
8870
      instance_os = self.op.os_name
8871
    else:
8872
      instance_os = instance.os
8873

    
8874
    if self.op.disk_template:
8875
      if instance.disk_template == self.op.disk_template:
8876
        raise errors.OpPrereqError("Instance already has disk template %s" %
8877
                                   instance.disk_template, errors.ECODE_INVAL)
8878

    
8879
      if (instance.disk_template,
8880
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8881
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8882
                                   " %s to %s" % (instance.disk_template,
8883
                                                  self.op.disk_template),
8884
                                   errors.ECODE_INVAL)
8885
      _CheckInstanceDown(self, instance, "cannot change disk template")
8886
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8887
        if self.op.remote_node == pnode:
8888
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8889
                                     " as the primary node of the instance" %
8890
                                     self.op.remote_node, errors.ECODE_STATE)
8891
        _CheckNodeOnline(self, self.op.remote_node)
8892
        _CheckNodeNotDrained(self, self.op.remote_node)
8893
        disks = [{"size": d.size} for d in instance.disks]
8894
        required = _ComputeDiskSize(self.op.disk_template, disks)
8895
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8896

    
8897
    # hvparams processing
8898
    if self.op.hvparams:
8899
      hv_type = instance.hypervisor
8900
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8901
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8902
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8903

    
8904
      # local check
8905
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8906
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8907
      self.hv_new = hv_new # the new actual values
8908
      self.hv_inst = i_hvdict # the new dict (without defaults)
8909
    else:
8910
      self.hv_new = self.hv_inst = {}
8911

    
8912
    # beparams processing
8913
    if self.op.beparams:
8914
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8915
                                   use_none=True)
8916
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8917
      be_new = cluster.SimpleFillBE(i_bedict)
8918
      self.be_new = be_new # the new actual values
8919
      self.be_inst = i_bedict # the new dict (without defaults)
8920
    else:
8921
      self.be_new = self.be_inst = {}
8922

    
8923
    # osparams processing
8924
    if self.op.osparams:
8925
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8926
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8927
      self.os_inst = i_osdict # the new dict (without defaults)
8928
    else:
8929
      self.os_inst = {}
8930

    
8931
    self.warn = []
8932

    
8933
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8934
      mem_check_list = [pnode]
8935
      if be_new[constants.BE_AUTO_BALANCE]:
8936
        # either we changed auto_balance to yes or it was from before
8937
        mem_check_list.extend(instance.secondary_nodes)
8938
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8939
                                                  instance.hypervisor)
8940
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8941
                                         instance.hypervisor)
8942
      pninfo = nodeinfo[pnode]
8943
      msg = pninfo.fail_msg
8944
      if msg:
8945
        # Assume the primary node is unreachable and go ahead
8946
        self.warn.append("Can't get info from primary node %s: %s" %
8947
                         (pnode,  msg))
8948
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8949
        self.warn.append("Node data from primary node %s doesn't contain"
8950
                         " free memory information" % pnode)
8951
      elif instance_info.fail_msg:
8952
        self.warn.append("Can't get instance runtime information: %s" %
8953
                        instance_info.fail_msg)
8954
      else:
8955
        if instance_info.payload:
8956
          current_mem = int(instance_info.payload['memory'])
8957
        else:
8958
          # Assume instance not running
8959
          # (there is a slight race condition here, but it's not very probable,
8960
          # and we have no other way to check)
8961
          current_mem = 0
8962
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8963
                    pninfo.payload['memory_free'])
8964
        if miss_mem > 0:
8965
          raise errors.OpPrereqError("This change will prevent the instance"
8966
                                     " from starting, due to %d MB of memory"
8967
                                     " missing on its primary node" % miss_mem,
8968
                                     errors.ECODE_NORES)
8969

    
8970
      if be_new[constants.BE_AUTO_BALANCE]:
8971
        for node, nres in nodeinfo.items():
8972
          if node not in instance.secondary_nodes:
8973
            continue
8974
          msg = nres.fail_msg
8975
          if msg:
8976
            self.warn.append("Can't get info from secondary node %s: %s" %
8977
                             (node, msg))
8978
          elif not isinstance(nres.payload.get('memory_free', None), int):
8979
            self.warn.append("Secondary node %s didn't return free"
8980
                             " memory information" % node)
8981
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8982
            self.warn.append("Not enough memory to failover instance to"
8983
                             " secondary node %s" % node)
8984

    
8985
    # NIC processing
8986
    self.nic_pnew = {}
8987
    self.nic_pinst = {}
8988
    for nic_op, nic_dict in self.op.nics:
8989
      if nic_op == constants.DDM_REMOVE:
8990
        if not instance.nics:
8991
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8992
                                     errors.ECODE_INVAL)
8993
        continue
8994
      if nic_op != constants.DDM_ADD:
8995
        # an existing nic
8996
        if not instance.nics:
8997
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8998
                                     " no NICs" % nic_op,
8999
                                     errors.ECODE_INVAL)
9000
        if nic_op < 0 or nic_op >= len(instance.nics):
9001
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9002
                                     " are 0 to %d" %
9003
                                     (nic_op, len(instance.nics) - 1),
9004
                                     errors.ECODE_INVAL)
9005
        old_nic_params = instance.nics[nic_op].nicparams
9006
        old_nic_ip = instance.nics[nic_op].ip
9007
      else:
9008
        old_nic_params = {}
9009
        old_nic_ip = None
9010

    
9011
      update_params_dict = dict([(key, nic_dict[key])
9012
                                 for key in constants.NICS_PARAMETERS
9013
                                 if key in nic_dict])
9014

    
9015
      if 'bridge' in nic_dict:
9016
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9017

    
9018
      new_nic_params = _GetUpdatedParams(old_nic_params,
9019
                                         update_params_dict)
9020
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9021
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9022
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9023
      self.nic_pinst[nic_op] = new_nic_params
9024
      self.nic_pnew[nic_op] = new_filled_nic_params
9025
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9026

    
9027
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9028
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9029
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9030
        if msg:
9031
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9032
          if self.op.force:
9033
            self.warn.append(msg)
9034
          else:
9035
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9036
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9037
        if 'ip' in nic_dict:
9038
          nic_ip = nic_dict['ip']
9039
        else:
9040
          nic_ip = old_nic_ip
9041
        if nic_ip is None:
9042
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9043
                                     ' on a routed nic', errors.ECODE_INVAL)
9044
      if 'mac' in nic_dict:
9045
        nic_mac = nic_dict['mac']
9046
        if nic_mac is None:
9047
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9048
                                     errors.ECODE_INVAL)
9049
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9050
          # otherwise generate the mac
9051
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9052
        else:
9053
          # or validate/reserve the current one
9054
          try:
9055
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9056
          except errors.ReservationError:
9057
            raise errors.OpPrereqError("MAC address %s already in use"
9058
                                       " in cluster" % nic_mac,
9059
                                       errors.ECODE_NOTUNIQUE)
9060

    
9061
    # DISK processing
9062
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9063
      raise errors.OpPrereqError("Disk operations not supported for"
9064
                                 " diskless instances",
9065
                                 errors.ECODE_INVAL)
9066
    for disk_op, _ in self.op.disks:
9067
      if disk_op == constants.DDM_REMOVE:
9068
        if len(instance.disks) == 1:
9069
          raise errors.OpPrereqError("Cannot remove the last disk of"
9070
                                     " an instance", errors.ECODE_INVAL)
9071
        _CheckInstanceDown(self, instance, "cannot remove disks")
9072

    
9073
      if (disk_op == constants.DDM_ADD and
9074
          len(instance.nics) >= constants.MAX_DISKS):
9075
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9076
                                   " add more" % constants.MAX_DISKS,
9077
                                   errors.ECODE_STATE)
9078
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9079
        # an existing disk
9080
        if disk_op < 0 or disk_op >= len(instance.disks):
9081
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9082
                                     " are 0 to %d" %
9083
                                     (disk_op, len(instance.disks)),
9084
                                     errors.ECODE_INVAL)
9085

    
9086
    return
9087

    
9088
  def _ConvertPlainToDrbd(self, feedback_fn):
9089
    """Converts an instance from plain to drbd.
9090

9091
    """
9092
    feedback_fn("Converting template to drbd")
9093
    instance = self.instance
9094
    pnode = instance.primary_node
9095
    snode = self.op.remote_node
9096

    
9097
    # create a fake disk info for _GenerateDiskTemplate
9098
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9099
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9100
                                      instance.name, pnode, [snode],
9101
                                      disk_info, None, None, 0)
9102
    info = _GetInstanceInfoText(instance)
9103
    feedback_fn("Creating aditional volumes...")
9104
    # first, create the missing data and meta devices
9105
    for disk in new_disks:
9106
      # unfortunately this is... not too nice
9107
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9108
                            info, True)
9109
      for child in disk.children:
9110
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9111
    # at this stage, all new LVs have been created, we can rename the
9112
    # old ones
9113
    feedback_fn("Renaming original volumes...")
9114
    rename_list = [(o, n.children[0].logical_id)
9115
                   for (o, n) in zip(instance.disks, new_disks)]
9116
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9117
    result.Raise("Failed to rename original LVs")
9118

    
9119
    feedback_fn("Initializing DRBD devices...")
9120
    # all child devices are in place, we can now create the DRBD devices
9121
    for disk in new_disks:
9122
      for node in [pnode, snode]:
9123
        f_create = node == pnode
9124
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9125

    
9126
    # at this point, the instance has been modified
9127
    instance.disk_template = constants.DT_DRBD8
9128
    instance.disks = new_disks
9129
    self.cfg.Update(instance, feedback_fn)
9130

    
9131
    # disks are created, waiting for sync
9132
    disk_abort = not _WaitForSync(self, instance)
9133
    if disk_abort:
9134
      raise errors.OpExecError("There are some degraded disks for"
9135
                               " this instance, please cleanup manually")
9136

    
9137
  def _ConvertDrbdToPlain(self, feedback_fn):
9138
    """Converts an instance from drbd to plain.
9139

9140
    """
9141
    instance = self.instance
9142
    assert len(instance.secondary_nodes) == 1
9143
    pnode = instance.primary_node
9144
    snode = instance.secondary_nodes[0]
9145
    feedback_fn("Converting template to plain")
9146

    
9147
    old_disks = instance.disks
9148
    new_disks = [d.children[0] for d in old_disks]
9149

    
9150
    # copy over size and mode
9151
    for parent, child in zip(old_disks, new_disks):
9152
      child.size = parent.size
9153
      child.mode = parent.mode
9154

    
9155
    # update instance structure
9156
    instance.disks = new_disks
9157
    instance.disk_template = constants.DT_PLAIN
9158
    self.cfg.Update(instance, feedback_fn)
9159

    
9160
    feedback_fn("Removing volumes on the secondary node...")
9161
    for disk in old_disks:
9162
      self.cfg.SetDiskID(disk, snode)
9163
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9164
      if msg:
9165
        self.LogWarning("Could not remove block device %s on node %s,"
9166
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9167

    
9168
    feedback_fn("Removing unneeded volumes on the primary node...")
9169
    for idx, disk in enumerate(old_disks):
9170
      meta = disk.children[1]
9171
      self.cfg.SetDiskID(meta, pnode)
9172
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9173
      if msg:
9174
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9175
                        " continuing anyway: %s", idx, pnode, msg)
9176

    
9177

    
9178
  def Exec(self, feedback_fn):
9179
    """Modifies an instance.
9180

9181
    All parameters take effect only at the next restart of the instance.
9182

9183
    """
9184
    # Process here the warnings from CheckPrereq, as we don't have a
9185
    # feedback_fn there.
9186
    for warn in self.warn:
9187
      feedback_fn("WARNING: %s" % warn)
9188

    
9189
    result = []
9190
    instance = self.instance
9191
    # disk changes
9192
    for disk_op, disk_dict in self.op.disks:
9193
      if disk_op == constants.DDM_REMOVE:
9194
        # remove the last disk
9195
        device = instance.disks.pop()
9196
        device_idx = len(instance.disks)
9197
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9198
          self.cfg.SetDiskID(disk, node)
9199
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9200
          if msg:
9201
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9202
                            " continuing anyway", device_idx, node, msg)
9203
        result.append(("disk/%d" % device_idx, "remove"))
9204
      elif disk_op == constants.DDM_ADD:
9205
        # add a new disk
9206
        if instance.disk_template == constants.DT_FILE:
9207
          file_driver, file_path = instance.disks[0].logical_id
9208
          file_path = os.path.dirname(file_path)
9209
        else:
9210
          file_driver = file_path = None
9211
        disk_idx_base = len(instance.disks)
9212
        new_disk = _GenerateDiskTemplate(self,
9213
                                         instance.disk_template,
9214
                                         instance.name, instance.primary_node,
9215
                                         instance.secondary_nodes,
9216
                                         [disk_dict],
9217
                                         file_path,
9218
                                         file_driver,
9219
                                         disk_idx_base)[0]
9220
        instance.disks.append(new_disk)
9221
        info = _GetInstanceInfoText(instance)
9222

    
9223
        logging.info("Creating volume %s for instance %s",
9224
                     new_disk.iv_name, instance.name)
9225
        # Note: this needs to be kept in sync with _CreateDisks
9226
        #HARDCODE
9227
        for node in instance.all_nodes:
9228
          f_create = node == instance.primary_node
9229
          try:
9230
            _CreateBlockDev(self, node, instance, new_disk,
9231
                            f_create, info, f_create)
9232
          except errors.OpExecError, err:
9233
            self.LogWarning("Failed to create volume %s (%s) on"
9234
                            " node %s: %s",
9235
                            new_disk.iv_name, new_disk, node, err)
9236
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9237
                       (new_disk.size, new_disk.mode)))
9238
      else:
9239
        # change a given disk
9240
        instance.disks[disk_op].mode = disk_dict['mode']
9241
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9242

    
9243
    if self.op.disk_template:
9244
      r_shut = _ShutdownInstanceDisks(self, instance)
9245
      if not r_shut:
9246
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9247
                                 " proceed with disk template conversion")
9248
      mode = (instance.disk_template, self.op.disk_template)
9249
      try:
9250
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9251
      except:
9252
        self.cfg.ReleaseDRBDMinors(instance.name)
9253
        raise
9254
      result.append(("disk_template", self.op.disk_template))
9255

    
9256
    # NIC changes
9257
    for nic_op, nic_dict in self.op.nics:
9258
      if nic_op == constants.DDM_REMOVE:
9259
        # remove the last nic
9260
        del instance.nics[-1]
9261
        result.append(("nic.%d" % len(instance.nics), "remove"))
9262
      elif nic_op == constants.DDM_ADD:
9263
        # mac and bridge should be set, by now
9264
        mac = nic_dict['mac']
9265
        ip = nic_dict.get('ip', None)
9266
        nicparams = self.nic_pinst[constants.DDM_ADD]
9267
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9268
        instance.nics.append(new_nic)
9269
        result.append(("nic.%d" % (len(instance.nics) - 1),
9270
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9271
                       (new_nic.mac, new_nic.ip,
9272
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9273
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9274
                       )))
9275
      else:
9276
        for key in 'mac', 'ip':
9277
          if key in nic_dict:
9278
            setattr(instance.nics[nic_op], key, nic_dict[key])
9279
        if nic_op in self.nic_pinst:
9280
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9281
        for key, val in nic_dict.iteritems():
9282
          result.append(("nic.%s/%d" % (key, nic_op), val))
9283

    
9284
    # hvparams changes
9285
    if self.op.hvparams:
9286
      instance.hvparams = self.hv_inst
9287
      for key, val in self.op.hvparams.iteritems():
9288
        result.append(("hv/%s" % key, val))
9289

    
9290
    # beparams changes
9291
    if self.op.beparams:
9292
      instance.beparams = self.be_inst
9293
      for key, val in self.op.beparams.iteritems():
9294
        result.append(("be/%s" % key, val))
9295

    
9296
    # OS change
9297
    if self.op.os_name:
9298
      instance.os = self.op.os_name
9299

    
9300
    # osparams changes
9301
    if self.op.osparams:
9302
      instance.osparams = self.os_inst
9303
      for key, val in self.op.osparams.iteritems():
9304
        result.append(("os/%s" % key, val))
9305

    
9306
    self.cfg.Update(instance, feedback_fn)
9307

    
9308
    return result
9309

    
9310
  _DISK_CONVERSIONS = {
9311
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9312
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9313
    }
9314

    
9315

    
9316
class LUQueryExports(NoHooksLU):
9317
  """Query the exports list
9318

9319
  """
9320
  _OP_PARAMS = [
9321
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9322
    ("use_locking", False, ht.TBool),
9323
    ]
9324
  REQ_BGL = False
9325

    
9326
  def ExpandNames(self):
9327
    self.needed_locks = {}
9328
    self.share_locks[locking.LEVEL_NODE] = 1
9329
    if not self.op.nodes:
9330
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9331
    else:
9332
      self.needed_locks[locking.LEVEL_NODE] = \
9333
        _GetWantedNodes(self, self.op.nodes)
9334

    
9335
  def Exec(self, feedback_fn):
9336
    """Compute the list of all the exported system images.
9337

9338
    @rtype: dict
9339
    @return: a dictionary with the structure node->(export-list)
9340
        where export-list is a list of the instances exported on
9341
        that node.
9342

9343
    """
9344
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9345
    rpcresult = self.rpc.call_export_list(self.nodes)
9346
    result = {}
9347
    for node in rpcresult:
9348
      if rpcresult[node].fail_msg:
9349
        result[node] = False
9350
      else:
9351
        result[node] = rpcresult[node].payload
9352

    
9353
    return result
9354

    
9355

    
9356
class LUPrepareExport(NoHooksLU):
9357
  """Prepares an instance for an export and returns useful information.
9358

9359
  """
9360
  _OP_PARAMS = [
9361
    _PInstanceName,
9362
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9363
    ]
9364
  REQ_BGL = False
9365

    
9366
  def ExpandNames(self):
9367
    self._ExpandAndLockInstance()
9368

    
9369
  def CheckPrereq(self):
9370
    """Check prerequisites.
9371

9372
    """
9373
    instance_name = self.op.instance_name
9374

    
9375
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9376
    assert self.instance is not None, \
9377
          "Cannot retrieve locked instance %s" % self.op.instance_name
9378
    _CheckNodeOnline(self, self.instance.primary_node)
9379

    
9380
    self._cds = _GetClusterDomainSecret()
9381

    
9382
  def Exec(self, feedback_fn):
9383
    """Prepares an instance for an export.
9384

9385
    """
9386
    instance = self.instance
9387

    
9388
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9389
      salt = utils.GenerateSecret(8)
9390

    
9391
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9392
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9393
                                              constants.RIE_CERT_VALIDITY)
9394
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9395

    
9396
      (name, cert_pem) = result.payload
9397

    
9398
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9399
                                             cert_pem)
9400

    
9401
      return {
9402
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9403
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9404
                          salt),
9405
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9406
        }
9407

    
9408
    return None
9409

    
9410

    
9411
class LUExportInstance(LogicalUnit):
9412
  """Export an instance to an image in the cluster.
9413

9414
  """
9415
  HPATH = "instance-export"
9416
  HTYPE = constants.HTYPE_INSTANCE
9417
  _OP_PARAMS = [
9418
    _PInstanceName,
9419
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9420
    ("shutdown", True, ht.TBool),
9421
    _PShutdownTimeout,
9422
    ("remove_instance", False, ht.TBool),
9423
    ("ignore_remove_failures", False, ht.TBool),
9424
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9425
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9426
    ("destination_x509_ca", None, ht.TMaybeString),
9427
    ]
9428
  REQ_BGL = False
9429

    
9430
  def CheckArguments(self):
9431
    """Check the arguments.
9432

9433
    """
9434
    self.x509_key_name = self.op.x509_key_name
9435
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9436

    
9437
    if self.op.remove_instance and not self.op.shutdown:
9438
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9439
                                 " down before")
9440

    
9441
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9442
      if not self.x509_key_name:
9443
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9444
                                   errors.ECODE_INVAL)
9445

    
9446
      if not self.dest_x509_ca_pem:
9447
        raise errors.OpPrereqError("Missing destination X509 CA",
9448
                                   errors.ECODE_INVAL)
9449

    
9450
  def ExpandNames(self):
9451
    self._ExpandAndLockInstance()
9452

    
9453
    # Lock all nodes for local exports
9454
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9455
      # FIXME: lock only instance primary and destination node
9456
      #
9457
      # Sad but true, for now we have do lock all nodes, as we don't know where
9458
      # the previous export might be, and in this LU we search for it and
9459
      # remove it from its current node. In the future we could fix this by:
9460
      #  - making a tasklet to search (share-lock all), then create the
9461
      #    new one, then one to remove, after
9462
      #  - removing the removal operation altogether
9463
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9464

    
9465
  def DeclareLocks(self, level):
9466
    """Last minute lock declaration."""
9467
    # All nodes are locked anyway, so nothing to do here.
9468

    
9469
  def BuildHooksEnv(self):
9470
    """Build hooks env.
9471

9472
    This will run on the master, primary node and target node.
9473

9474
    """
9475
    env = {
9476
      "EXPORT_MODE": self.op.mode,
9477
      "EXPORT_NODE": self.op.target_node,
9478
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9479
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9480
      # TODO: Generic function for boolean env variables
9481
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9482
      }
9483

    
9484
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9485

    
9486
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9487

    
9488
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9489
      nl.append(self.op.target_node)
9490

    
9491
    return env, nl, nl
9492

    
9493
  def CheckPrereq(self):
9494
    """Check prerequisites.
9495

9496
    This checks that the instance and node names are valid.
9497

9498
    """
9499
    instance_name = self.op.instance_name
9500

    
9501
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9502
    assert self.instance is not None, \
9503
          "Cannot retrieve locked instance %s" % self.op.instance_name
9504
    _CheckNodeOnline(self, self.instance.primary_node)
9505

    
9506
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9507
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9508
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9509
      assert self.dst_node is not None
9510

    
9511
      _CheckNodeOnline(self, self.dst_node.name)
9512
      _CheckNodeNotDrained(self, self.dst_node.name)
9513

    
9514
      self._cds = None
9515
      self.dest_disk_info = None
9516
      self.dest_x509_ca = None
9517

    
9518
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9519
      self.dst_node = None
9520

    
9521
      if len(self.op.target_node) != len(self.instance.disks):
9522
        raise errors.OpPrereqError(("Received destination information for %s"
9523
                                    " disks, but instance %s has %s disks") %
9524
                                   (len(self.op.target_node), instance_name,
9525
                                    len(self.instance.disks)),
9526
                                   errors.ECODE_INVAL)
9527

    
9528
      cds = _GetClusterDomainSecret()
9529

    
9530
      # Check X509 key name
9531
      try:
9532
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9533
      except (TypeError, ValueError), err:
9534
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9535

    
9536
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9537
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9538
                                   errors.ECODE_INVAL)
9539

    
9540
      # Load and verify CA
9541
      try:
9542
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9543
      except OpenSSL.crypto.Error, err:
9544
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9545
                                   (err, ), errors.ECODE_INVAL)
9546

    
9547
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9548
      if errcode is not None:
9549
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9550
                                   (msg, ), errors.ECODE_INVAL)
9551

    
9552
      self.dest_x509_ca = cert
9553

    
9554
      # Verify target information
9555
      disk_info = []
9556
      for idx, disk_data in enumerate(self.op.target_node):
9557
        try:
9558
          (host, port, magic) = \
9559
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9560
        except errors.GenericError, err:
9561
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9562
                                     (idx, err), errors.ECODE_INVAL)
9563

    
9564
        disk_info.append((host, port, magic))
9565

    
9566
      assert len(disk_info) == len(self.op.target_node)
9567
      self.dest_disk_info = disk_info
9568

    
9569
    else:
9570
      raise errors.ProgrammerError("Unhandled export mode %r" %
9571
                                   self.op.mode)
9572

    
9573
    # instance disk type verification
9574
    # TODO: Implement export support for file-based disks
9575
    for disk in self.instance.disks:
9576
      if disk.dev_type == constants.LD_FILE:
9577
        raise errors.OpPrereqError("Export not supported for instances with"
9578
                                   " file-based disks", errors.ECODE_INVAL)
9579

    
9580
  def _CleanupExports(self, feedback_fn):
9581
    """Removes exports of current instance from all other nodes.
9582

9583
    If an instance in a cluster with nodes A..D was exported to node C, its
9584
    exports will be removed from the nodes A, B and D.
9585

9586
    """
9587
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9588

    
9589
    nodelist = self.cfg.GetNodeList()
9590
    nodelist.remove(self.dst_node.name)
9591

    
9592
    # on one-node clusters nodelist will be empty after the removal
9593
    # if we proceed the backup would be removed because OpQueryExports
9594
    # substitutes an empty list with the full cluster node list.
9595
    iname = self.instance.name
9596
    if nodelist:
9597
      feedback_fn("Removing old exports for instance %s" % iname)
9598
      exportlist = self.rpc.call_export_list(nodelist)
9599
      for node in exportlist:
9600
        if exportlist[node].fail_msg:
9601
          continue
9602
        if iname in exportlist[node].payload:
9603
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9604
          if msg:
9605
            self.LogWarning("Could not remove older export for instance %s"
9606
                            " on node %s: %s", iname, node, msg)
9607

    
9608
  def Exec(self, feedback_fn):
9609
    """Export an instance to an image in the cluster.
9610

9611
    """
9612
    assert self.op.mode in constants.EXPORT_MODES
9613

    
9614
    instance = self.instance
9615
    src_node = instance.primary_node
9616

    
9617
    if self.op.shutdown:
9618
      # shutdown the instance, but not the disks
9619
      feedback_fn("Shutting down instance %s" % instance.name)
9620
      result = self.rpc.call_instance_shutdown(src_node, instance,
9621
                                               self.op.shutdown_timeout)
9622
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9623
      result.Raise("Could not shutdown instance %s on"
9624
                   " node %s" % (instance.name, src_node))
9625

    
9626
    # set the disks ID correctly since call_instance_start needs the
9627
    # correct drbd minor to create the symlinks
9628
    for disk in instance.disks:
9629
      self.cfg.SetDiskID(disk, src_node)
9630

    
9631
    activate_disks = (not instance.admin_up)
9632

    
9633
    if activate_disks:
9634
      # Activate the instance disks if we'exporting a stopped instance
9635
      feedback_fn("Activating disks for %s" % instance.name)
9636
      _StartInstanceDisks(self, instance, None)
9637

    
9638
    try:
9639
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9640
                                                     instance)
9641

    
9642
      helper.CreateSnapshots()
9643
      try:
9644
        if (self.op.shutdown and instance.admin_up and
9645
            not self.op.remove_instance):
9646
          assert not activate_disks
9647
          feedback_fn("Starting instance %s" % instance.name)
9648
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9649
          msg = result.fail_msg
9650
          if msg:
9651
            feedback_fn("Failed to start instance: %s" % msg)
9652
            _ShutdownInstanceDisks(self, instance)
9653
            raise errors.OpExecError("Could not start instance: %s" % msg)
9654

    
9655
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9656
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9657
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9658
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9659
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9660

    
9661
          (key_name, _, _) = self.x509_key_name
9662

    
9663
          dest_ca_pem = \
9664
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9665
                                            self.dest_x509_ca)
9666

    
9667
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9668
                                                     key_name, dest_ca_pem,
9669
                                                     timeouts)
9670
      finally:
9671
        helper.Cleanup()
9672

    
9673
      # Check for backwards compatibility
9674
      assert len(dresults) == len(instance.disks)
9675
      assert compat.all(isinstance(i, bool) for i in dresults), \
9676
             "Not all results are boolean: %r" % dresults
9677

    
9678
    finally:
9679
      if activate_disks:
9680
        feedback_fn("Deactivating disks for %s" % instance.name)
9681
        _ShutdownInstanceDisks(self, instance)
9682

    
9683
    if not (compat.all(dresults) and fin_resu):
9684
      failures = []
9685
      if not fin_resu:
9686
        failures.append("export finalization")
9687
      if not compat.all(dresults):
9688
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9689
                               if not dsk)
9690
        failures.append("disk export: disk(s) %s" % fdsk)
9691

    
9692
      raise errors.OpExecError("Export failed, errors in %s" %
9693
                               utils.CommaJoin(failures))
9694

    
9695
    # At this point, the export was successful, we can cleanup/finish
9696

    
9697
    # Remove instance if requested
9698
    if self.op.remove_instance:
9699
      feedback_fn("Removing instance %s" % instance.name)
9700
      _RemoveInstance(self, feedback_fn, instance,
9701
                      self.op.ignore_remove_failures)
9702

    
9703
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9704
      self._CleanupExports(feedback_fn)
9705

    
9706
    return fin_resu, dresults
9707

    
9708

    
9709
class LURemoveExport(NoHooksLU):
9710
  """Remove exports related to the named instance.
9711

9712
  """
9713
  _OP_PARAMS = [
9714
    _PInstanceName,
9715
    ]
9716
  REQ_BGL = False
9717

    
9718
  def ExpandNames(self):
9719
    self.needed_locks = {}
9720
    # We need all nodes to be locked in order for RemoveExport to work, but we
9721
    # don't need to lock the instance itself, as nothing will happen to it (and
9722
    # we can remove exports also for a removed instance)
9723
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9724

    
9725
  def Exec(self, feedback_fn):
9726
    """Remove any export.
9727

9728
    """
9729
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9730
    # If the instance was not found we'll try with the name that was passed in.
9731
    # This will only work if it was an FQDN, though.
9732
    fqdn_warn = False
9733
    if not instance_name:
9734
      fqdn_warn = True
9735
      instance_name = self.op.instance_name
9736

    
9737
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9738
    exportlist = self.rpc.call_export_list(locked_nodes)
9739
    found = False
9740
    for node in exportlist:
9741
      msg = exportlist[node].fail_msg
9742
      if msg:
9743
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9744
        continue
9745
      if instance_name in exportlist[node].payload:
9746
        found = True
9747
        result = self.rpc.call_export_remove(node, instance_name)
9748
        msg = result.fail_msg
9749
        if msg:
9750
          logging.error("Could not remove export for instance %s"
9751
                        " on node %s: %s", instance_name, node, msg)
9752

    
9753
    if fqdn_warn and not found:
9754
      feedback_fn("Export not found. If trying to remove an export belonging"
9755
                  " to a deleted instance please use its Fully Qualified"
9756
                  " Domain Name.")
9757

    
9758

    
9759
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9760
  """Generic tags LU.
9761

9762
  This is an abstract class which is the parent of all the other tags LUs.
9763

9764
  """
9765

    
9766
  def ExpandNames(self):
9767
    self.needed_locks = {}
9768
    if self.op.kind == constants.TAG_NODE:
9769
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9770
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9771
    elif self.op.kind == constants.TAG_INSTANCE:
9772
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9773
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9774

    
9775
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
9776
    # not possible to acquire the BGL based on opcode parameters)
9777

    
9778
  def CheckPrereq(self):
9779
    """Check prerequisites.
9780

9781
    """
9782
    if self.op.kind == constants.TAG_CLUSTER:
9783
      self.target = self.cfg.GetClusterInfo()
9784
    elif self.op.kind == constants.TAG_NODE:
9785
      self.target = self.cfg.GetNodeInfo(self.op.name)
9786
    elif self.op.kind == constants.TAG_INSTANCE:
9787
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9788
    else:
9789
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9790
                                 str(self.op.kind), errors.ECODE_INVAL)
9791

    
9792

    
9793
class LUGetTags(TagsLU):
9794
  """Returns the tags of a given object.
9795

9796
  """
9797
  _OP_PARAMS = [
9798
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9799
    # Name is only meaningful for nodes and instances
9800
    ("name", ht.NoDefault, ht.TMaybeString),
9801
    ]
9802
  REQ_BGL = False
9803

    
9804
  def ExpandNames(self):
9805
    TagsLU.ExpandNames(self)
9806

    
9807
    # Share locks as this is only a read operation
9808
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9809

    
9810
  def Exec(self, feedback_fn):
9811
    """Returns the tag list.
9812

9813
    """
9814
    return list(self.target.GetTags())
9815

    
9816

    
9817
class LUSearchTags(NoHooksLU):
9818
  """Searches the tags for a given pattern.
9819

9820
  """
9821
  _OP_PARAMS = [
9822
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
9823
    ]
9824
  REQ_BGL = False
9825

    
9826
  def ExpandNames(self):
9827
    self.needed_locks = {}
9828

    
9829
  def CheckPrereq(self):
9830
    """Check prerequisites.
9831

9832
    This checks the pattern passed for validity by compiling it.
9833

9834
    """
9835
    try:
9836
      self.re = re.compile(self.op.pattern)
9837
    except re.error, err:
9838
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9839
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9840

    
9841
  def Exec(self, feedback_fn):
9842
    """Returns the tag list.
9843

9844
    """
9845
    cfg = self.cfg
9846
    tgts = [("/cluster", cfg.GetClusterInfo())]
9847
    ilist = cfg.GetAllInstancesInfo().values()
9848
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9849
    nlist = cfg.GetAllNodesInfo().values()
9850
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9851
    results = []
9852
    for path, target in tgts:
9853
      for tag in target.GetTags():
9854
        if self.re.search(tag):
9855
          results.append((path, tag))
9856
    return results
9857

    
9858

    
9859
class LUAddTags(TagsLU):
9860
  """Sets a tag on a given object.
9861

9862
  """
9863
  _OP_PARAMS = [
9864
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9865
    # Name is only meaningful for nodes and instances
9866
    ("name", ht.NoDefault, ht.TMaybeString),
9867
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
9868
    ]
9869
  REQ_BGL = False
9870

    
9871
  def CheckPrereq(self):
9872
    """Check prerequisites.
9873

9874
    This checks the type and length of the tag name and value.
9875

9876
    """
9877
    TagsLU.CheckPrereq(self)
9878
    for tag in self.op.tags:
9879
      objects.TaggableObject.ValidateTag(tag)
9880

    
9881
  def Exec(self, feedback_fn):
9882
    """Sets the tag.
9883

9884
    """
9885
    try:
9886
      for tag in self.op.tags:
9887
        self.target.AddTag(tag)
9888
    except errors.TagError, err:
9889
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9890
    self.cfg.Update(self.target, feedback_fn)
9891

    
9892

    
9893
class LUDelTags(TagsLU):
9894
  """Delete a list of tags from a given object.
9895

9896
  """
9897
  _OP_PARAMS = [
9898
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9899
    # Name is only meaningful for nodes and instances
9900
    ("name", ht.NoDefault, ht.TMaybeString),
9901
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
9902
    ]
9903
  REQ_BGL = False
9904

    
9905
  def CheckPrereq(self):
9906
    """Check prerequisites.
9907

9908
    This checks that we have the given tag.
9909

9910
    """
9911
    TagsLU.CheckPrereq(self)
9912
    for tag in self.op.tags:
9913
      objects.TaggableObject.ValidateTag(tag)
9914
    del_tags = frozenset(self.op.tags)
9915
    cur_tags = self.target.GetTags()
9916

    
9917
    diff_tags = del_tags - cur_tags
9918
    if diff_tags:
9919
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
9920
      raise errors.OpPrereqError("Tag(s) %s not found" %
9921
                                 (utils.CommaJoin(diff_names), ),
9922
                                 errors.ECODE_NOENT)
9923

    
9924
  def Exec(self, feedback_fn):
9925
    """Remove the tag from the object.
9926

9927
    """
9928
    for tag in self.op.tags:
9929
      self.target.RemoveTag(tag)
9930
    self.cfg.Update(self.target, feedback_fn)
9931

    
9932

    
9933
class LUTestDelay(NoHooksLU):
9934
  """Sleep for a specified amount of time.
9935

9936
  This LU sleeps on the master and/or nodes for a specified amount of
9937
  time.
9938

9939
  """
9940
  _OP_PARAMS = [
9941
    ("duration", ht.NoDefault, ht.TFloat),
9942
    ("on_master", True, ht.TBool),
9943
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9944
    ("repeat", 0, ht.TPositiveInt)
9945
    ]
9946
  REQ_BGL = False
9947

    
9948
  def ExpandNames(self):
9949
    """Expand names and set required locks.
9950

9951
    This expands the node list, if any.
9952

9953
    """
9954
    self.needed_locks = {}
9955
    if self.op.on_nodes:
9956
      # _GetWantedNodes can be used here, but is not always appropriate to use
9957
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9958
      # more information.
9959
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9960
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9961

    
9962
  def _TestDelay(self):
9963
    """Do the actual sleep.
9964

9965
    """
9966
    if self.op.on_master:
9967
      if not utils.TestDelay(self.op.duration):
9968
        raise errors.OpExecError("Error during master delay test")
9969
    if self.op.on_nodes:
9970
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9971
      for node, node_result in result.items():
9972
        node_result.Raise("Failure during rpc call to node %s" % node)
9973

    
9974
  def Exec(self, feedback_fn):
9975
    """Execute the test delay opcode, with the wanted repetitions.
9976

9977
    """
9978
    if self.op.repeat == 0:
9979
      self._TestDelay()
9980
    else:
9981
      top_value = self.op.repeat - 1
9982
      for i in range(self.op.repeat):
9983
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9984
        self._TestDelay()
9985

    
9986

    
9987
class LUTestJobqueue(NoHooksLU):
9988
  """Utility LU to test some aspects of the job queue.
9989

9990
  """
9991
  _OP_PARAMS = [
9992
    ("notify_waitlock", False, ht.TBool),
9993
    ("notify_exec", False, ht.TBool),
9994
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
9995
    ("fail", False, ht.TBool),
9996
    ]
9997
  REQ_BGL = False
9998

    
9999
  # Must be lower than default timeout for WaitForJobChange to see whether it
10000
  # notices changed jobs
10001
  _CLIENT_CONNECT_TIMEOUT = 20.0
10002
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10003

    
10004
  @classmethod
10005
  def _NotifyUsingSocket(cls, cb, errcls):
10006
    """Opens a Unix socket and waits for another program to connect.
10007

10008
    @type cb: callable
10009
    @param cb: Callback to send socket name to client
10010
    @type errcls: class
10011
    @param errcls: Exception class to use for errors
10012

10013
    """
10014
    # Using a temporary directory as there's no easy way to create temporary
10015
    # sockets without writing a custom loop around tempfile.mktemp and
10016
    # socket.bind
10017
    tmpdir = tempfile.mkdtemp()
10018
    try:
10019
      tmpsock = utils.PathJoin(tmpdir, "sock")
10020

    
10021
      logging.debug("Creating temporary socket at %s", tmpsock)
10022
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10023
      try:
10024
        sock.bind(tmpsock)
10025
        sock.listen(1)
10026

    
10027
        # Send details to client
10028
        cb(tmpsock)
10029

    
10030
        # Wait for client to connect before continuing
10031
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10032
        try:
10033
          (conn, _) = sock.accept()
10034
        except socket.error, err:
10035
          raise errcls("Client didn't connect in time (%s)" % err)
10036
      finally:
10037
        sock.close()
10038
    finally:
10039
      # Remove as soon as client is connected
10040
      shutil.rmtree(tmpdir)
10041

    
10042
    # Wait for client to close
10043
    try:
10044
      try:
10045
        # pylint: disable-msg=E1101
10046
        # Instance of '_socketobject' has no ... member
10047
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10048
        conn.recv(1)
10049
      except socket.error, err:
10050
        raise errcls("Client failed to confirm notification (%s)" % err)
10051
    finally:
10052
      conn.close()
10053

    
10054
  def _SendNotification(self, test, arg, sockname):
10055
    """Sends a notification to the client.
10056

10057
    @type test: string
10058
    @param test: Test name
10059
    @param arg: Test argument (depends on test)
10060
    @type sockname: string
10061
    @param sockname: Socket path
10062

10063
    """
10064
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10065

    
10066
  def _Notify(self, prereq, test, arg):
10067
    """Notifies the client of a test.
10068

10069
    @type prereq: bool
10070
    @param prereq: Whether this is a prereq-phase test
10071
    @type test: string
10072
    @param test: Test name
10073
    @param arg: Test argument (depends on test)
10074

10075
    """
10076
    if prereq:
10077
      errcls = errors.OpPrereqError
10078
    else:
10079
      errcls = errors.OpExecError
10080

    
10081
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10082
                                                  test, arg),
10083
                                   errcls)
10084

    
10085
  def CheckArguments(self):
10086
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10087
    self.expandnames_calls = 0
10088

    
10089
  def ExpandNames(self):
10090
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10091
    if checkargs_calls < 1:
10092
      raise errors.ProgrammerError("CheckArguments was not called")
10093

    
10094
    self.expandnames_calls += 1
10095

    
10096
    if self.op.notify_waitlock:
10097
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10098

    
10099
    self.LogInfo("Expanding names")
10100

    
10101
    # Get lock on master node (just to get a lock, not for a particular reason)
10102
    self.needed_locks = {
10103
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10104
      }
10105

    
10106
  def Exec(self, feedback_fn):
10107
    if self.expandnames_calls < 1:
10108
      raise errors.ProgrammerError("ExpandNames was not called")
10109

    
10110
    if self.op.notify_exec:
10111
      self._Notify(False, constants.JQT_EXEC, None)
10112

    
10113
    self.LogInfo("Executing")
10114

    
10115
    if self.op.log_messages:
10116
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10117
      for idx, msg in enumerate(self.op.log_messages):
10118
        self.LogInfo("Sending log message %s", idx + 1)
10119
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10120
        # Report how many test messages have been sent
10121
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10122

    
10123
    if self.op.fail:
10124
      raise errors.OpExecError("Opcode failure was requested")
10125

    
10126
    return True
10127

    
10128

    
10129
class IAllocator(object):
10130
  """IAllocator framework.
10131

10132
  An IAllocator instance has three sets of attributes:
10133
    - cfg that is needed to query the cluster
10134
    - input data (all members of the _KEYS class attribute are required)
10135
    - four buffer attributes (in|out_data|text), that represent the
10136
      input (to the external script) in text and data structure format,
10137
      and the output from it, again in two formats
10138
    - the result variables from the script (success, info, nodes) for
10139
      easy usage
10140

10141
  """
10142
  # pylint: disable-msg=R0902
10143
  # lots of instance attributes
10144
  _ALLO_KEYS = [
10145
    "name", "mem_size", "disks", "disk_template",
10146
    "os", "tags", "nics", "vcpus", "hypervisor",
10147
    ]
10148
  _RELO_KEYS = [
10149
    "name", "relocate_from",
10150
    ]
10151
  _EVAC_KEYS = [
10152
    "evac_nodes",
10153
    ]
10154

    
10155
  def __init__(self, cfg, rpc, mode, **kwargs):
10156
    self.cfg = cfg
10157
    self.rpc = rpc
10158
    # init buffer variables
10159
    self.in_text = self.out_text = self.in_data = self.out_data = None
10160
    # init all input fields so that pylint is happy
10161
    self.mode = mode
10162
    self.mem_size = self.disks = self.disk_template = None
10163
    self.os = self.tags = self.nics = self.vcpus = None
10164
    self.hypervisor = None
10165
    self.relocate_from = None
10166
    self.name = None
10167
    self.evac_nodes = None
10168
    # computed fields
10169
    self.required_nodes = None
10170
    # init result fields
10171
    self.success = self.info = self.result = None
10172
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10173
      keyset = self._ALLO_KEYS
10174
      fn = self._AddNewInstance
10175
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10176
      keyset = self._RELO_KEYS
10177
      fn = self._AddRelocateInstance
10178
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10179
      keyset = self._EVAC_KEYS
10180
      fn = self._AddEvacuateNodes
10181
    else:
10182
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10183
                                   " IAllocator" % self.mode)
10184
    for key in kwargs:
10185
      if key not in keyset:
10186
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10187
                                     " IAllocator" % key)
10188
      setattr(self, key, kwargs[key])
10189

    
10190
    for key in keyset:
10191
      if key not in kwargs:
10192
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10193
                                     " IAllocator" % key)
10194
    self._BuildInputData(fn)
10195

    
10196
  def _ComputeClusterData(self):
10197
    """Compute the generic allocator input data.
10198

10199
    This is the data that is independent of the actual operation.
10200

10201
    """
10202
    cfg = self.cfg
10203
    cluster_info = cfg.GetClusterInfo()
10204
    # cluster data
10205
    data = {
10206
      "version": constants.IALLOCATOR_VERSION,
10207
      "cluster_name": cfg.GetClusterName(),
10208
      "cluster_tags": list(cluster_info.GetTags()),
10209
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10210
      # we don't have job IDs
10211
      }
10212
    iinfo = cfg.GetAllInstancesInfo().values()
10213
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10214

    
10215
    # node data
10216
    node_list = cfg.GetNodeList()
10217

    
10218
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10219
      hypervisor_name = self.hypervisor
10220
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10221
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10222
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10223
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10224

    
10225
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10226
                                        hypervisor_name)
10227
    node_iinfo = \
10228
      self.rpc.call_all_instances_info(node_list,
10229
                                       cluster_info.enabled_hypervisors)
10230

    
10231
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10232

    
10233
    data["nodes"] = self._ComputeNodeData(cfg, node_data, node_iinfo, i_list)
10234

    
10235
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10236

    
10237
    self.in_data = data
10238

    
10239
  @staticmethod
10240
  def _ComputeNodeGroupData(cfg):
10241
    """Compute node groups data.
10242

10243
    """
10244
    ng = {}
10245
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10246
      ng[guuid] = { "name": gdata.name }
10247
    return ng
10248

    
10249
  @staticmethod
10250
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10251
    """Compute global node data.
10252

10253
    """
10254
    node_results = {}
10255
    for nname, nresult in node_data.items():
10256
      # first fill in static (config-based) values
10257
      ninfo = cfg.GetNodeInfo(nname)
10258
      pnr = {
10259
        "tags": list(ninfo.GetTags()),
10260
        "primary_ip": ninfo.primary_ip,
10261
        "secondary_ip": ninfo.secondary_ip,
10262
        "offline": ninfo.offline,
10263
        "drained": ninfo.drained,
10264
        "master_candidate": ninfo.master_candidate,
10265
        "group": ninfo.group,
10266
        "master_capable": ninfo.master_capable,
10267
        "vm_capable": ninfo.vm_capable,
10268
        }
10269

    
10270
      if not (ninfo.offline or ninfo.drained):
10271
        nresult.Raise("Can't get data for node %s" % nname)
10272
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10273
                                nname)
10274
        remote_info = nresult.payload
10275

    
10276
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10277
                     'vg_size', 'vg_free', 'cpu_total']:
10278
          if attr not in remote_info:
10279
            raise errors.OpExecError("Node '%s' didn't return attribute"
10280
                                     " '%s'" % (nname, attr))
10281
          if not isinstance(remote_info[attr], int):
10282
            raise errors.OpExecError("Node '%s' returned invalid value"
10283
                                     " for '%s': %s" %
10284
                                     (nname, attr, remote_info[attr]))
10285
        # compute memory used by primary instances
10286
        i_p_mem = i_p_up_mem = 0
10287
        for iinfo, beinfo in i_list:
10288
          if iinfo.primary_node == nname:
10289
            i_p_mem += beinfo[constants.BE_MEMORY]
10290
            if iinfo.name not in node_iinfo[nname].payload:
10291
              i_used_mem = 0
10292
            else:
10293
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10294
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10295
            remote_info['memory_free'] -= max(0, i_mem_diff)
10296

    
10297
            if iinfo.admin_up:
10298
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10299

    
10300
        # compute memory used by instances
10301
        pnr_dyn = {
10302
          "total_memory": remote_info['memory_total'],
10303
          "reserved_memory": remote_info['memory_dom0'],
10304
          "free_memory": remote_info['memory_free'],
10305
          "total_disk": remote_info['vg_size'],
10306
          "free_disk": remote_info['vg_free'],
10307
          "total_cpus": remote_info['cpu_total'],
10308
          "i_pri_memory": i_p_mem,
10309
          "i_pri_up_memory": i_p_up_mem,
10310
          }
10311
        pnr.update(pnr_dyn)
10312

    
10313
      node_results[nname] = pnr
10314

    
10315
    return node_results
10316

    
10317
  @staticmethod
10318
  def _ComputeInstanceData(cluster_info, i_list):
10319
    """Compute global instance data.
10320

10321
    """
10322
    instance_data = {}
10323
    for iinfo, beinfo in i_list:
10324
      nic_data = []
10325
      for nic in iinfo.nics:
10326
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10327
        nic_dict = {"mac": nic.mac,
10328
                    "ip": nic.ip,
10329
                    "mode": filled_params[constants.NIC_MODE],
10330
                    "link": filled_params[constants.NIC_LINK],
10331
                   }
10332
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10333
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10334
        nic_data.append(nic_dict)
10335
      pir = {
10336
        "tags": list(iinfo.GetTags()),
10337
        "admin_up": iinfo.admin_up,
10338
        "vcpus": beinfo[constants.BE_VCPUS],
10339
        "memory": beinfo[constants.BE_MEMORY],
10340
        "os": iinfo.os,
10341
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10342
        "nics": nic_data,
10343
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10344
        "disk_template": iinfo.disk_template,
10345
        "hypervisor": iinfo.hypervisor,
10346
        }
10347
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10348
                                                 pir["disks"])
10349
      instance_data[iinfo.name] = pir
10350

    
10351
    return instance_data
10352

    
10353
  def _AddNewInstance(self):
10354
    """Add new instance data to allocator structure.
10355

10356
    This in combination with _AllocatorGetClusterData will create the
10357
    correct structure needed as input for the allocator.
10358

10359
    The checks for the completeness of the opcode must have already been
10360
    done.
10361

10362
    """
10363
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10364

    
10365
    if self.disk_template in constants.DTS_NET_MIRROR:
10366
      self.required_nodes = 2
10367
    else:
10368
      self.required_nodes = 1
10369
    request = {
10370
      "name": self.name,
10371
      "disk_template": self.disk_template,
10372
      "tags": self.tags,
10373
      "os": self.os,
10374
      "vcpus": self.vcpus,
10375
      "memory": self.mem_size,
10376
      "disks": self.disks,
10377
      "disk_space_total": disk_space,
10378
      "nics": self.nics,
10379
      "required_nodes": self.required_nodes,
10380
      }
10381
    return request
10382

    
10383
  def _AddRelocateInstance(self):
10384
    """Add relocate instance data to allocator structure.
10385

10386
    This in combination with _IAllocatorGetClusterData will create the
10387
    correct structure needed as input for the allocator.
10388

10389
    The checks for the completeness of the opcode must have already been
10390
    done.
10391

10392
    """
10393
    instance = self.cfg.GetInstanceInfo(self.name)
10394
    if instance is None:
10395
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10396
                                   " IAllocator" % self.name)
10397

    
10398
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10399
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10400
                                 errors.ECODE_INVAL)
10401

    
10402
    if len(instance.secondary_nodes) != 1:
10403
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10404
                                 errors.ECODE_STATE)
10405

    
10406
    self.required_nodes = 1
10407
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10408
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10409

    
10410
    request = {
10411
      "name": self.name,
10412
      "disk_space_total": disk_space,
10413
      "required_nodes": self.required_nodes,
10414
      "relocate_from": self.relocate_from,
10415
      }
10416
    return request
10417

    
10418
  def _AddEvacuateNodes(self):
10419
    """Add evacuate nodes data to allocator structure.
10420

10421
    """
10422
    request = {
10423
      "evac_nodes": self.evac_nodes
10424
      }
10425
    return request
10426

    
10427
  def _BuildInputData(self, fn):
10428
    """Build input data structures.
10429

10430
    """
10431
    self._ComputeClusterData()
10432

    
10433
    request = fn()
10434
    request["type"] = self.mode
10435
    self.in_data["request"] = request
10436

    
10437
    self.in_text = serializer.Dump(self.in_data)
10438

    
10439
  def Run(self, name, validate=True, call_fn=None):
10440
    """Run an instance allocator and return the results.
10441

10442
    """
10443
    if call_fn is None:
10444
      call_fn = self.rpc.call_iallocator_runner
10445

    
10446
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10447
    result.Raise("Failure while running the iallocator script")
10448

    
10449
    self.out_text = result.payload
10450
    if validate:
10451
      self._ValidateResult()
10452

    
10453
  def _ValidateResult(self):
10454
    """Process the allocator results.
10455

10456
    This will process and if successful save the result in
10457
    self.out_data and the other parameters.
10458

10459
    """
10460
    try:
10461
      rdict = serializer.Load(self.out_text)
10462
    except Exception, err:
10463
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10464

    
10465
    if not isinstance(rdict, dict):
10466
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10467

    
10468
    # TODO: remove backwards compatiblity in later versions
10469
    if "nodes" in rdict and "result" not in rdict:
10470
      rdict["result"] = rdict["nodes"]
10471
      del rdict["nodes"]
10472

    
10473
    for key in "success", "info", "result":
10474
      if key not in rdict:
10475
        raise errors.OpExecError("Can't parse iallocator results:"
10476
                                 " missing key '%s'" % key)
10477
      setattr(self, key, rdict[key])
10478

    
10479
    if not isinstance(rdict["result"], list):
10480
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10481
                               " is not a list")
10482
    self.out_data = rdict
10483

    
10484

    
10485
class LUTestAllocator(NoHooksLU):
10486
  """Run allocator tests.
10487

10488
  This LU runs the allocator tests
10489

10490
  """
10491
  _OP_PARAMS = [
10492
    ("direction", ht.NoDefault,
10493
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10494
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10495
    ("name", ht.NoDefault, ht.TNonEmptyString),
10496
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10497
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10498
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10499
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10500
    ("hypervisor", None, ht.TMaybeString),
10501
    ("allocator", None, ht.TMaybeString),
10502
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10503
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10504
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10505
    ("os", None, ht.TMaybeString),
10506
    ("disk_template", None, ht.TMaybeString),
10507
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10508
    ]
10509

    
10510
  def CheckPrereq(self):
10511
    """Check prerequisites.
10512

10513
    This checks the opcode parameters depending on the director and mode test.
10514

10515
    """
10516
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10517
      for attr in ["mem_size", "disks", "disk_template",
10518
                   "os", "tags", "nics", "vcpus"]:
10519
        if not hasattr(self.op, attr):
10520
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10521
                                     attr, errors.ECODE_INVAL)
10522
      iname = self.cfg.ExpandInstanceName(self.op.name)
10523
      if iname is not None:
10524
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10525
                                   iname, errors.ECODE_EXISTS)
10526
      if not isinstance(self.op.nics, list):
10527
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10528
                                   errors.ECODE_INVAL)
10529
      if not isinstance(self.op.disks, list):
10530
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10531
                                   errors.ECODE_INVAL)
10532
      for row in self.op.disks:
10533
        if (not isinstance(row, dict) or
10534
            "size" not in row or
10535
            not isinstance(row["size"], int) or
10536
            "mode" not in row or
10537
            row["mode"] not in ['r', 'w']):
10538
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10539
                                     " parameter", errors.ECODE_INVAL)
10540
      if self.op.hypervisor is None:
10541
        self.op.hypervisor = self.cfg.GetHypervisorType()
10542
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10543
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10544
      self.op.name = fname
10545
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10546
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10547
      if not hasattr(self.op, "evac_nodes"):
10548
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10549
                                   " opcode input", errors.ECODE_INVAL)
10550
    else:
10551
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10552
                                 self.op.mode, errors.ECODE_INVAL)
10553

    
10554
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10555
      if self.op.allocator is None:
10556
        raise errors.OpPrereqError("Missing allocator name",
10557
                                   errors.ECODE_INVAL)
10558
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10559
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10560
                                 self.op.direction, errors.ECODE_INVAL)
10561

    
10562
  def Exec(self, feedback_fn):
10563
    """Run the allocator test.
10564

10565
    """
10566
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10567
      ial = IAllocator(self.cfg, self.rpc,
10568
                       mode=self.op.mode,
10569
                       name=self.op.name,
10570
                       mem_size=self.op.mem_size,
10571
                       disks=self.op.disks,
10572
                       disk_template=self.op.disk_template,
10573
                       os=self.op.os,
10574
                       tags=self.op.tags,
10575
                       nics=self.op.nics,
10576
                       vcpus=self.op.vcpus,
10577
                       hypervisor=self.op.hypervisor,
10578
                       )
10579
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10580
      ial = IAllocator(self.cfg, self.rpc,
10581
                       mode=self.op.mode,
10582
                       name=self.op.name,
10583
                       relocate_from=list(self.relocate_from),
10584
                       )
10585
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10586
      ial = IAllocator(self.cfg, self.rpc,
10587
                       mode=self.op.mode,
10588
                       evac_nodes=self.op.evac_nodes)
10589
    else:
10590
      raise errors.ProgrammerError("Uncatched mode %s in"
10591
                                   " LUTestAllocator.Exec", self.op.mode)
10592

    
10593
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10594
      result = ial.in_text
10595
    else:
10596
      ial.Run(self.op.allocator, validate=False)
10597
      result = ial.out_text
10598
    return result