Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 77bad5b2

History | View | Annotate | Download (377.1 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
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
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
    @type vm_capable: boolean
1223
    @ivar vm_capable: whether the node can host instances
1224

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

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

    
1251
  def _Error(self, ecode, item, msg, *args, **kwargs):
1252
    """Format an error message.
1253

1254
    Based on the opcode's error_codes parameter, either format a
1255
    parseable error code, or a simpler error string.
1256

1257
    This must be called only from Exec and functions called from Exec.
1258

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

    
1277
  def _ErrorIf(self, cond, *args, **kwargs):
1278
    """Log an error message if the passed condition is True.
1279

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

    
1288
  def _VerifyNode(self, ninfo, nresult):
1289
    """Perform some basic validation on data returned from a node.
1290

1291
      - check the result data structure is well formed and has all the
1292
        mandatory fields
1293
      - check ganeti version
1294

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

1302
    """
1303
    node = ninfo.name
1304
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1305

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

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

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

    
1331
    # node seems compatible, we can actually try to look into its results
1332

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

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

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

    
1352
    return True
1353

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

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

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

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

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

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

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

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

1394
    """
1395
    if vg_name is None:
1396
      return
1397

    
1398
    node = ninfo.name
1399
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1400

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

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

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

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

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

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

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

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

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

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

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

    
1476
    node_vol_should = {}
1477
    instanceconfig.MapLVsByNode(node_vol_should)
1478

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

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

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

    
1502
    diskdata = [(nname, disk, idx)
1503
                for (nname, disks) in diskstatus.items()
1504
                for idx, disk in enumerate(disks)]
1505

    
1506
    for nname, bdev_status, idx in diskdata:
1507
      _ErrorIf(not bdev_status,
1508
               self.EINSTANCEFAULTYDISK, instance,
1509
               "couldn't retrieve status for disk/%s on %s", idx, nname)
1510
      _ErrorIf(bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY,
1511
               self.EINSTANCEFAULTYDISK, instance,
1512
               "disk/%s on %s is faulty", idx, nname)
1513

    
1514
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1515
    """Verify if there are any unknown volumes in the cluster.
1516

1517
    The .os, .swap and backup volumes are ignored. All other volumes are
1518
    reported as unknown.
1519

1520
    @type reserved: L{ganeti.utils.FieldSet}
1521
    @param reserved: a FieldSet of reserved volume names
1522

1523
    """
1524
    for node, n_img in node_image.items():
1525
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1526
        # skip non-healthy nodes
1527
        continue
1528
      for volume in n_img.volumes:
1529
        test = ((node not in node_vol_should or
1530
                volume not in node_vol_should[node]) and
1531
                not reserved.Matches(volume))
1532
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1533
                      "volume %s is unknown", volume)
1534

    
1535
  def _VerifyOrphanInstances(self, instancelist, node_image):
1536
    """Verify the list of running instances.
1537

1538
    This checks what instances are running but unknown to the cluster.
1539

1540
    """
1541
    for node, n_img in node_image.items():
1542
      for o_inst in n_img.instances:
1543
        test = o_inst not in instancelist
1544
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1545
                      "instance %s on node %s should not exist", o_inst, node)
1546

    
1547
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1548
    """Verify N+1 Memory Resilience.
1549

1550
    Check that if one single node dies we can still start all the
1551
    instances it was primary for.
1552

1553
    """
1554
    for node, n_img in node_image.items():
1555
      # This code checks that every node which is now listed as
1556
      # secondary has enough memory to host all instances it is
1557
      # supposed to should a single other node in the cluster fail.
1558
      # FIXME: not ready for failover to an arbitrary node
1559
      # FIXME: does not support file-backed instances
1560
      # WARNING: we currently take into account down instances as well
1561
      # as up ones, considering that even if they're down someone
1562
      # might want to start them even in the event of a node failure.
1563
      for prinode, instances in n_img.sbp.items():
1564
        needed_mem = 0
1565
        for instance in instances:
1566
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1567
          if bep[constants.BE_AUTO_BALANCE]:
1568
            needed_mem += bep[constants.BE_MEMORY]
1569
        test = n_img.mfree < needed_mem
1570
        self._ErrorIf(test, self.ENODEN1, node,
1571
                      "not enough memory on to accommodate"
1572
                      " failovers should peer node %s fail", prinode)
1573

    
1574
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1575
                       master_files):
1576
    """Verifies and computes the node required file checksums.
1577

1578
    @type ninfo: L{objects.Node}
1579
    @param ninfo: the node to check
1580
    @param nresult: the remote results for the node
1581
    @param file_list: required list of files
1582
    @param local_cksum: dictionary of local files and their checksums
1583
    @param master_files: list of files that only masters should have
1584

1585
    """
1586
    node = ninfo.name
1587
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1588

    
1589
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1590
    test = not isinstance(remote_cksum, dict)
1591
    _ErrorIf(test, self.ENODEFILECHECK, node,
1592
             "node hasn't returned file checksum data")
1593
    if test:
1594
      return
1595

    
1596
    for file_name in file_list:
1597
      node_is_mc = ninfo.master_candidate
1598
      must_have = (file_name not in master_files) or node_is_mc
1599
      # missing
1600
      test1 = file_name not in remote_cksum
1601
      # invalid checksum
1602
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1603
      # existing and good
1604
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1605
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1606
               "file '%s' missing", file_name)
1607
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1608
               "file '%s' has wrong checksum", file_name)
1609
      # not candidate and this is not a must-have file
1610
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1611
               "file '%s' should not exist on non master"
1612
               " candidates (and the file is outdated)", file_name)
1613
      # all good, except non-master/non-must have combination
1614
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1615
               "file '%s' should not exist"
1616
               " on non master candidates", file_name)
1617

    
1618
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1619
                      drbd_map):
1620
    """Verifies and the node DRBD status.
1621

1622
    @type ninfo: L{objects.Node}
1623
    @param ninfo: the node to check
1624
    @param nresult: the remote results for the node
1625
    @param instanceinfo: the dict of instances
1626
    @param drbd_helper: the configured DRBD usermode helper
1627
    @param drbd_map: the DRBD map as returned by
1628
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1629

1630
    """
1631
    node = ninfo.name
1632
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1633

    
1634
    if drbd_helper:
1635
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1636
      test = (helper_result == None)
1637
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1638
               "no drbd usermode helper returned")
1639
      if helper_result:
1640
        status, payload = helper_result
1641
        test = not status
1642
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1643
                 "drbd usermode helper check unsuccessful: %s", payload)
1644
        test = status and (payload != drbd_helper)
1645
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1646
                 "wrong drbd usermode helper: %s", payload)
1647

    
1648
    # compute the DRBD minors
1649
    node_drbd = {}
1650
    for minor, instance in drbd_map[node].items():
1651
      test = instance not in instanceinfo
1652
      _ErrorIf(test, self.ECLUSTERCFG, None,
1653
               "ghost instance '%s' in temporary DRBD map", instance)
1654
        # ghost instance should not be running, but otherwise we
1655
        # don't give double warnings (both ghost instance and
1656
        # unallocated minor in use)
1657
      if test:
1658
        node_drbd[minor] = (instance, False)
1659
      else:
1660
        instance = instanceinfo[instance]
1661
        node_drbd[minor] = (instance.name, instance.admin_up)
1662

    
1663
    # and now check them
1664
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1665
    test = not isinstance(used_minors, (tuple, list))
1666
    _ErrorIf(test, self.ENODEDRBD, node,
1667
             "cannot parse drbd status file: %s", str(used_minors))
1668
    if test:
1669
      # we cannot check drbd status
1670
      return
1671

    
1672
    for minor, (iname, must_exist) in node_drbd.items():
1673
      test = minor not in used_minors and must_exist
1674
      _ErrorIf(test, self.ENODEDRBD, node,
1675
               "drbd minor %d of instance %s is not active", minor, iname)
1676
    for minor in used_minors:
1677
      test = minor not in node_drbd
1678
      _ErrorIf(test, self.ENODEDRBD, node,
1679
               "unallocated drbd minor %d is in use", minor)
1680

    
1681
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1682
    """Builds the node OS structures.
1683

1684
    @type ninfo: L{objects.Node}
1685
    @param ninfo: the node to check
1686
    @param nresult: the remote results for the node
1687
    @param nimg: the node image object
1688

1689
    """
1690
    node = ninfo.name
1691
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1692

    
1693
    remote_os = nresult.get(constants.NV_OSLIST, None)
1694
    test = (not isinstance(remote_os, list) or
1695
            not compat.all(isinstance(v, list) and len(v) == 7
1696
                           for v in remote_os))
1697

    
1698
    _ErrorIf(test, self.ENODEOS, node,
1699
             "node hasn't returned valid OS data")
1700

    
1701
    nimg.os_fail = test
1702

    
1703
    if test:
1704
      return
1705

    
1706
    os_dict = {}
1707

    
1708
    for (name, os_path, status, diagnose,
1709
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1710

    
1711
      if name not in os_dict:
1712
        os_dict[name] = []
1713

    
1714
      # parameters is a list of lists instead of list of tuples due to
1715
      # JSON lacking a real tuple type, fix it:
1716
      parameters = [tuple(v) for v in parameters]
1717
      os_dict[name].append((os_path, status, diagnose,
1718
                            set(variants), set(parameters), set(api_ver)))
1719

    
1720
    nimg.oslist = os_dict
1721

    
1722
  def _VerifyNodeOS(self, ninfo, nimg, base):
1723
    """Verifies the node OS list.
1724

1725
    @type ninfo: L{objects.Node}
1726
    @param ninfo: the node to check
1727
    @param nimg: the node image object
1728
    @param base: the 'template' node we match against (e.g. from the master)
1729

1730
    """
1731
    node = ninfo.name
1732
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1733

    
1734
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1735

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

    
1769
    # check any missing OSes
1770
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1771
    _ErrorIf(missing, self.ENODEOS, node,
1772
             "OSes present on reference node %s but missing on this node: %s",
1773
             base.name, utils.CommaJoin(missing))
1774

    
1775
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1776
    """Verifies and updates the node volume data.
1777

1778
    This function will update a L{NodeImage}'s internal structures
1779
    with data from the remote call.
1780

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

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

    
1791
    nimg.lvm_fail = True
1792
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1793
    if vg_name is None:
1794
      pass
1795
    elif isinstance(lvdata, basestring):
1796
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1797
               utils.SafeEncode(lvdata))
1798
    elif not isinstance(lvdata, dict):
1799
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1800
    else:
1801
      nimg.volumes = lvdata
1802
      nimg.lvm_fail = False
1803

    
1804
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1805
    """Verifies and updates the node instance list.
1806

1807
    If the listing was successful, then updates this node's instance
1808
    list. Otherwise, it marks the RPC call as failed for the instance
1809
    list key.
1810

1811
    @type ninfo: L{objects.Node}
1812
    @param ninfo: the node to check
1813
    @param nresult: the remote results for the node
1814
    @param nimg: the node image object
1815

1816
    """
1817
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1818
    test = not isinstance(idata, list)
1819
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1820
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1821
    if test:
1822
      nimg.hyp_fail = True
1823
    else:
1824
      nimg.instances = idata
1825

    
1826
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1827
    """Verifies and computes a node information map
1828

1829
    @type ninfo: L{objects.Node}
1830
    @param ninfo: the node to check
1831
    @param nresult: the remote results for the node
1832
    @param nimg: the node image object
1833
    @param vg_name: the configured VG name
1834

1835
    """
1836
    node = ninfo.name
1837
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1838

    
1839
    # try to read free memory (from the hypervisor)
1840
    hv_info = nresult.get(constants.NV_HVINFO, None)
1841
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1842
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1843
    if not test:
1844
      try:
1845
        nimg.mfree = int(hv_info["memory_free"])
1846
      except (ValueError, TypeError):
1847
        _ErrorIf(True, self.ENODERPC, node,
1848
                 "node returned invalid nodeinfo, check hypervisor")
1849

    
1850
    # FIXME: devise a free space model for file based instances as well
1851
    if vg_name is not None:
1852
      test = (constants.NV_VGLIST not in nresult or
1853
              vg_name not in nresult[constants.NV_VGLIST])
1854
      _ErrorIf(test, self.ENODELVM, node,
1855
               "node didn't return data for the volume group '%s'"
1856
               " - it is either missing or broken", vg_name)
1857
      if not test:
1858
        try:
1859
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1860
        except (ValueError, TypeError):
1861
          _ErrorIf(True, self.ENODERPC, node,
1862
                   "node returned invalid LVM info, check LVM status")
1863

    
1864
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1865
    """Gets per-disk status information for all instances.
1866

1867
    @type nodelist: list of strings
1868
    @param nodelist: Node names
1869
    @type node_image: dict of (name, L{objects.Node})
1870
    @param node_image: Node objects
1871
    @type instanceinfo: dict of (name, L{objects.Instance})
1872
    @param instanceinfo: Instance objects
1873

1874
    """
1875
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1876

    
1877
    node_disks = {}
1878
    node_disks_devonly = {}
1879

    
1880
    for nname in nodelist:
1881
      disks = [(inst, disk)
1882
               for instlist in [node_image[nname].pinst,
1883
                                node_image[nname].sinst]
1884
               for inst in instlist
1885
               for disk in instanceinfo[inst].disks]
1886

    
1887
      if not disks:
1888
        # No need to collect data
1889
        continue
1890

    
1891
      node_disks[nname] = disks
1892

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

    
1897
      for dev in devonly:
1898
        self.cfg.SetDiskID(dev, nname)
1899

    
1900
      node_disks_devonly[nname] = devonly
1901

    
1902
    assert len(node_disks) == len(node_disks_devonly)
1903

    
1904
    # Collect data from all nodes with disks
1905
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1906
                                                          node_disks_devonly)
1907

    
1908
    assert len(result) == len(node_disks)
1909

    
1910
    instdisk = {}
1911

    
1912
    for (nname, nres) in result.items():
1913
      if nres.offline:
1914
        # Ignore offline node
1915
        continue
1916

    
1917
      disks = node_disks[nname]
1918

    
1919
      msg = nres.fail_msg
1920
      _ErrorIf(msg, self.ENODERPC, nname,
1921
               "while getting disk information: %s", nres.fail_msg)
1922
      if msg:
1923
        # No data from this node
1924
        data = len(disks) * [None]
1925
      else:
1926
        data = nres.payload
1927

    
1928
      for ((inst, _), status) in zip(disks, data):
1929
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
1930

    
1931
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
1932
                      len(nnames) <= len(instanceinfo[inst].all_nodes)
1933
                      for inst, nnames in instdisk.items()
1934
                      for nname, statuses in nnames.items())
1935

    
1936
    return instdisk
1937

    
1938
  def BuildHooksEnv(self):
1939
    """Build hooks env.
1940

1941
    Cluster-Verify hooks just ran in the post phase and their failure makes
1942
    the output be logged in the verify output and the verification to fail.
1943

1944
    """
1945
    all_nodes = self.cfg.GetNodeList()
1946
    env = {
1947
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1948
      }
1949
    for node in self.cfg.GetAllNodesInfo().values():
1950
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1951

    
1952
    return env, [], all_nodes
1953

    
1954
  def Exec(self, feedback_fn):
1955
    """Verify integrity of cluster, performing various test on nodes.
1956

1957
    """
1958
    self.bad = False
1959
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1960
    verbose = self.op.verbose
1961
    self._feedback_fn = feedback_fn
1962
    feedback_fn("* Verifying global settings")
1963
    for msg in self.cfg.VerifyConfig():
1964
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1965

    
1966
    # Check the cluster certificates
1967
    for cert_filename in constants.ALL_CERT_FILES:
1968
      (errcode, msg) = _VerifyCertificate(cert_filename)
1969
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1970

    
1971
    vg_name = self.cfg.GetVGName()
1972
    drbd_helper = self.cfg.GetDRBDHelper()
1973
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1974
    cluster = self.cfg.GetClusterInfo()
1975
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1976
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1977
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1978
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1979
                        for iname in instancelist)
1980
    i_non_redundant = [] # Non redundant instances
1981
    i_non_a_balanced = [] # Non auto-balanced instances
1982
    n_offline = 0 # Count of offline nodes
1983
    n_drained = 0 # Count of nodes being drained
1984
    node_vol_should = {}
1985

    
1986
    # FIXME: verify OS list
1987
    # do local checksums
1988
    master_files = [constants.CLUSTER_CONF_FILE]
1989
    master_node = self.master_node = self.cfg.GetMasterNode()
1990
    master_ip = self.cfg.GetMasterIP()
1991

    
1992
    file_names = ssconf.SimpleStore().GetFileList()
1993
    file_names.extend(constants.ALL_CERT_FILES)
1994
    file_names.extend(master_files)
1995
    if cluster.modify_etc_hosts:
1996
      file_names.append(constants.ETC_HOSTS)
1997

    
1998
    local_checksums = utils.FingerprintFiles(file_names)
1999

    
2000
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2001
    node_verify_param = {
2002
      constants.NV_FILELIST: file_names,
2003
      constants.NV_NODELIST: [node.name for node in nodeinfo
2004
                              if not node.offline],
2005
      constants.NV_HYPERVISOR: hypervisors,
2006
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2007
                                  node.secondary_ip) for node in nodeinfo
2008
                                 if not node.offline],
2009
      constants.NV_INSTANCELIST: hypervisors,
2010
      constants.NV_VERSION: None,
2011
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2012
      constants.NV_NODESETUP: None,
2013
      constants.NV_TIME: None,
2014
      constants.NV_MASTERIP: (master_node, master_ip),
2015
      constants.NV_OSLIST: None,
2016
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2017
      }
2018

    
2019
    if vg_name is not None:
2020
      node_verify_param[constants.NV_VGLIST] = None
2021
      node_verify_param[constants.NV_LVLIST] = vg_name
2022
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2023
      node_verify_param[constants.NV_DRBDLIST] = None
2024

    
2025
    if drbd_helper:
2026
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2027

    
2028
    # Build our expected cluster state
2029
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2030
                                                 name=node.name,
2031
                                                 vm_capable=node.vm_capable))
2032
                      for node in nodeinfo)
2033

    
2034
    for instance in instancelist:
2035
      inst_config = instanceinfo[instance]
2036

    
2037
      for nname in inst_config.all_nodes:
2038
        if nname not in node_image:
2039
          # ghost node
2040
          gnode = self.NodeImage(name=nname)
2041
          gnode.ghost = True
2042
          node_image[nname] = gnode
2043

    
2044
      inst_config.MapLVsByNode(node_vol_should)
2045

    
2046
      pnode = inst_config.primary_node
2047
      node_image[pnode].pinst.append(instance)
2048

    
2049
      for snode in inst_config.secondary_nodes:
2050
        nimg = node_image[snode]
2051
        nimg.sinst.append(instance)
2052
        if pnode not in nimg.sbp:
2053
          nimg.sbp[pnode] = []
2054
        nimg.sbp[pnode].append(instance)
2055

    
2056
    # At this point, we have the in-memory data structures complete,
2057
    # except for the runtime information, which we'll gather next
2058

    
2059
    # Due to the way our RPC system works, exact response times cannot be
2060
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2061
    # time before and after executing the request, we can at least have a time
2062
    # window.
2063
    nvinfo_starttime = time.time()
2064
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2065
                                           self.cfg.GetClusterName())
2066
    nvinfo_endtime = time.time()
2067

    
2068
    all_drbd_map = self.cfg.ComputeDRBDMap()
2069

    
2070
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2071
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2072

    
2073
    feedback_fn("* Verifying node status")
2074

    
2075
    refos_img = None
2076

    
2077
    for node_i in nodeinfo:
2078
      node = node_i.name
2079
      nimg = node_image[node]
2080

    
2081
      if node_i.offline:
2082
        if verbose:
2083
          feedback_fn("* Skipping offline node %s" % (node,))
2084
        n_offline += 1
2085
        continue
2086

    
2087
      if node == master_node:
2088
        ntype = "master"
2089
      elif node_i.master_candidate:
2090
        ntype = "master candidate"
2091
      elif node_i.drained:
2092
        ntype = "drained"
2093
        n_drained += 1
2094
      else:
2095
        ntype = "regular"
2096
      if verbose:
2097
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2098

    
2099
      msg = all_nvinfo[node].fail_msg
2100
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2101
      if msg:
2102
        nimg.rpc_fail = True
2103
        continue
2104

    
2105
      nresult = all_nvinfo[node].payload
2106

    
2107
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2108
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2109
      self._VerifyNodeNetwork(node_i, nresult)
2110
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2111
                            master_files)
2112

    
2113
      if nimg.vm_capable:
2114
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2115
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2116
                             all_drbd_map)
2117

    
2118
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2119
        self._UpdateNodeInstances(node_i, nresult, nimg)
2120
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2121
        self._UpdateNodeOS(node_i, nresult, nimg)
2122
        if not nimg.os_fail:
2123
          if refos_img is None:
2124
            refos_img = nimg
2125
          self._VerifyNodeOS(node_i, nimg, refos_img)
2126

    
2127
    feedback_fn("* Verifying instance status")
2128
    for instance in instancelist:
2129
      if verbose:
2130
        feedback_fn("* Verifying instance %s" % instance)
2131
      inst_config = instanceinfo[instance]
2132
      self._VerifyInstance(instance, inst_config, node_image,
2133
                           instdisk[instance])
2134
      inst_nodes_offline = []
2135

    
2136
      pnode = inst_config.primary_node
2137
      pnode_img = node_image[pnode]
2138
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2139
               self.ENODERPC, pnode, "instance %s, connection to"
2140
               " primary node failed", instance)
2141

    
2142
      if pnode_img.offline:
2143
        inst_nodes_offline.append(pnode)
2144

    
2145
      # If the instance is non-redundant we cannot survive losing its primary
2146
      # node, so we are not N+1 compliant. On the other hand we have no disk
2147
      # templates with more than one secondary so that situation is not well
2148
      # supported either.
2149
      # FIXME: does not support file-backed instances
2150
      if not inst_config.secondary_nodes:
2151
        i_non_redundant.append(instance)
2152
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2153
               instance, "instance has multiple secondary nodes: %s",
2154
               utils.CommaJoin(inst_config.secondary_nodes),
2155
               code=self.ETYPE_WARNING)
2156

    
2157
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2158
        i_non_a_balanced.append(instance)
2159

    
2160
      for snode in inst_config.secondary_nodes:
2161
        s_img = node_image[snode]
2162
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2163
                 "instance %s, connection to secondary node failed", instance)
2164

    
2165
        if s_img.offline:
2166
          inst_nodes_offline.append(snode)
2167

    
2168
      # warn that the instance lives on offline nodes
2169
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2170
               "instance lives on offline node(s) %s",
2171
               utils.CommaJoin(inst_nodes_offline))
2172
      # ... or ghost/non-vm_capable nodes
2173
      for node in inst_config.all_nodes:
2174
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2175
                 "instance lives on ghost node %s", node)
2176
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2177
                 instance, "instance lives on non-vm_capable node %s", node)
2178

    
2179
    feedback_fn("* Verifying orphan volumes")
2180
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2181
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2182

    
2183
    feedback_fn("* Verifying orphan instances")
2184
    self._VerifyOrphanInstances(instancelist, node_image)
2185

    
2186
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2187
      feedback_fn("* Verifying N+1 Memory redundancy")
2188
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2189

    
2190
    feedback_fn("* Other Notes")
2191
    if i_non_redundant:
2192
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2193
                  % len(i_non_redundant))
2194

    
2195
    if i_non_a_balanced:
2196
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2197
                  % len(i_non_a_balanced))
2198

    
2199
    if n_offline:
2200
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2201

    
2202
    if n_drained:
2203
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2204

    
2205
    return not self.bad
2206

    
2207
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2208
    """Analyze the post-hooks' result
2209

2210
    This method analyses the hook result, handles it, and sends some
2211
    nicely-formatted feedback back to the user.
2212

2213
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2214
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2215
    @param hooks_results: the results of the multi-node hooks rpc call
2216
    @param feedback_fn: function used send feedback back to the caller
2217
    @param lu_result: previous Exec result
2218
    @return: the new Exec result, based on the previous result
2219
        and hook results
2220

2221
    """
2222
    # We only really run POST phase hooks, and are only interested in
2223
    # their results
2224
    if phase == constants.HOOKS_PHASE_POST:
2225
      # Used to change hooks' output to proper indentation
2226
      indent_re = re.compile('^', re.M)
2227
      feedback_fn("* Hooks Results")
2228
      assert hooks_results, "invalid result from hooks"
2229

    
2230
      for node_name in hooks_results:
2231
        res = hooks_results[node_name]
2232
        msg = res.fail_msg
2233
        test = msg and not res.offline
2234
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2235
                      "Communication failure in hooks execution: %s", msg)
2236
        if res.offline or msg:
2237
          # No need to investigate payload if node is offline or gave an error.
2238
          # override manually lu_result here as _ErrorIf only
2239
          # overrides self.bad
2240
          lu_result = 1
2241
          continue
2242
        for script, hkr, output in res.payload:
2243
          test = hkr == constants.HKR_FAIL
2244
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2245
                        "Script %s failed, output:", script)
2246
          if test:
2247
            output = indent_re.sub('      ', output)
2248
            feedback_fn("%s" % output)
2249
            lu_result = 0
2250

    
2251
      return lu_result
2252

    
2253

    
2254
class LUVerifyDisks(NoHooksLU):
2255
  """Verifies the cluster disks status.
2256

2257
  """
2258
  REQ_BGL = False
2259

    
2260
  def ExpandNames(self):
2261
    self.needed_locks = {
2262
      locking.LEVEL_NODE: locking.ALL_SET,
2263
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2264
    }
2265
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2266

    
2267
  def Exec(self, feedback_fn):
2268
    """Verify integrity of cluster disks.
2269

2270
    @rtype: tuple of three items
2271
    @return: a tuple of (dict of node-to-node_error, list of instances
2272
        which need activate-disks, dict of instance: (node, volume) for
2273
        missing volumes
2274

2275
    """
2276
    result = res_nodes, res_instances, res_missing = {}, [], {}
2277

    
2278
    vg_name = self.cfg.GetVGName()
2279
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2280
    instances = [self.cfg.GetInstanceInfo(name)
2281
                 for name in self.cfg.GetInstanceList()]
2282

    
2283
    nv_dict = {}
2284
    for inst in instances:
2285
      inst_lvs = {}
2286
      if (not inst.admin_up or
2287
          inst.disk_template not in constants.DTS_NET_MIRROR):
2288
        continue
2289
      inst.MapLVsByNode(inst_lvs)
2290
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2291
      for node, vol_list in inst_lvs.iteritems():
2292
        for vol in vol_list:
2293
          nv_dict[(node, vol)] = inst
2294

    
2295
    if not nv_dict:
2296
      return result
2297

    
2298
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2299

    
2300
    for node in nodes:
2301
      # node_volume
2302
      node_res = node_lvs[node]
2303
      if node_res.offline:
2304
        continue
2305
      msg = node_res.fail_msg
2306
      if msg:
2307
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2308
        res_nodes[node] = msg
2309
        continue
2310

    
2311
      lvs = node_res.payload
2312
      for lv_name, (_, _, lv_online) in lvs.items():
2313
        inst = nv_dict.pop((node, lv_name), None)
2314
        if (not lv_online and inst is not None
2315
            and inst.name not in res_instances):
2316
          res_instances.append(inst.name)
2317

    
2318
    # any leftover items in nv_dict are missing LVs, let's arrange the
2319
    # data better
2320
    for key, inst in nv_dict.iteritems():
2321
      if inst.name not in res_missing:
2322
        res_missing[inst.name] = []
2323
      res_missing[inst.name].append(key)
2324

    
2325
    return result
2326

    
2327

    
2328
class LURepairDiskSizes(NoHooksLU):
2329
  """Verifies the cluster disks sizes.
2330

2331
  """
2332
  _OP_PARAMS = [("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString))]
2333
  REQ_BGL = False
2334

    
2335
  def ExpandNames(self):
2336
    if self.op.instances:
2337
      self.wanted_names = []
2338
      for name in self.op.instances:
2339
        full_name = _ExpandInstanceName(self.cfg, name)
2340
        self.wanted_names.append(full_name)
2341
      self.needed_locks = {
2342
        locking.LEVEL_NODE: [],
2343
        locking.LEVEL_INSTANCE: self.wanted_names,
2344
        }
2345
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2346
    else:
2347
      self.wanted_names = None
2348
      self.needed_locks = {
2349
        locking.LEVEL_NODE: locking.ALL_SET,
2350
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2351
        }
2352
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2353

    
2354
  def DeclareLocks(self, level):
2355
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2356
      self._LockInstancesNodes(primary_only=True)
2357

    
2358
  def CheckPrereq(self):
2359
    """Check prerequisites.
2360

2361
    This only checks the optional instance list against the existing names.
2362

2363
    """
2364
    if self.wanted_names is None:
2365
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2366

    
2367
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2368
                             in self.wanted_names]
2369

    
2370
  def _EnsureChildSizes(self, disk):
2371
    """Ensure children of the disk have the needed disk size.
2372

2373
    This is valid mainly for DRBD8 and fixes an issue where the
2374
    children have smaller disk size.
2375

2376
    @param disk: an L{ganeti.objects.Disk} object
2377

2378
    """
2379
    if disk.dev_type == constants.LD_DRBD8:
2380
      assert disk.children, "Empty children for DRBD8?"
2381
      fchild = disk.children[0]
2382
      mismatch = fchild.size < disk.size
2383
      if mismatch:
2384
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2385
                     fchild.size, disk.size)
2386
        fchild.size = disk.size
2387

    
2388
      # and we recurse on this child only, not on the metadev
2389
      return self._EnsureChildSizes(fchild) or mismatch
2390
    else:
2391
      return False
2392

    
2393
  def Exec(self, feedback_fn):
2394
    """Verify the size of cluster disks.
2395

2396
    """
2397
    # TODO: check child disks too
2398
    # TODO: check differences in size between primary/secondary nodes
2399
    per_node_disks = {}
2400
    for instance in self.wanted_instances:
2401
      pnode = instance.primary_node
2402
      if pnode not in per_node_disks:
2403
        per_node_disks[pnode] = []
2404
      for idx, disk in enumerate(instance.disks):
2405
        per_node_disks[pnode].append((instance, idx, disk))
2406

    
2407
    changed = []
2408
    for node, dskl in per_node_disks.items():
2409
      newl = [v[2].Copy() for v in dskl]
2410
      for dsk in newl:
2411
        self.cfg.SetDiskID(dsk, node)
2412
      result = self.rpc.call_blockdev_getsizes(node, newl)
2413
      if result.fail_msg:
2414
        self.LogWarning("Failure in blockdev_getsizes call to node"
2415
                        " %s, ignoring", node)
2416
        continue
2417
      if len(result.data) != len(dskl):
2418
        self.LogWarning("Invalid result from node %s, ignoring node results",
2419
                        node)
2420
        continue
2421
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2422
        if size is None:
2423
          self.LogWarning("Disk %d of instance %s did not return size"
2424
                          " information, ignoring", idx, instance.name)
2425
          continue
2426
        if not isinstance(size, (int, long)):
2427
          self.LogWarning("Disk %d of instance %s did not return valid"
2428
                          " size information, ignoring", idx, instance.name)
2429
          continue
2430
        size = size >> 20
2431
        if size != disk.size:
2432
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2433
                       " correcting: recorded %d, actual %d", idx,
2434
                       instance.name, disk.size, size)
2435
          disk.size = size
2436
          self.cfg.Update(instance, feedback_fn)
2437
          changed.append((instance.name, idx, size))
2438
        if self._EnsureChildSizes(disk):
2439
          self.cfg.Update(instance, feedback_fn)
2440
          changed.append((instance.name, idx, disk.size))
2441
    return changed
2442

    
2443

    
2444
class LURenameCluster(LogicalUnit):
2445
  """Rename the cluster.
2446

2447
  """
2448
  HPATH = "cluster-rename"
2449
  HTYPE = constants.HTYPE_CLUSTER
2450
  _OP_PARAMS = [("name", ht.NoDefault, ht.TNonEmptyString)]
2451

    
2452
  def BuildHooksEnv(self):
2453
    """Build hooks env.
2454

2455
    """
2456
    env = {
2457
      "OP_TARGET": self.cfg.GetClusterName(),
2458
      "NEW_NAME": self.op.name,
2459
      }
2460
    mn = self.cfg.GetMasterNode()
2461
    all_nodes = self.cfg.GetNodeList()
2462
    return env, [mn], all_nodes
2463

    
2464
  def CheckPrereq(self):
2465
    """Verify that the passed name is a valid one.
2466

2467
    """
2468
    hostname = netutils.GetHostname(name=self.op.name,
2469
                                    family=self.cfg.GetPrimaryIPFamily())
2470

    
2471
    new_name = hostname.name
2472
    self.ip = new_ip = hostname.ip
2473
    old_name = self.cfg.GetClusterName()
2474
    old_ip = self.cfg.GetMasterIP()
2475
    if new_name == old_name and new_ip == old_ip:
2476
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2477
                                 " cluster has changed",
2478
                                 errors.ECODE_INVAL)
2479
    if new_ip != old_ip:
2480
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2481
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2482
                                   " reachable on the network" %
2483
                                   new_ip, errors.ECODE_NOTUNIQUE)
2484

    
2485
    self.op.name = new_name
2486

    
2487
  def Exec(self, feedback_fn):
2488
    """Rename the cluster.
2489

2490
    """
2491
    clustername = self.op.name
2492
    ip = self.ip
2493

    
2494
    # shutdown the master IP
2495
    master = self.cfg.GetMasterNode()
2496
    result = self.rpc.call_node_stop_master(master, False)
2497
    result.Raise("Could not disable the master role")
2498

    
2499
    try:
2500
      cluster = self.cfg.GetClusterInfo()
2501
      cluster.cluster_name = clustername
2502
      cluster.master_ip = ip
2503
      self.cfg.Update(cluster, feedback_fn)
2504

    
2505
      # update the known hosts file
2506
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2507
      node_list = self.cfg.GetNodeList()
2508
      try:
2509
        node_list.remove(master)
2510
      except ValueError:
2511
        pass
2512
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2513
    finally:
2514
      result = self.rpc.call_node_start_master(master, False, False)
2515
      msg = result.fail_msg
2516
      if msg:
2517
        self.LogWarning("Could not re-enable the master role on"
2518
                        " the master, please restart manually: %s", msg)
2519

    
2520
    return clustername
2521

    
2522

    
2523
class LUSetClusterParams(LogicalUnit):
2524
  """Change the parameters of the cluster.
2525

2526
  """
2527
  HPATH = "cluster-modify"
2528
  HTYPE = constants.HTYPE_CLUSTER
2529
  _OP_PARAMS = [
2530
    ("vg_name", None, ht.TMaybeString),
2531
    ("enabled_hypervisors", None,
2532
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
2533
            ht.TNone)),
2534
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2535
                              ht.TNone)),
2536
    ("beparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2537
                              ht.TNone)),
2538
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2539
                            ht.TNone)),
2540
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2541
                              ht.TNone)),
2542
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
2543
    ("uid_pool", None, ht.NoType),
2544
    ("add_uids", None, ht.NoType),
2545
    ("remove_uids", None, ht.NoType),
2546
    ("maintain_node_health", None, ht.TMaybeBool),
2547
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
2548
    ("nicparams", None, ht.TOr(ht.TDict, ht.TNone)),
2549
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
2550
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
2551
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
2552
    ("hidden_os", None, ht.TOr(ht.TListOf(\
2553
          ht.TAnd(ht.TList,
2554
                ht.TIsLength(2),
2555
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2556
          ht.TNone)),
2557
    ("blacklisted_os", None, ht.TOr(ht.TListOf(\
2558
          ht.TAnd(ht.TList,
2559
                ht.TIsLength(2),
2560
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2561
          ht.TNone)),
2562
    ]
2563
  REQ_BGL = False
2564

    
2565
  def CheckArguments(self):
2566
    """Check parameters
2567

2568
    """
2569
    if self.op.uid_pool:
2570
      uidpool.CheckUidPool(self.op.uid_pool)
2571

    
2572
    if self.op.add_uids:
2573
      uidpool.CheckUidPool(self.op.add_uids)
2574

    
2575
    if self.op.remove_uids:
2576
      uidpool.CheckUidPool(self.op.remove_uids)
2577

    
2578
  def ExpandNames(self):
2579
    # FIXME: in the future maybe other cluster params won't require checking on
2580
    # all nodes to be modified.
2581
    self.needed_locks = {
2582
      locking.LEVEL_NODE: locking.ALL_SET,
2583
    }
2584
    self.share_locks[locking.LEVEL_NODE] = 1
2585

    
2586
  def BuildHooksEnv(self):
2587
    """Build hooks env.
2588

2589
    """
2590
    env = {
2591
      "OP_TARGET": self.cfg.GetClusterName(),
2592
      "NEW_VG_NAME": self.op.vg_name,
2593
      }
2594
    mn = self.cfg.GetMasterNode()
2595
    return env, [mn], [mn]
2596

    
2597
  def CheckPrereq(self):
2598
    """Check prerequisites.
2599

2600
    This checks whether the given params don't conflict and
2601
    if the given volume group is valid.
2602

2603
    """
2604
    if self.op.vg_name is not None and not self.op.vg_name:
2605
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2606
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2607
                                   " instances exist", errors.ECODE_INVAL)
2608

    
2609
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2610
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2611
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2612
                                   " drbd-based instances exist",
2613
                                   errors.ECODE_INVAL)
2614

    
2615
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2616

    
2617
    # if vg_name not None, checks given volume group on all nodes
2618
    if self.op.vg_name:
2619
      vglist = self.rpc.call_vg_list(node_list)
2620
      for node in node_list:
2621
        msg = vglist[node].fail_msg
2622
        if msg:
2623
          # ignoring down node
2624
          self.LogWarning("Error while gathering data on node %s"
2625
                          " (ignoring node): %s", node, msg)
2626
          continue
2627
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2628
                                              self.op.vg_name,
2629
                                              constants.MIN_VG_SIZE)
2630
        if vgstatus:
2631
          raise errors.OpPrereqError("Error on node '%s': %s" %
2632
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2633

    
2634
    if self.op.drbd_helper:
2635
      # checks given drbd helper on all nodes
2636
      helpers = self.rpc.call_drbd_helper(node_list)
2637
      for node in node_list:
2638
        ninfo = self.cfg.GetNodeInfo(node)
2639
        if ninfo.offline:
2640
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2641
          continue
2642
        msg = helpers[node].fail_msg
2643
        if msg:
2644
          raise errors.OpPrereqError("Error checking drbd helper on node"
2645
                                     " '%s': %s" % (node, msg),
2646
                                     errors.ECODE_ENVIRON)
2647
        node_helper = helpers[node].payload
2648
        if node_helper != self.op.drbd_helper:
2649
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2650
                                     (node, node_helper), errors.ECODE_ENVIRON)
2651

    
2652
    self.cluster = cluster = self.cfg.GetClusterInfo()
2653
    # validate params changes
2654
    if self.op.beparams:
2655
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2656
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2657

    
2658
    if self.op.nicparams:
2659
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2660
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2661
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2662
      nic_errors = []
2663

    
2664
      # check all instances for consistency
2665
      for instance in self.cfg.GetAllInstancesInfo().values():
2666
        for nic_idx, nic in enumerate(instance.nics):
2667
          params_copy = copy.deepcopy(nic.nicparams)
2668
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2669

    
2670
          # check parameter syntax
2671
          try:
2672
            objects.NIC.CheckParameterSyntax(params_filled)
2673
          except errors.ConfigurationError, err:
2674
            nic_errors.append("Instance %s, nic/%d: %s" %
2675
                              (instance.name, nic_idx, err))
2676

    
2677
          # if we're moving instances to routed, check that they have an ip
2678
          target_mode = params_filled[constants.NIC_MODE]
2679
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2680
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2681
                              (instance.name, nic_idx))
2682
      if nic_errors:
2683
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2684
                                   "\n".join(nic_errors))
2685

    
2686
    # hypervisor list/parameters
2687
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2688
    if self.op.hvparams:
2689
      for hv_name, hv_dict in self.op.hvparams.items():
2690
        if hv_name not in self.new_hvparams:
2691
          self.new_hvparams[hv_name] = hv_dict
2692
        else:
2693
          self.new_hvparams[hv_name].update(hv_dict)
2694

    
2695
    # os hypervisor parameters
2696
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2697
    if self.op.os_hvp:
2698
      for os_name, hvs in self.op.os_hvp.items():
2699
        if os_name not in self.new_os_hvp:
2700
          self.new_os_hvp[os_name] = hvs
2701
        else:
2702
          for hv_name, hv_dict in hvs.items():
2703
            if hv_name not in self.new_os_hvp[os_name]:
2704
              self.new_os_hvp[os_name][hv_name] = hv_dict
2705
            else:
2706
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2707

    
2708
    # os parameters
2709
    self.new_osp = objects.FillDict(cluster.osparams, {})
2710
    if self.op.osparams:
2711
      for os_name, osp in self.op.osparams.items():
2712
        if os_name not in self.new_osp:
2713
          self.new_osp[os_name] = {}
2714

    
2715
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2716
                                                  use_none=True)
2717

    
2718
        if not self.new_osp[os_name]:
2719
          # we removed all parameters
2720
          del self.new_osp[os_name]
2721
        else:
2722
          # check the parameter validity (remote check)
2723
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2724
                         os_name, self.new_osp[os_name])
2725

    
2726
    # changes to the hypervisor list
2727
    if self.op.enabled_hypervisors is not None:
2728
      self.hv_list = self.op.enabled_hypervisors
2729
      for hv in self.hv_list:
2730
        # if the hypervisor doesn't already exist in the cluster
2731
        # hvparams, we initialize it to empty, and then (in both
2732
        # cases) we make sure to fill the defaults, as we might not
2733
        # have a complete defaults list if the hypervisor wasn't
2734
        # enabled before
2735
        if hv not in new_hvp:
2736
          new_hvp[hv] = {}
2737
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2738
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2739
    else:
2740
      self.hv_list = cluster.enabled_hypervisors
2741

    
2742
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2743
      # either the enabled list has changed, or the parameters have, validate
2744
      for hv_name, hv_params in self.new_hvparams.items():
2745
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2746
            (self.op.enabled_hypervisors and
2747
             hv_name in self.op.enabled_hypervisors)):
2748
          # either this is a new hypervisor, or its parameters have changed
2749
          hv_class = hypervisor.GetHypervisor(hv_name)
2750
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2751
          hv_class.CheckParameterSyntax(hv_params)
2752
          _CheckHVParams(self, node_list, hv_name, hv_params)
2753

    
2754
    if self.op.os_hvp:
2755
      # no need to check any newly-enabled hypervisors, since the
2756
      # defaults have already been checked in the above code-block
2757
      for os_name, os_hvp in self.new_os_hvp.items():
2758
        for hv_name, hv_params in os_hvp.items():
2759
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2760
          # we need to fill in the new os_hvp on top of the actual hv_p
2761
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2762
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2763
          hv_class = hypervisor.GetHypervisor(hv_name)
2764
          hv_class.CheckParameterSyntax(new_osp)
2765
          _CheckHVParams(self, node_list, hv_name, new_osp)
2766

    
2767
    if self.op.default_iallocator:
2768
      alloc_script = utils.FindFile(self.op.default_iallocator,
2769
                                    constants.IALLOCATOR_SEARCH_PATH,
2770
                                    os.path.isfile)
2771
      if alloc_script is None:
2772
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2773
                                   " specified" % self.op.default_iallocator,
2774
                                   errors.ECODE_INVAL)
2775

    
2776
  def Exec(self, feedback_fn):
2777
    """Change the parameters of the cluster.
2778

2779
    """
2780
    if self.op.vg_name is not None:
2781
      new_volume = self.op.vg_name
2782
      if not new_volume:
2783
        new_volume = None
2784
      if new_volume != self.cfg.GetVGName():
2785
        self.cfg.SetVGName(new_volume)
2786
      else:
2787
        feedback_fn("Cluster LVM configuration already in desired"
2788
                    " state, not changing")
2789
    if self.op.drbd_helper is not None:
2790
      new_helper = self.op.drbd_helper
2791
      if not new_helper:
2792
        new_helper = None
2793
      if new_helper != self.cfg.GetDRBDHelper():
2794
        self.cfg.SetDRBDHelper(new_helper)
2795
      else:
2796
        feedback_fn("Cluster DRBD helper already in desired state,"
2797
                    " not changing")
2798
    if self.op.hvparams:
2799
      self.cluster.hvparams = self.new_hvparams
2800
    if self.op.os_hvp:
2801
      self.cluster.os_hvp = self.new_os_hvp
2802
    if self.op.enabled_hypervisors is not None:
2803
      self.cluster.hvparams = self.new_hvparams
2804
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2805
    if self.op.beparams:
2806
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2807
    if self.op.nicparams:
2808
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2809
    if self.op.osparams:
2810
      self.cluster.osparams = self.new_osp
2811

    
2812
    if self.op.candidate_pool_size is not None:
2813
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2814
      # we need to update the pool size here, otherwise the save will fail
2815
      _AdjustCandidatePool(self, [])
2816

    
2817
    if self.op.maintain_node_health is not None:
2818
      self.cluster.maintain_node_health = self.op.maintain_node_health
2819

    
2820
    if self.op.prealloc_wipe_disks is not None:
2821
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2822

    
2823
    if self.op.add_uids is not None:
2824
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2825

    
2826
    if self.op.remove_uids is not None:
2827
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2828

    
2829
    if self.op.uid_pool is not None:
2830
      self.cluster.uid_pool = self.op.uid_pool
2831

    
2832
    if self.op.default_iallocator is not None:
2833
      self.cluster.default_iallocator = self.op.default_iallocator
2834

    
2835
    if self.op.reserved_lvs is not None:
2836
      self.cluster.reserved_lvs = self.op.reserved_lvs
2837

    
2838
    def helper_os(aname, mods, desc):
2839
      desc += " OS list"
2840
      lst = getattr(self.cluster, aname)
2841
      for key, val in mods:
2842
        if key == constants.DDM_ADD:
2843
          if val in lst:
2844
            feedback_fn("OS %s already in %s, ignoring", val, desc)
2845
          else:
2846
            lst.append(val)
2847
        elif key == constants.DDM_REMOVE:
2848
          if val in lst:
2849
            lst.remove(val)
2850
          else:
2851
            feedback_fn("OS %s not found in %s, ignoring", val, desc)
2852
        else:
2853
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2854

    
2855
    if self.op.hidden_os:
2856
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2857

    
2858
    if self.op.blacklisted_os:
2859
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2860

    
2861
    self.cfg.Update(self.cluster, feedback_fn)
2862

    
2863

    
2864
def _UploadHelper(lu, nodes, fname):
2865
  """Helper for uploading a file and showing warnings.
2866

2867
  """
2868
  if os.path.exists(fname):
2869
    result = lu.rpc.call_upload_file(nodes, fname)
2870
    for to_node, to_result in result.items():
2871
      msg = to_result.fail_msg
2872
      if msg:
2873
        msg = ("Copy of file %s to node %s failed: %s" %
2874
               (fname, to_node, msg))
2875
        lu.proc.LogWarning(msg)
2876

    
2877

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

2881
  ConfigWriter takes care of distributing the config and ssconf files, but
2882
  there are more files which should be distributed to all nodes. This function
2883
  makes sure those are copied.
2884

2885
  @param lu: calling logical unit
2886
  @param additional_nodes: list of nodes not in the config to distribute to
2887
  @type additional_vm: boolean
2888
  @param additional_vm: whether the additional nodes are vm-capable or not
2889

2890
  """
2891
  # 1. Gather target nodes
2892
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2893
  dist_nodes = lu.cfg.GetOnlineNodeList()
2894
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
2895
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
2896
  if additional_nodes is not None:
2897
    dist_nodes.extend(additional_nodes)
2898
    if additional_vm:
2899
      vm_nodes.extend(additional_nodes)
2900
  if myself.name in dist_nodes:
2901
    dist_nodes.remove(myself.name)
2902
  if myself.name in vm_nodes:
2903
    vm_nodes.remove(myself.name)
2904

    
2905
  # 2. Gather files to distribute
2906
  dist_files = set([constants.ETC_HOSTS,
2907
                    constants.SSH_KNOWN_HOSTS_FILE,
2908
                    constants.RAPI_CERT_FILE,
2909
                    constants.RAPI_USERS_FILE,
2910
                    constants.CONFD_HMAC_KEY,
2911
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2912
                   ])
2913

    
2914
  vm_files = set()
2915
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2916
  for hv_name in enabled_hypervisors:
2917
    hv_class = hypervisor.GetHypervisor(hv_name)
2918
    vm_files.update(hv_class.GetAncillaryFiles())
2919

    
2920
  # 3. Perform the files upload
2921
  for fname in dist_files:
2922
    _UploadHelper(lu, dist_nodes, fname)
2923
  for fname in vm_files:
2924
    _UploadHelper(lu, vm_nodes, fname)
2925

    
2926

    
2927
class LURedistributeConfig(NoHooksLU):
2928
  """Force the redistribution of cluster configuration.
2929

2930
  This is a very simple LU.
2931

2932
  """
2933
  REQ_BGL = False
2934

    
2935
  def ExpandNames(self):
2936
    self.needed_locks = {
2937
      locking.LEVEL_NODE: locking.ALL_SET,
2938
    }
2939
    self.share_locks[locking.LEVEL_NODE] = 1
2940

    
2941
  def Exec(self, feedback_fn):
2942
    """Redistribute the configuration.
2943

2944
    """
2945
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2946
    _RedistributeAncillaryFiles(self)
2947

    
2948

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

2952
  """
2953
  if not instance.disks or disks is not None and not disks:
2954
    return True
2955

    
2956
  disks = _ExpandCheckDisks(instance, disks)
2957

    
2958
  if not oneshot:
2959
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2960

    
2961
  node = instance.primary_node
2962

    
2963
  for dev in disks:
2964
    lu.cfg.SetDiskID(dev, node)
2965

    
2966
  # TODO: Convert to utils.Retry
2967

    
2968
  retries = 0
2969
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2970
  while True:
2971
    max_time = 0
2972
    done = True
2973
    cumul_degraded = False
2974
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2975
    msg = rstats.fail_msg
2976
    if msg:
2977
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2978
      retries += 1
2979
      if retries >= 10:
2980
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2981
                                 " aborting." % node)
2982
      time.sleep(6)
2983
      continue
2984
    rstats = rstats.payload
2985
    retries = 0
2986
    for i, mstat in enumerate(rstats):
2987
      if mstat is None:
2988
        lu.LogWarning("Can't compute data for node %s/%s",
2989
                           node, disks[i].iv_name)
2990
        continue
2991

    
2992
      cumul_degraded = (cumul_degraded or
2993
                        (mstat.is_degraded and mstat.sync_percent is None))
2994
      if mstat.sync_percent is not None:
2995
        done = False
2996
        if mstat.estimated_time is not None:
2997
          rem_time = ("%s remaining (estimated)" %
2998
                      utils.FormatSeconds(mstat.estimated_time))
2999
          max_time = mstat.estimated_time
3000
        else:
3001
          rem_time = "no time estimate"
3002
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3003
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3004

    
3005
    # if we're done but degraded, let's do a few small retries, to
3006
    # make sure we see a stable and not transient situation; therefore
3007
    # we force restart of the loop
3008
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3009
      logging.info("Degraded disks found, %d retries left", degr_retries)
3010
      degr_retries -= 1
3011
      time.sleep(1)
3012
      continue
3013

    
3014
    if done or oneshot:
3015
      break
3016

    
3017
    time.sleep(min(60, max_time))
3018

    
3019
  if done:
3020
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3021
  return not cumul_degraded
3022

    
3023

    
3024
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3025
  """Check that mirrors are not degraded.
3026

3027
  The ldisk parameter, if True, will change the test from the
3028
  is_degraded attribute (which represents overall non-ok status for
3029
  the device(s)) to the ldisk (representing the local storage status).
3030

3031
  """
3032
  lu.cfg.SetDiskID(dev, node)
3033

    
3034
  result = True
3035

    
3036
  if on_primary or dev.AssembleOnSecondary():
3037
    rstats = lu.rpc.call_blockdev_find(node, dev)
3038
    msg = rstats.fail_msg
3039
    if msg:
3040
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3041
      result = False
3042
    elif not rstats.payload:
3043
      lu.LogWarning("Can't find disk on node %s", node)
3044
      result = False
3045
    else:
3046
      if ldisk:
3047
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3048
      else:
3049
        result = result and not rstats.payload.is_degraded
3050

    
3051
  if dev.children:
3052
    for child in dev.children:
3053
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3054

    
3055
  return result
3056

    
3057

    
3058
class LUDiagnoseOS(NoHooksLU):
3059
  """Logical unit for OS diagnose/query.
3060

3061
  """
3062
  _OP_PARAMS = [
3063
    _POutputFields,
3064
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3065
    ]
3066
  REQ_BGL = False
3067
  _HID = "hidden"
3068
  _BLK = "blacklisted"
3069
  _VLD = "valid"
3070
  _FIELDS_STATIC = utils.FieldSet()
3071
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3072
                                   "parameters", "api_versions", _HID, _BLK)
3073

    
3074
  def CheckArguments(self):
3075
    if self.op.names:
3076
      raise errors.OpPrereqError("Selective OS query not supported",
3077
                                 errors.ECODE_INVAL)
3078

    
3079
    _CheckOutputFields(static=self._FIELDS_STATIC,
3080
                       dynamic=self._FIELDS_DYNAMIC,
3081
                       selected=self.op.output_fields)
3082

    
3083
  def ExpandNames(self):
3084
    # Lock all nodes, in shared mode
3085
    # Temporary removal of locks, should be reverted later
3086
    # TODO: reintroduce locks when they are lighter-weight
3087
    self.needed_locks = {}
3088
    #self.share_locks[locking.LEVEL_NODE] = 1
3089
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3090

    
3091
  @staticmethod
3092
  def _DiagnoseByOS(rlist):
3093
    """Remaps a per-node return list into an a per-os per-node dictionary
3094

3095
    @param rlist: a map with node names as keys and OS objects as values
3096

3097
    @rtype: dict
3098
    @return: a dictionary with osnames as keys and as value another
3099
        map, with nodes as keys and tuples of (path, status, diagnose,
3100
        variants, parameters, api_versions) as values, eg::
3101

3102
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3103
                                     (/srv/..., False, "invalid api")],
3104
                           "node2": [(/srv/..., True, "", [], [])]}
3105
          }
3106

3107
    """
3108
    all_os = {}
3109
    # we build here the list of nodes that didn't fail the RPC (at RPC
3110
    # level), so that nodes with a non-responding node daemon don't
3111
    # make all OSes invalid
3112
    good_nodes = [node_name for node_name in rlist
3113
                  if not rlist[node_name].fail_msg]
3114
    for node_name, nr in rlist.items():
3115
      if nr.fail_msg or not nr.payload:
3116
        continue
3117
      for (name, path, status, diagnose, variants,
3118
           params, api_versions) in nr.payload:
3119
        if name not in all_os:
3120
          # build a list of nodes for this os containing empty lists
3121
          # for each node in node_list
3122
          all_os[name] = {}
3123
          for nname in good_nodes:
3124
            all_os[name][nname] = []
3125
        # convert params from [name, help] to (name, help)
3126
        params = [tuple(v) for v in params]
3127
        all_os[name][node_name].append((path, status, diagnose,
3128
                                        variants, params, api_versions))
3129
    return all_os
3130

    
3131
  def Exec(self, feedback_fn):
3132
    """Compute the list of OSes.
3133

3134
    """
3135
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3136
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3137
    pol = self._DiagnoseByOS(node_data)
3138
    output = []
3139
    cluster = self.cfg.GetClusterInfo()
3140

    
3141
    for os_name in utils.NiceSort(pol.keys()):
3142
      os_data = pol[os_name]
3143
      row = []
3144
      valid = True
3145
      (variants, params, api_versions) = null_state = (set(), set(), set())
3146
      for idx, osl in enumerate(os_data.values()):
3147
        valid = bool(valid and osl and osl[0][1])
3148
        if not valid:
3149
          (variants, params, api_versions) = null_state
3150
          break
3151
        node_variants, node_params, node_api = osl[0][3:6]
3152
        if idx == 0: # first entry
3153
          variants = set(node_variants)
3154
          params = set(node_params)
3155
          api_versions = set(node_api)
3156
        else: # keep consistency
3157
          variants.intersection_update(node_variants)
3158
          params.intersection_update(node_params)
3159
          api_versions.intersection_update(node_api)
3160

    
3161
      is_hid = os_name in cluster.hidden_os
3162
      is_blk = os_name in cluster.blacklisted_os
3163
      if ((self._HID not in self.op.output_fields and is_hid) or
3164
          (self._BLK not in self.op.output_fields and is_blk) or
3165
          (self._VLD not in self.op.output_fields and not valid)):
3166
        continue
3167

    
3168
      for field in self.op.output_fields:
3169
        if field == "name":
3170
          val = os_name
3171
        elif field == self._VLD:
3172
          val = valid
3173
        elif field == "node_status":
3174
          # this is just a copy of the dict
3175
          val = {}
3176
          for node_name, nos_list in os_data.items():
3177
            val[node_name] = nos_list
3178
        elif field == "variants":
3179
          val = utils.NiceSort(list(variants))
3180
        elif field == "parameters":
3181
          val = list(params)
3182
        elif field == "api_versions":
3183
          val = list(api_versions)
3184
        elif field == self._HID:
3185
          val = is_hid
3186
        elif field == self._BLK:
3187
          val = is_blk
3188
        else:
3189
          raise errors.ParameterError(field)
3190
        row.append(val)
3191
      output.append(row)
3192

    
3193
    return output
3194

    
3195

    
3196
class LURemoveNode(LogicalUnit):
3197
  """Logical unit for removing a node.
3198

3199
  """
3200
  HPATH = "node-remove"
3201
  HTYPE = constants.HTYPE_NODE
3202
  _OP_PARAMS = [
3203
    _PNodeName,
3204
    ]
3205

    
3206
  def BuildHooksEnv(self):
3207
    """Build hooks env.
3208

3209
    This doesn't run on the target node in the pre phase as a failed
3210
    node would then be impossible to remove.
3211

3212
    """
3213
    env = {
3214
      "OP_TARGET": self.op.node_name,
3215
      "NODE_NAME": self.op.node_name,
3216
      }
3217
    all_nodes = self.cfg.GetNodeList()
3218
    try:
3219
      all_nodes.remove(self.op.node_name)
3220
    except ValueError:
3221
      logging.warning("Node %s which is about to be removed not found"
3222
                      " in the all nodes list", self.op.node_name)
3223
    return env, all_nodes, all_nodes
3224

    
3225
  def CheckPrereq(self):
3226
    """Check prerequisites.
3227

3228
    This checks:
3229
     - the node exists in the configuration
3230
     - it does not have primary or secondary instances
3231
     - it's not the master
3232

3233
    Any errors are signaled by raising errors.OpPrereqError.
3234

3235
    """
3236
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3237
    node = self.cfg.GetNodeInfo(self.op.node_name)
3238
    assert node is not None
3239

    
3240
    instance_list = self.cfg.GetInstanceList()
3241

    
3242
    masternode = self.cfg.GetMasterNode()
3243
    if node.name == masternode:
3244
      raise errors.OpPrereqError("Node is the master node,"
3245
                                 " you need to failover first.",
3246
                                 errors.ECODE_INVAL)
3247

    
3248
    for instance_name in instance_list:
3249
      instance = self.cfg.GetInstanceInfo(instance_name)
3250
      if node.name in instance.all_nodes:
3251
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3252
                                   " please remove first." % instance_name,
3253
                                   errors.ECODE_INVAL)
3254
    self.op.node_name = node.name
3255
    self.node = node
3256

    
3257
  def Exec(self, feedback_fn):
3258
    """Removes the node from the cluster.
3259

3260
    """
3261
    node = self.node
3262
    logging.info("Stopping the node daemon and removing configs from node %s",
3263
                 node.name)
3264

    
3265
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3266

    
3267
    # Promote nodes to master candidate as needed
3268
    _AdjustCandidatePool(self, exceptions=[node.name])
3269
    self.context.RemoveNode(node.name)
3270

    
3271
    # Run post hooks on the node before it's removed
3272
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3273
    try:
3274
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3275
    except:
3276
      # pylint: disable-msg=W0702
3277
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3278

    
3279
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3280
    msg = result.fail_msg
3281
    if msg:
3282
      self.LogWarning("Errors encountered on the remote node while leaving"
3283
                      " the cluster: %s", msg)
3284

    
3285
    # Remove node from our /etc/hosts
3286
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3287
      master_node = self.cfg.GetMasterNode()
3288
      result = self.rpc.call_etc_hosts_modify(master_node,
3289
                                              constants.ETC_HOSTS_REMOVE,
3290
                                              node.name, None)
3291
      result.Raise("Can't update hosts file with new host data")
3292
      _RedistributeAncillaryFiles(self)
3293

    
3294

    
3295
class LUQueryNodes(NoHooksLU):
3296
  """Logical unit for querying nodes.
3297

3298
  """
3299
  # pylint: disable-msg=W0142
3300
  _OP_PARAMS = [
3301
    _POutputFields,
3302
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3303
    ("use_locking", False, ht.TBool),
3304
    ]
3305
  REQ_BGL = False
3306

    
3307
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3308
                    "master_candidate", "offline", "drained",
3309
                    "master_capable", "vm_capable"]
3310

    
3311
  _FIELDS_DYNAMIC = utils.FieldSet(
3312
    "dtotal", "dfree",
3313
    "mtotal", "mnode", "mfree",
3314
    "bootid",
3315
    "ctotal", "cnodes", "csockets",
3316
    )
3317

    
3318
  _FIELDS_STATIC = utils.FieldSet(*[
3319
    "pinst_cnt", "sinst_cnt",
3320
    "pinst_list", "sinst_list",
3321
    "pip", "sip", "tags",
3322
    "master",
3323
    "role"] + _SIMPLE_FIELDS
3324
    )
3325

    
3326
  def CheckArguments(self):
3327
    _CheckOutputFields(static=self._FIELDS_STATIC,
3328
                       dynamic=self._FIELDS_DYNAMIC,
3329
                       selected=self.op.output_fields)
3330

    
3331
  def ExpandNames(self):
3332
    self.needed_locks = {}
3333
    self.share_locks[locking.LEVEL_NODE] = 1
3334

    
3335
    if self.op.names:
3336
      self.wanted = _GetWantedNodes(self, self.op.names)
3337
    else:
3338
      self.wanted = locking.ALL_SET
3339

    
3340
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3341
    self.do_locking = self.do_node_query and self.op.use_locking
3342
    if self.do_locking:
3343
      # if we don't request only static fields, we need to lock the nodes
3344
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3345

    
3346
  def Exec(self, feedback_fn):
3347
    """Computes the list of nodes and their attributes.
3348

3349
    """
3350
    all_info = self.cfg.GetAllNodesInfo()
3351
    if self.do_locking:
3352
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3353
    elif self.wanted != locking.ALL_SET:
3354
      nodenames = self.wanted
3355
      missing = set(nodenames).difference(all_info.keys())
3356
      if missing:
3357
        raise errors.OpExecError(
3358
          "Some nodes were removed before retrieving their data: %s" % missing)
3359
    else:
3360
      nodenames = all_info.keys()
3361

    
3362
    nodenames = utils.NiceSort(nodenames)
3363
    nodelist = [all_info[name] for name in nodenames]
3364

    
3365
    # begin data gathering
3366

    
3367
    if self.do_node_query:
3368
      live_data = {}
3369
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3370
                                          self.cfg.GetHypervisorType())
3371
      for name in nodenames:
3372
        nodeinfo = node_data[name]
3373
        if not nodeinfo.fail_msg and nodeinfo.payload:
3374
          nodeinfo = nodeinfo.payload
3375
          fn = utils.TryConvert
3376
          live_data[name] = {
3377
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3378
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3379
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3380
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3381
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3382
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3383
            "bootid": nodeinfo.get('bootid', None),
3384
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3385
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3386
            }
3387
        else:
3388
          live_data[name] = {}
3389
    else:
3390
      live_data = dict.fromkeys(nodenames, {})
3391

    
3392
    node_to_primary = dict([(name, set()) for name in nodenames])
3393
    node_to_secondary = dict([(name, set()) for name in nodenames])
3394

    
3395
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3396
                             "sinst_cnt", "sinst_list"))
3397
    if inst_fields & frozenset(self.op.output_fields):
3398
      inst_data = self.cfg.GetAllInstancesInfo()
3399

    
3400
      for inst in inst_data.values():
3401
        if inst.primary_node in node_to_primary:
3402
          node_to_primary[inst.primary_node].add(inst.name)
3403
        for secnode in inst.secondary_nodes:
3404
          if secnode in node_to_secondary:
3405
            node_to_secondary[secnode].add(inst.name)
3406

    
3407
    master_node = self.cfg.GetMasterNode()
3408

    
3409
    # end data gathering
3410

    
3411
    output = []
3412
    for node in nodelist:
3413
      node_output = []
3414
      for field in self.op.output_fields:
3415
        if field in self._SIMPLE_FIELDS:
3416
          val = getattr(node, field)
3417
        elif field == "pinst_list":
3418
          val = list(node_to_primary[node.name])
3419
        elif field == "sinst_list":
3420
          val = list(node_to_secondary[node.name])
3421
        elif field == "pinst_cnt":
3422
          val = len(node_to_primary[node.name])
3423
        elif field == "sinst_cnt":
3424
          val = len(node_to_secondary[node.name])
3425
        elif field == "pip":
3426
          val = node.primary_ip
3427
        elif field == "sip":
3428
          val = node.secondary_ip
3429
        elif field == "tags":
3430
          val = list(node.GetTags())
3431
        elif field == "master":
3432
          val = node.name == master_node
3433
        elif self._FIELDS_DYNAMIC.Matches(field):
3434
          val = live_data[node.name].get(field, None)
3435
        elif field == "role":
3436
          if node.name == master_node:
3437
            val = "M"
3438
          elif node.master_candidate:
3439
            val = "C"
3440
          elif node.drained:
3441
            val = "D"
3442
          elif node.offline:
3443
            val = "O"
3444
          else:
3445
            val = "R"
3446
        else:
3447
          raise errors.ParameterError(field)
3448
        node_output.append(val)
3449
      output.append(node_output)
3450

    
3451
    return output
3452

    
3453

    
3454
class LUQueryNodeVolumes(NoHooksLU):
3455
  """Logical unit for getting volumes on node(s).
3456

3457
  """
3458
  _OP_PARAMS = [
3459
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3460
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3461
    ]
3462
  REQ_BGL = False
3463
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3464
  _FIELDS_STATIC = utils.FieldSet("node")
3465

    
3466
  def CheckArguments(self):
3467
    _CheckOutputFields(static=self._FIELDS_STATIC,
3468
                       dynamic=self._FIELDS_DYNAMIC,
3469
                       selected=self.op.output_fields)
3470

    
3471
  def ExpandNames(self):
3472
    self.needed_locks = {}
3473
    self.share_locks[locking.LEVEL_NODE] = 1
3474
    if not self.op.nodes:
3475
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3476
    else:
3477
      self.needed_locks[locking.LEVEL_NODE] = \
3478
        _GetWantedNodes(self, self.op.nodes)
3479

    
3480
  def Exec(self, feedback_fn):
3481
    """Computes the list of nodes and their attributes.
3482

3483
    """
3484
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3485
    volumes = self.rpc.call_node_volumes(nodenames)
3486

    
3487
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3488
             in self.cfg.GetInstanceList()]
3489

    
3490
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3491

    
3492
    output = []
3493
    for node in nodenames:
3494
      nresult = volumes[node]
3495
      if nresult.offline:
3496
        continue
3497
      msg = nresult.fail_msg
3498
      if msg:
3499
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3500
        continue
3501

    
3502
      node_vols = nresult.payload[:]
3503
      node_vols.sort(key=lambda vol: vol['dev'])
3504

    
3505
      for vol in node_vols:
3506
        node_output = []
3507
        for field in self.op.output_fields:
3508
          if field == "node":
3509
            val = node
3510
          elif field == "phys":
3511
            val = vol['dev']
3512
          elif field == "vg":
3513
            val = vol['vg']
3514
          elif field == "name":
3515
            val = vol['name']
3516
          elif field == "size":
3517
            val = int(float(vol['size']))
3518
          elif field == "instance":
3519
            for inst in ilist:
3520
              if node not in lv_by_node[inst]:
3521
                continue
3522
              if vol['name'] in lv_by_node[inst][node]:
3523
                val = inst.name
3524
                break
3525
            else:
3526
              val = '-'
3527
          else:
3528
            raise errors.ParameterError(field)
3529
          node_output.append(str(val))
3530

    
3531
        output.append(node_output)
3532

    
3533
    return output
3534

    
3535

    
3536
class LUQueryNodeStorage(NoHooksLU):
3537
  """Logical unit for getting information on storage units on node(s).
3538

3539
  """
3540
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3541
  _OP_PARAMS = [
3542
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3543
    ("storage_type", ht.NoDefault, _CheckStorageType),
3544
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3545
    ("name", None, ht.TMaybeString),
3546
    ]
3547
  REQ_BGL = False
3548

    
3549
  def CheckArguments(self):
3550
    _CheckOutputFields(static=self._FIELDS_STATIC,
3551
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3552
                       selected=self.op.output_fields)
3553

    
3554
  def ExpandNames(self):
3555
    self.needed_locks = {}
3556
    self.share_locks[locking.LEVEL_NODE] = 1
3557

    
3558
    if self.op.nodes:
3559
      self.needed_locks[locking.LEVEL_NODE] = \
3560
        _GetWantedNodes(self, self.op.nodes)
3561
    else:
3562
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3563

    
3564
  def Exec(self, feedback_fn):
3565
    """Computes the list of nodes and their attributes.
3566

3567
    """
3568
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3569

    
3570
    # Always get name to sort by
3571
    if constants.SF_NAME in self.op.output_fields:
3572
      fields = self.op.output_fields[:]
3573
    else:
3574
      fields = [constants.SF_NAME] + self.op.output_fields
3575

    
3576
    # Never ask for node or type as it's only known to the LU
3577
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3578
      while extra in fields:
3579
        fields.remove(extra)
3580

    
3581
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3582
    name_idx = field_idx[constants.SF_NAME]
3583

    
3584
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3585
    data = self.rpc.call_storage_list(self.nodes,
3586
                                      self.op.storage_type, st_args,
3587
                                      self.op.name, fields)
3588

    
3589
    result = []
3590

    
3591
    for node in utils.NiceSort(self.nodes):
3592
      nresult = data[node]
3593
      if nresult.offline:
3594
        continue
3595

    
3596
      msg = nresult.fail_msg
3597
      if msg:
3598
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3599
        continue
3600

    
3601
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3602

    
3603
      for name in utils.NiceSort(rows.keys()):
3604
        row = rows[name]
3605

    
3606
        out = []
3607

    
3608
        for field in self.op.output_fields:
3609
          if field == constants.SF_NODE:
3610
            val = node
3611
          elif field == constants.SF_TYPE:
3612
            val = self.op.storage_type
3613
          elif field in field_idx:
3614
            val = row[field_idx[field]]
3615
          else:
3616
            raise errors.ParameterError(field)
3617

    
3618
          out.append(val)
3619

    
3620
        result.append(out)
3621

    
3622
    return result
3623

    
3624

    
3625
class LUModifyNodeStorage(NoHooksLU):
3626
  """Logical unit for modifying a storage volume on a node.
3627

3628
  """
3629
  _OP_PARAMS = [
3630
    _PNodeName,
3631
    ("storage_type", ht.NoDefault, _CheckStorageType),
3632
    ("name", ht.NoDefault, ht.TNonEmptyString),
3633
    ("changes", ht.NoDefault, ht.TDict),
3634
    ]
3635
  REQ_BGL = False
3636

    
3637
  def CheckArguments(self):
3638
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3639

    
3640
    storage_type = self.op.storage_type
3641

    
3642
    try:
3643
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3644
    except KeyError:
3645
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3646
                                 " modified" % storage_type,
3647
                                 errors.ECODE_INVAL)
3648

    
3649
    diff = set(self.op.changes.keys()) - modifiable
3650
    if diff:
3651
      raise errors.OpPrereqError("The following fields can not be modified for"
3652
                                 " storage units of type '%s': %r" %
3653
                                 (storage_type, list(diff)),
3654
                                 errors.ECODE_INVAL)
3655

    
3656
  def ExpandNames(self):
3657
    self.needed_locks = {
3658
      locking.LEVEL_NODE: self.op.node_name,
3659
      }
3660

    
3661
  def Exec(self, feedback_fn):
3662
    """Computes the list of nodes and their attributes.
3663

3664
    """
3665
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3666
    result = self.rpc.call_storage_modify(self.op.node_name,
3667
                                          self.op.storage_type, st_args,
3668
                                          self.op.name, self.op.changes)
3669
    result.Raise("Failed to modify storage unit '%s' on %s" %
3670
                 (self.op.name, self.op.node_name))
3671

    
3672

    
3673
class LUAddNode(LogicalUnit):
3674
  """Logical unit for adding node to the cluster.
3675

3676
  """
3677
  HPATH = "node-add"
3678
  HTYPE = constants.HTYPE_NODE
3679
  _OP_PARAMS = [
3680
    _PNodeName,
3681
    ("primary_ip", None, ht.NoType),
3682
    ("secondary_ip", None, ht.TMaybeString),
3683
    ("readd", False, ht.TBool),
3684
    ("group", None, ht.TMaybeString)
3685
    ]
3686

    
3687
  def CheckArguments(self):
3688
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3689
    # validate/normalize the node name
3690
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3691
                                         family=self.primary_ip_family)
3692
    self.op.node_name = self.hostname.name
3693
    if self.op.readd and self.op.group:
3694
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3695
                                 " being readded", errors.ECODE_INVAL)
3696

    
3697
  def BuildHooksEnv(self):
3698
    """Build hooks env.
3699

3700
    This will run on all nodes before, and on all nodes + the new node after.
3701

3702
    """
3703
    env = {
3704
      "OP_TARGET": self.op.node_name,
3705
      "NODE_NAME": self.op.node_name,
3706
      "NODE_PIP": self.op.primary_ip,
3707
      "NODE_SIP": self.op.secondary_ip,
3708
      }
3709
    nodes_0 = self.cfg.GetNodeList()
3710
    nodes_1 = nodes_0 + [self.op.node_name, ]
3711
    return env, nodes_0, nodes_1
3712

    
3713
  def CheckPrereq(self):
3714
    """Check prerequisites.
3715

3716
    This checks:
3717
     - the new node is not already in the config
3718
     - it is resolvable
3719
     - its parameters (single/dual homed) matches the cluster
3720

3721
    Any errors are signaled by raising errors.OpPrereqError.
3722

3723
    """
3724
    cfg = self.cfg
3725
    hostname = self.hostname
3726
    node = hostname.name
3727
    primary_ip = self.op.primary_ip = hostname.ip
3728
    if self.op.secondary_ip is None:
3729
      if self.primary_ip_family == netutils.IP6Address.family:
3730
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3731
                                   " IPv4 address must be given as secondary",
3732
                                   errors.ECODE_INVAL)
3733
      self.op.secondary_ip = primary_ip
3734

    
3735
    secondary_ip = self.op.secondary_ip
3736
    if not netutils.IP4Address.IsValid(secondary_ip):
3737
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3738
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3739

    
3740
    node_list = cfg.GetNodeList()
3741
    if not self.op.readd and node in node_list:
3742
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3743
                                 node, errors.ECODE_EXISTS)
3744
    elif self.op.readd and node not in node_list:
3745
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3746
                                 errors.ECODE_NOENT)
3747

    
3748
    self.changed_primary_ip = False
3749

    
3750
    for existing_node_name in node_list:
3751
      existing_node = cfg.GetNodeInfo(existing_node_name)
3752

    
3753
      if self.op.readd and node == existing_node_name:
3754
        if existing_node.secondary_ip != secondary_ip:
3755
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3756
                                     " address configuration as before",
3757
                                     errors.ECODE_INVAL)
3758
        if existing_node.primary_ip != primary_ip:
3759
          self.changed_primary_ip = True
3760

    
3761
        continue
3762

    
3763
      if (existing_node.primary_ip == primary_ip or
3764
          existing_node.secondary_ip == primary_ip or
3765
          existing_node.primary_ip == secondary_ip or
3766
          existing_node.secondary_ip == secondary_ip):
3767
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3768
                                   " existing node %s" % existing_node.name,
3769
                                   errors.ECODE_NOTUNIQUE)
3770

    
3771
    # check that the type of the node (single versus dual homed) is the
3772
    # same as for the master
3773
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3774
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3775
    newbie_singlehomed = secondary_ip == primary_ip
3776
    if master_singlehomed != newbie_singlehomed:
3777
      if master_singlehomed:
3778
        raise errors.OpPrereqError("The master has no private ip but the"
3779
                                   " new node has one",
3780
                                   errors.ECODE_INVAL)
3781
      else:
3782
        raise errors.OpPrereqError("The master has a private ip but the"
3783
                                   " new node doesn't have one",
3784
                                   errors.ECODE_INVAL)
3785

    
3786
    # checks reachability
3787
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3788
      raise errors.OpPrereqError("Node not reachable by ping",
3789
                                 errors.ECODE_ENVIRON)
3790

    
3791
    if not newbie_singlehomed:
3792
      # check reachability from my secondary ip to newbie's secondary ip
3793
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3794
                           source=myself.secondary_ip):
3795
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3796
                                   " based ping to noded port",
3797
                                   errors.ECODE_ENVIRON)
3798

    
3799
    if self.op.readd:
3800
      exceptions = [node]
3801
    else:
3802
      exceptions = []
3803

    
3804
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3805

    
3806
    if self.op.readd:
3807
      self.new_node = self.cfg.GetNodeInfo(node)
3808
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3809
    else:
3810
      node_group = cfg.LookupNodeGroup(self.op.group)
3811
      self.new_node = objects.Node(name=node,
3812
                                   primary_ip=primary_ip,
3813
                                   secondary_ip=secondary_ip,
3814
                                   master_candidate=self.master_candidate,
3815
                                   master_capable=True,
3816
                                   vm_capable=True,
3817
                                   offline=False, drained=False,
3818
                                   group=node_group)
3819

    
3820
  def Exec(self, feedback_fn):
3821
    """Adds the new node to the cluster.
3822

3823
    """
3824
    new_node = self.new_node
3825
    node = new_node.name
3826

    
3827
    # for re-adds, reset the offline/drained/master-candidate flags;
3828
    # we need to reset here, otherwise offline would prevent RPC calls
3829
    # later in the procedure; this also means that if the re-add
3830
    # fails, we are left with a non-offlined, broken node
3831
    if self.op.readd:
3832
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3833
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3834
      # if we demote the node, we do cleanup later in the procedure
3835
      new_node.master_candidate = self.master_candidate
3836
      if self.changed_primary_ip:
3837
        new_node.primary_ip = self.op.primary_ip
3838

    
3839
    # notify the user about any possible mc promotion
3840
    if new_node.master_candidate:
3841
      self.LogInfo("Node will be a master candidate")
3842

    
3843
    # check connectivity
3844
    result = self.rpc.call_version([node])[node]
3845
    result.Raise("Can't get version information from node %s" % node)
3846
    if constants.PROTOCOL_VERSION == result.payload:
3847
      logging.info("Communication to node %s fine, sw version %s match",
3848
                   node, result.payload)
3849
    else:
3850
      raise errors.OpExecError("Version mismatch master version %s,"
3851
                               " node version %s" %
3852
                               (constants.PROTOCOL_VERSION, result.payload))
3853

    
3854
    # Add node to our /etc/hosts, and add key to known_hosts
3855
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3856
      master_node = self.cfg.GetMasterNode()
3857
      result = self.rpc.call_etc_hosts_modify(master_node,
3858
                                              constants.ETC_HOSTS_ADD,
3859
                                              self.hostname.name,
3860
                                              self.hostname.ip)
3861
      result.Raise("Can't update hosts file with new host data")
3862

    
3863
    if new_node.secondary_ip != new_node.primary_ip:
3864
      result = self.rpc.call_node_has_ip_address(new_node.name,
3865
                                                 new_node.secondary_ip)
3866
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3867
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3868
      if not result.payload:
3869
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3870
                                 " you gave (%s). Please fix and re-run this"
3871
                                 " command." % new_node.secondary_ip)
3872

    
3873
    node_verify_list = [self.cfg.GetMasterNode()]
3874
    node_verify_param = {
3875
      constants.NV_NODELIST: [node],
3876
      # TODO: do a node-net-test as well?
3877
    }
3878

    
3879
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3880
                                       self.cfg.GetClusterName())
3881
    for verifier in node_verify_list:
3882
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3883
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3884
      if nl_payload:
3885
        for failed in nl_payload:
3886
          feedback_fn("ssh/hostname verification failed"
3887
                      " (checking from %s): %s" %
3888
                      (verifier, nl_payload[failed]))
3889
        raise errors.OpExecError("ssh/hostname verification failed.")
3890

    
3891
    if self.op.readd:
3892
      _RedistributeAncillaryFiles(self)
3893
      self.context.ReaddNode(new_node)
3894
      # make sure we redistribute the config
3895
      self.cfg.Update(new_node, feedback_fn)
3896
      # and make sure the new node will not have old files around
3897
      if not new_node.master_candidate:
3898
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3899
        msg = result.fail_msg
3900
        if msg:
3901
          self.LogWarning("Node failed to demote itself from master"
3902
                          " candidate status: %s" % msg)
3903
    else:
3904
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3905
      self.context.AddNode(new_node, self.proc.GetECId())
3906

    
3907

    
3908
class LUSetNodeParams(LogicalUnit):
3909
  """Modifies the parameters of a node.
3910

3911
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
3912
      to the node role (as _ROLE_*)
3913
  @cvar _R2F: a dictionary from node role to tuples of flags
3914
  @cvar _FLAGS: a list of attribute names corresponding to the flags
3915

3916
  """
3917
  HPATH = "node-modify"
3918
  HTYPE = constants.HTYPE_NODE
3919
  _OP_PARAMS = [
3920
    _PNodeName,
3921
    ("master_candidate", None, ht.TMaybeBool),
3922
    ("offline", None, ht.TMaybeBool),
3923
    ("drained", None, ht.TMaybeBool),
3924
    ("auto_promote", False, ht.TBool),
3925
    ("master_capable", None, ht.TMaybeBool),
3926
    ("vm_capable", None, ht.TMaybeBool),
3927
    _PForce,
3928
    ]
3929
  REQ_BGL = False
3930
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
3931
  _F2R = {
3932
    (True, False, False): _ROLE_CANDIDATE,
3933
    (False, True, False): _ROLE_DRAINED,
3934
    (False, False, True): _ROLE_OFFLINE,
3935
    (False, False, False): _ROLE_REGULAR,
3936
    }
3937
  _R2F = dict((v, k) for k, v in _F2R.items())
3938
  _FLAGS = ["master_candidate", "drained", "offline"]
3939

    
3940
  def CheckArguments(self):
3941
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3942
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
3943
                self.op.master_capable, self.op.vm_capable]
3944
    if all_mods.count(None) == len(all_mods):
3945
      raise errors.OpPrereqError("Please pass at least one modification",
3946
                                 errors.ECODE_INVAL)
3947
    if all_mods.count(True) > 1:
3948
      raise errors.OpPrereqError("Can't set the node into more than one"
3949
                                 " state at the same time",
3950
                                 errors.ECODE_INVAL)
3951

    
3952
    # Boolean value that tells us whether we might be demoting from MC
3953
    self.might_demote = (self.op.master_candidate == False or
3954
                         self.op.offline == True or
3955
                         self.op.drained == True or
3956
                         self.op.master_capable == False)
3957

    
3958
    self.lock_all = self.op.auto_promote and self.might_demote
3959

    
3960
  def ExpandNames(self):
3961
    if self.lock_all:
3962
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3963
    else:
3964
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3965

    
3966
  def BuildHooksEnv(self):
3967
    """Build hooks env.
3968

3969
    This runs on the master node.
3970

3971
    """
3972
    env = {
3973
      "OP_TARGET": self.op.node_name,
3974
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3975
      "OFFLINE": str(self.op.offline),
3976
      "DRAINED": str(self.op.drained),
3977
      "MASTER_CAPABLE": str(self.op.master_capable),
3978
      "VM_CAPABLE": str(self.op.vm_capable),
3979
      }
3980
    nl = [self.cfg.GetMasterNode(),
3981
          self.op.node_name]
3982
    return env, nl, nl
3983

    
3984
  def CheckPrereq(self):
3985
    """Check prerequisites.
3986

3987
    This only checks the instance list against the existing names.
3988

3989
    """
3990
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3991

    
3992
    if (self.op.master_candidate is not None or
3993
        self.op.drained is not None or
3994
        self.op.offline is not None):
3995
      # we can't change the master's node flags
3996
      if self.op.node_name == self.cfg.GetMasterNode():
3997
        raise errors.OpPrereqError("The master role can be changed"
3998
                                   " only via master-failover",
3999
                                   errors.ECODE_INVAL)
4000

    
4001
    if self.op.master_candidate and not node.master_capable:
4002
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4003
                                 " it a master candidate" % node.name,
4004
                                 errors.ECODE_STATE)
4005

    
4006
    if self.op.vm_capable == False:
4007
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4008
      if ipri or isec:
4009
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4010
                                   " the vm_capable flag" % node.name,
4011
                                   errors.ECODE_STATE)
4012

    
4013
    if node.master_candidate and self.might_demote and not self.lock_all:
4014
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4015
      # check if after removing the current node, we're missing master
4016
      # candidates
4017
      (mc_remaining, mc_should, _) = \
4018
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4019
      if mc_remaining < mc_should:
4020
        raise errors.OpPrereqError("Not enough master candidates, please"
4021
                                   " pass auto_promote to allow promotion",
4022
                                   errors.ECODE_STATE)
4023

    
4024
    self.old_flags = old_flags = (node.master_candidate,
4025
                                  node.drained, node.offline)
4026
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4027
    self.old_role = self._F2R[old_flags]
4028

    
4029
    # Check for ineffective changes
4030
    for attr in self._FLAGS:
4031
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4032
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4033
        setattr(self.op, attr, None)
4034

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

    
4038
    # If we're being deofflined/drained, we'll MC ourself if needed
4039
    if (self.op.drained == False or self.op.offline == False or
4040
        (self.op.master_capable and not node.master_capable)):
4041
      if _DecideSelfPromotion(self):
4042
        self.op.master_candidate = True
4043
        self.LogInfo("Auto-promoting node to master candidate")
4044

    
4045
    # If we're no longer master capable, we'll demote ourselves from MC
4046
    if self.op.master_capable == False and node.master_candidate:
4047
      self.LogInfo("Demoting from master candidate")
4048
      self.op.master_candidate = False
4049

    
4050
  def Exec(self, feedback_fn):
4051
    """Modifies a node.
4052

4053
    """
4054
    node = self.node
4055
    old_role = self.old_role
4056

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

    
4059
    # compute new flags
4060
    if self.op.master_candidate:
4061
      new_role = self._ROLE_CANDIDATE
4062
    elif self.op.drained:
4063
      new_role = self._ROLE_DRAINED
4064
    elif self.op.offline:
4065
      new_role = self._ROLE_OFFLINE
4066
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4067
      # False is still in new flags, which means we're un-setting (the
4068
      # only) True flag
4069
      new_role = self._ROLE_REGULAR
4070
    else: # no new flags, nothing, keep old role
4071
      new_role = old_role
4072

    
4073
    result = []
4074

    
4075
    for attr in ["master_capable", "vm_capable"]:
4076
      val = getattr(self.op, attr)
4077
      if val is not None:
4078
        setattr(node, attr, val)
4079
        result.append((attr, str(val)))
4080

    
4081
    if new_role != old_role:
4082
      # Tell the node to demote itself, if no longer MC and not offline
4083
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4084
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4085
        if msg:
4086
          self.LogWarning("Node failed to demote itself: %s", msg)
4087

    
4088
      new_flags = self._R2F[new_role]
4089
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4090
        if of != nf:
4091
          result.append((desc, str(nf)))
4092
      (node.master_candidate, node.drained, node.offline) = new_flags
4093

    
4094
      # we locked all nodes, we adjust the CP before updating this node
4095
      if self.lock_all:
4096
        _AdjustCandidatePool(self, [node.name])
4097

    
4098
    # this will trigger configuration file update, if needed
4099
    self.cfg.Update(node, feedback_fn)
4100

    
4101
    # this will trigger job queue propagation or cleanup if the mc
4102
    # flag changed
4103
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4104
      self.context.ReaddNode(node)
4105

    
4106
    return result
4107

    
4108

    
4109
class LUPowercycleNode(NoHooksLU):
4110
  """Powercycles a node.
4111

4112
  """
4113
  _OP_PARAMS = [
4114
    _PNodeName,
4115
    _PForce,
4116
    ]
4117
  REQ_BGL = False
4118

    
4119
  def CheckArguments(self):
4120
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4121
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4122
      raise errors.OpPrereqError("The node is the master and the force"
4123
                                 " parameter was not set",
4124
                                 errors.ECODE_INVAL)
4125

    
4126
  def ExpandNames(self):
4127
    """Locking for PowercycleNode.
4128

4129
    This is a last-resort option and shouldn't block on other
4130
    jobs. Therefore, we grab no locks.
4131

4132
    """
4133
    self.needed_locks = {}
4134

    
4135
  def Exec(self, feedback_fn):
4136
    """Reboots a node.
4137

4138
    """
4139
    result = self.rpc.call_node_powercycle(self.op.node_name,
4140
                                           self.cfg.GetHypervisorType())
4141
    result.Raise("Failed to schedule the reboot")
4142
    return result.payload
4143

    
4144

    
4145
class LUQueryClusterInfo(NoHooksLU):
4146
  """Query cluster configuration.
4147

4148
  """
4149
  REQ_BGL = False
4150

    
4151
  def ExpandNames(self):
4152
    self.needed_locks = {}
4153

    
4154
  def Exec(self, feedback_fn):
4155
    """Return cluster config.
4156

4157
    """
4158
    cluster = self.cfg.GetClusterInfo()
4159
    os_hvp = {}
4160

    
4161
    # Filter just for enabled hypervisors
4162
    for os_name, hv_dict in cluster.os_hvp.items():
4163
      os_hvp[os_name] = {}
4164
      for hv_name, hv_params in hv_dict.items():
4165
        if hv_name in cluster.enabled_hypervisors:
4166
          os_hvp[os_name][hv_name] = hv_params
4167

    
4168
    # Convert ip_family to ip_version
4169
    primary_ip_version = constants.IP4_VERSION
4170
    if cluster.primary_ip_family == netutils.IP6Address.family:
4171
      primary_ip_version = constants.IP6_VERSION
4172

    
4173
    result = {
4174
      "software_version": constants.RELEASE_VERSION,
4175
      "protocol_version": constants.PROTOCOL_VERSION,
4176
      "config_version": constants.CONFIG_VERSION,
4177
      "os_api_version": max(constants.OS_API_VERSIONS),
4178
      "export_version": constants.EXPORT_VERSION,
4179
      "architecture": (platform.architecture()[0], platform.machine()),
4180
      "name": cluster.cluster_name,
4181
      "master": cluster.master_node,
4182
      "default_hypervisor": cluster.enabled_hypervisors[0],
4183
      "enabled_hypervisors": cluster.enabled_hypervisors,
4184
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4185
                        for hypervisor_name in cluster.enabled_hypervisors]),
4186
      "os_hvp": os_hvp,
4187
      "beparams": cluster.beparams,
4188
      "osparams": cluster.osparams,
4189
      "nicparams": cluster.nicparams,
4190
      "candidate_pool_size": cluster.candidate_pool_size,
4191
      "master_netdev": cluster.master_netdev,
4192
      "volume_group_name": cluster.volume_group_name,
4193
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4194
      "file_storage_dir": cluster.file_storage_dir,
4195
      "maintain_node_health": cluster.maintain_node_health,
4196
      "ctime": cluster.ctime,
4197
      "mtime": cluster.mtime,
4198
      "uuid": cluster.uuid,
4199
      "tags": list(cluster.GetTags()),
4200
      "uid_pool": cluster.uid_pool,
4201
      "default_iallocator": cluster.default_iallocator,
4202
      "reserved_lvs": cluster.reserved_lvs,
4203
      "primary_ip_version": primary_ip_version,
4204
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4205
      }
4206

    
4207
    return result
4208

    
4209

    
4210
class LUQueryConfigValues(NoHooksLU):
4211
  """Return configuration values.
4212

4213
  """
4214
  _OP_PARAMS = [_POutputFields]
4215
  REQ_BGL = False
4216
  _FIELDS_DYNAMIC = utils.FieldSet()
4217
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4218
                                  "watcher_pause", "volume_group_name")
4219

    
4220
  def CheckArguments(self):
4221
    _CheckOutputFields(static=self._FIELDS_STATIC,
4222
                       dynamic=self._FIELDS_DYNAMIC,
4223
                       selected=self.op.output_fields)
4224

    
4225
  def ExpandNames(self):
4226
    self.needed_locks = {}
4227

    
4228
  def Exec(self, feedback_fn):
4229
    """Dump a representation of the cluster config to the standard output.
4230

4231
    """
4232
    values = []
4233
    for field in self.op.output_fields:
4234
      if field == "cluster_name":
4235
        entry = self.cfg.GetClusterName()
4236
      elif field == "master_node":
4237
        entry = self.cfg.GetMasterNode()
4238
      elif field == "drain_flag":
4239
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4240
      elif field == "watcher_pause":
4241
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4242
      elif field == "volume_group_name":
4243
        entry = self.cfg.GetVGName()
4244
      else:
4245
        raise errors.ParameterError(field)
4246
      values.append(entry)
4247
    return values
4248

    
4249

    
4250
class LUActivateInstanceDisks(NoHooksLU):
4251
  """Bring up an instance's disks.
4252

4253
  """
4254
  _OP_PARAMS = [
4255
    _PInstanceName,
4256
    ("ignore_size", False, ht.TBool),
4257
    ]
4258
  REQ_BGL = False
4259

    
4260
  def ExpandNames(self):
4261
    self._ExpandAndLockInstance()
4262
    self.needed_locks[locking.LEVEL_NODE] = []
4263
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4264

    
4265
  def DeclareLocks(self, level):
4266
    if level == locking.LEVEL_NODE:
4267
      self._LockInstancesNodes()
4268

    
4269
  def CheckPrereq(self):
4270
    """Check prerequisites.
4271

4272
    This checks that the instance is in the cluster.
4273

4274
    """
4275
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4276
    assert self.instance is not None, \
4277
      "Cannot retrieve locked instance %s" % self.op.instance_name
4278
    _CheckNodeOnline(self, self.instance.primary_node)
4279

    
4280
  def Exec(self, feedback_fn):
4281
    """Activate the disks.
4282

4283
    """
4284
    disks_ok, disks_info = \
4285
              _AssembleInstanceDisks(self, self.instance,
4286
                                     ignore_size=self.op.ignore_size)
4287
    if not disks_ok:
4288
      raise errors.OpExecError("Cannot activate block devices")
4289

    
4290
    return disks_info
4291

    
4292

    
4293
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4294
                           ignore_size=False):
4295
  """Prepare the block devices for an instance.
4296

4297
  This sets up the block devices on all nodes.
4298

4299
  @type lu: L{LogicalUnit}
4300
  @param lu: the logical unit on whose behalf we execute
4301
  @type instance: L{objects.Instance}
4302
  @param instance: the instance for whose disks we assemble
4303
  @type disks: list of L{objects.Disk} or None
4304
  @param disks: which disks to assemble (or all, if None)
4305
  @type ignore_secondaries: boolean
4306
  @param ignore_secondaries: if true, errors on secondary nodes
4307
      won't result in an error return from the function
4308
  @type ignore_size: boolean
4309
  @param ignore_size: if true, the current known size of the disk
4310
      will not be used during the disk activation, useful for cases
4311
      when the size is wrong
4312
  @return: False if the operation failed, otherwise a list of
4313
      (host, instance_visible_name, node_visible_name)
4314
      with the mapping from node devices to instance devices
4315

4316
  """
4317
  device_info = []
4318
  disks_ok = True
4319
  iname = instance.name
4320
  disks = _ExpandCheckDisks(instance, disks)
4321

    
4322
  # With the two passes mechanism we try to reduce the window of
4323
  # opportunity for the race condition of switching DRBD to primary
4324
  # before handshaking occured, but we do not eliminate it
4325

    
4326
  # The proper fix would be to wait (with some limits) until the
4327
  # connection has been made and drbd transitions from WFConnection
4328
  # into any other network-connected state (Connected, SyncTarget,
4329
  # SyncSource, etc.)
4330

    
4331
  # 1st pass, assemble on all nodes in secondary mode
4332
  for inst_disk in disks:
4333
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4334
      if ignore_size:
4335
        node_disk = node_disk.Copy()
4336
        node_disk.UnsetSize()
4337
      lu.cfg.SetDiskID(node_disk, node)
4338
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4339
      msg = result.fail_msg
4340
      if msg:
4341
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4342
                           " (is_primary=False, pass=1): %s",
4343
                           inst_disk.iv_name, node, msg)
4344
        if not ignore_secondaries:
4345
          disks_ok = False
4346

    
4347
  # FIXME: race condition on drbd migration to primary
4348

    
4349
  # 2nd pass, do only the primary node
4350
  for inst_disk in disks:
4351
    dev_path = None
4352

    
4353
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4354
      if node != instance.primary_node:
4355
        continue
4356
      if ignore_size:
4357
        node_disk = node_disk.Copy()
4358
        node_disk.UnsetSize()
4359
      lu.cfg.SetDiskID(node_disk, node)
4360
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4361
      msg = result.fail_msg
4362
      if msg:
4363
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4364
                           " (is_primary=True, pass=2): %s",
4365
                           inst_disk.iv_name, node, msg)
4366
        disks_ok = False
4367
      else:
4368
        dev_path = result.payload
4369

    
4370
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4371

    
4372
  # leave the disks configured for the primary node
4373
  # this is a workaround that would be fixed better by
4374
  # improving the logical/physical id handling
4375
  for disk in disks:
4376
    lu.cfg.SetDiskID(disk, instance.primary_node)
4377

    
4378
  return disks_ok, device_info
4379

    
4380

    
4381
def _StartInstanceDisks(lu, instance, force):
4382
  """Start the disks of an instance.
4383

4384
  """
4385
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4386
                                           ignore_secondaries=force)
4387
  if not disks_ok:
4388
    _ShutdownInstanceDisks(lu, instance)
4389
    if force is not None and not force:
4390
      lu.proc.LogWarning("", hint="If the message above refers to a"
4391
                         " secondary node,"
4392
                         " you can retry the operation using '--force'.")
4393
    raise errors.OpExecError("Disk consistency error")
4394

    
4395

    
4396
class LUDeactivateInstanceDisks(NoHooksLU):
4397
  """Shutdown an instance's disks.
4398

4399
  """
4400
  _OP_PARAMS = [
4401
    _PInstanceName,
4402
    ]
4403
  REQ_BGL = False
4404

    
4405
  def ExpandNames(self):
4406
    self._ExpandAndLockInstance()
4407
    self.needed_locks[locking.LEVEL_NODE] = []
4408
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4409

    
4410
  def DeclareLocks(self, level):
4411
    if level == locking.LEVEL_NODE:
4412
      self._LockInstancesNodes()
4413

    
4414
  def CheckPrereq(self):
4415
    """Check prerequisites.
4416

4417
    This checks that the instance is in the cluster.
4418

4419
    """
4420
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4421
    assert self.instance is not None, \
4422
      "Cannot retrieve locked instance %s" % self.op.instance_name
4423

    
4424
  def Exec(self, feedback_fn):
4425
    """Deactivate the disks
4426

4427
    """
4428
    instance = self.instance
4429
    _SafeShutdownInstanceDisks(self, instance)
4430

    
4431

    
4432
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4433
  """Shutdown block devices of an instance.
4434

4435
  This function checks if an instance is running, before calling
4436
  _ShutdownInstanceDisks.
4437

4438
  """
4439
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4440
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4441

    
4442

    
4443
def _ExpandCheckDisks(instance, disks):
4444
  """Return the instance disks selected by the disks list
4445

4446
  @type disks: list of L{objects.Disk} or None
4447
  @param disks: selected disks
4448
  @rtype: list of L{objects.Disk}
4449
  @return: selected instance disks to act on
4450

4451
  """
4452
  if disks is None:
4453
    return instance.disks
4454
  else:
4455
    if not set(disks).issubset(instance.disks):
4456
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4457
                                   " target instance")
4458
    return disks
4459

    
4460

    
4461
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4462
  """Shutdown block devices of an instance.
4463

4464
  This does the shutdown on all nodes of the instance.
4465

4466
  If the ignore_primary is false, errors on the primary node are
4467
  ignored.
4468

4469
  """
4470
  all_result = True
4471
  disks = _ExpandCheckDisks(instance, disks)
4472

    
4473
  for disk in disks:
4474
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4475
      lu.cfg.SetDiskID(top_disk, node)
4476
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4477
      msg = result.fail_msg
4478
      if msg:
4479
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4480
                      disk.iv_name, node, msg)
4481
        if not ignore_primary or node != instance.primary_node:
4482
          all_result = False
4483
  return all_result
4484

    
4485

    
4486
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4487
  """Checks if a node has enough free memory.
4488

4489
  This function check if a given node has the needed amount of free
4490
  memory. In case the node has less memory or we cannot get the
4491
  information from the node, this function raise an OpPrereqError
4492
  exception.
4493

4494
  @type lu: C{LogicalUnit}
4495
  @param lu: a logical unit from which we get configuration data
4496
  @type node: C{str}
4497
  @param node: the node to check
4498
  @type reason: C{str}
4499
  @param reason: string to use in the error message
4500
  @type requested: C{int}
4501
  @param requested: the amount of memory in MiB to check for
4502
  @type hypervisor_name: C{str}
4503
  @param hypervisor_name: the hypervisor to ask for memory stats
4504
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4505
      we cannot check the node
4506

4507
  """
4508
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4509
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4510
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4511
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4512
  if not isinstance(free_mem, int):
4513
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4514
                               " was '%s'" % (node, free_mem),
4515
                               errors.ECODE_ENVIRON)
4516
  if requested > free_mem:
4517
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4518
                               " needed %s MiB, available %s MiB" %
4519
                               (node, reason, requested, free_mem),
4520
                               errors.ECODE_NORES)
4521

    
4522

    
4523
def _CheckNodesFreeDisk(lu, nodenames, requested):
4524
  """Checks if nodes have enough free disk space in the default VG.
4525

4526
  This function check if all given nodes have the needed amount of
4527
  free disk. In case any node has less disk or we cannot get the
4528
  information from the node, this function raise an OpPrereqError
4529
  exception.
4530

4531
  @type lu: C{LogicalUnit}
4532
  @param lu: a logical unit from which we get configuration data
4533
  @type nodenames: C{list}
4534
  @param nodenames: the list of node names to check
4535
  @type requested: C{int}
4536
  @param requested: the amount of disk in MiB to check for
4537
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4538
      we cannot check the node
4539

4540
  """
4541
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4542
                                   lu.cfg.GetHypervisorType())
4543
  for node in nodenames:
4544
    info = nodeinfo[node]
4545
    info.Raise("Cannot get current information from node %s" % node,
4546
               prereq=True, ecode=errors.ECODE_ENVIRON)
4547
    vg_free = info.payload.get("vg_free", None)
4548
    if not isinstance(vg_free, int):
4549
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4550
                                 " result was '%s'" % (node, vg_free),
4551
                                 errors.ECODE_ENVIRON)
4552
    if requested > vg_free:
4553
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4554
                                 " required %d MiB, available %d MiB" %
4555
                                 (node, requested, vg_free),
4556
                                 errors.ECODE_NORES)
4557

    
4558

    
4559
class LUStartupInstance(LogicalUnit):
4560
  """Starts an instance.
4561

4562
  """
4563
  HPATH = "instance-start"
4564
  HTYPE = constants.HTYPE_INSTANCE
4565
  _OP_PARAMS = [
4566
    _PInstanceName,
4567
    _PForce,
4568
    _PIgnoreOfflineNodes,
4569
    ("hvparams", ht.EmptyDict, ht.TDict),
4570
    ("beparams", ht.EmptyDict, ht.TDict),
4571
    ]
4572
  REQ_BGL = False
4573

    
4574
  def CheckArguments(self):
4575
    # extra beparams
4576
    if self.op.beparams:
4577
      # fill the beparams dict
4578
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4579

    
4580
  def ExpandNames(self):
4581
    self._ExpandAndLockInstance()
4582

    
4583
  def BuildHooksEnv(self):
4584
    """Build hooks env.
4585

4586
    This runs on master, primary and secondary nodes of the instance.
4587

4588
    """
4589
    env = {
4590
      "FORCE": self.op.force,
4591
      }
4592
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4593
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4594
    return env, nl, nl
4595

    
4596
  def CheckPrereq(self):
4597
    """Check prerequisites.
4598

4599
    This checks that the instance is in the cluster.
4600

4601
    """
4602
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4603
    assert self.instance is not None, \
4604
      "Cannot retrieve locked instance %s" % self.op.instance_name
4605

    
4606
    # extra hvparams
4607
    if self.op.hvparams:
4608
      # check hypervisor parameter syntax (locally)
4609
      cluster = self.cfg.GetClusterInfo()
4610
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4611
      filled_hvp = cluster.FillHV(instance)
4612
      filled_hvp.update(self.op.hvparams)
4613
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4614
      hv_type.CheckParameterSyntax(filled_hvp)
4615
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4616

    
4617
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4618

    
4619
    if self.primary_offline and self.op.ignore_offline_nodes:
4620
      self.proc.LogWarning("Ignoring offline primary node")
4621

    
4622
      if self.op.hvparams or self.op.beparams:
4623
        self.proc.LogWarning("Overridden parameters are ignored")
4624
    else:
4625
      _CheckNodeOnline(self, instance.primary_node)
4626

    
4627
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4628

    
4629
      # check bridges existence
4630
      _CheckInstanceBridgesExist(self, instance)
4631

    
4632
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4633
                                                instance.name,
4634
                                                instance.hypervisor)
4635
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4636
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4637
      if not remote_info.payload: # not running already
4638
        _CheckNodeFreeMemory(self, instance.primary_node,
4639
                             "starting instance %s" % instance.name,
4640
                             bep[constants.BE_MEMORY], instance.hypervisor)
4641

    
4642
  def Exec(self, feedback_fn):
4643
    """Start the instance.
4644

4645
    """
4646
    instance = self.instance
4647
    force = self.op.force
4648

    
4649
    self.cfg.MarkInstanceUp(instance.name)
4650

    
4651
    if self.primary_offline:
4652
      assert self.op.ignore_offline_nodes
4653
      self.proc.LogInfo("Primary node offline, marked instance as started")
4654
    else:
4655
      node_current = instance.primary_node
4656

    
4657
      _StartInstanceDisks(self, instance, force)
4658

    
4659
      result = self.rpc.call_instance_start(node_current, instance,
4660
                                            self.op.hvparams, self.op.beparams)
4661
      msg = result.fail_msg
4662
      if msg:
4663
        _ShutdownInstanceDisks(self, instance)
4664
        raise errors.OpExecError("Could not start instance: %s" % msg)
4665

    
4666

    
4667
class LURebootInstance(LogicalUnit):
4668
  """Reboot an instance.
4669

4670
  """
4671
  HPATH = "instance-reboot"
4672
  HTYPE = constants.HTYPE_INSTANCE
4673
  _OP_PARAMS = [
4674
    _PInstanceName,
4675
    ("ignore_secondaries", False, ht.TBool),
4676
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4677
    _PShutdownTimeout,
4678
    ]
4679
  REQ_BGL = False
4680

    
4681
  def ExpandNames(self):
4682
    self._ExpandAndLockInstance()
4683

    
4684
  def BuildHooksEnv(self):
4685
    """Build hooks env.
4686

4687
    This runs on master, primary and secondary nodes of the instance.
4688

4689
    """
4690
    env = {
4691
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4692
      "REBOOT_TYPE": self.op.reboot_type,
4693
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4694
      }
4695
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4696
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4697
    return env, nl, nl
4698

    
4699
  def CheckPrereq(self):
4700
    """Check prerequisites.
4701

4702
    This checks that the instance is in the cluster.
4703

4704
    """
4705
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4706
    assert self.instance is not None, \
4707
      "Cannot retrieve locked instance %s" % self.op.instance_name
4708

    
4709
    _CheckNodeOnline(self, instance.primary_node)
4710

    
4711
    # check bridges existence
4712
    _CheckInstanceBridgesExist(self, instance)
4713

    
4714
  def Exec(self, feedback_fn):
4715
    """Reboot the instance.
4716

4717
    """
4718
    instance = self.instance
4719
    ignore_secondaries = self.op.ignore_secondaries
4720
    reboot_type = self.op.reboot_type
4721

    
4722
    node_current = instance.primary_node
4723

    
4724
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4725
                       constants.INSTANCE_REBOOT_HARD]:
4726
      for disk in instance.disks:
4727
        self.cfg.SetDiskID(disk, node_current)
4728
      result = self.rpc.call_instance_reboot(node_current, instance,
4729
                                             reboot_type,
4730
                                             self.op.shutdown_timeout)
4731
      result.Raise("Could not reboot instance")
4732
    else:
4733
      result = self.rpc.call_instance_shutdown(node_current, instance,
4734
                                               self.op.shutdown_timeout)
4735
      result.Raise("Could not shutdown instance for full reboot")
4736
      _ShutdownInstanceDisks(self, instance)
4737
      _StartInstanceDisks(self, instance, ignore_secondaries)
4738
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4739
      msg = result.fail_msg
4740
      if msg:
4741
        _ShutdownInstanceDisks(self, instance)
4742
        raise errors.OpExecError("Could not start instance for"
4743
                                 " full reboot: %s" % msg)
4744

    
4745
    self.cfg.MarkInstanceUp(instance.name)
4746

    
4747

    
4748
class LUShutdownInstance(LogicalUnit):
4749
  """Shutdown an instance.
4750

4751
  """
4752
  HPATH = "instance-stop"
4753
  HTYPE = constants.HTYPE_INSTANCE
4754
  _OP_PARAMS = [
4755
    _PInstanceName,
4756
    _PIgnoreOfflineNodes,
4757
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
4758
    ]
4759
  REQ_BGL = False
4760

    
4761
  def ExpandNames(self):
4762
    self._ExpandAndLockInstance()
4763

    
4764
  def BuildHooksEnv(self):
4765
    """Build hooks env.
4766

4767
    This runs on master, primary and secondary nodes of the instance.
4768

4769
    """
4770
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4771
    env["TIMEOUT"] = self.op.timeout
4772
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4773
    return env, nl, nl
4774

    
4775
  def CheckPrereq(self):
4776
    """Check prerequisites.
4777

4778
    This checks that the instance is in the cluster.
4779

4780
    """
4781
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4782
    assert self.instance is not None, \
4783
      "Cannot retrieve locked instance %s" % self.op.instance_name
4784

    
4785
    self.primary_offline = \
4786
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
4787

    
4788
    if self.primary_offline and self.op.ignore_offline_nodes:
4789
      self.proc.LogWarning("Ignoring offline primary node")
4790
    else:
4791
      _CheckNodeOnline(self, self.instance.primary_node)
4792

    
4793
  def Exec(self, feedback_fn):
4794
    """Shutdown the instance.
4795

4796
    """
4797
    instance = self.instance
4798
    node_current = instance.primary_node
4799
    timeout = self.op.timeout
4800

    
4801
    self.cfg.MarkInstanceDown(instance.name)
4802

    
4803
    if self.primary_offline:
4804
      assert self.op.ignore_offline_nodes
4805
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
4806
    else:
4807
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4808
      msg = result.fail_msg
4809
      if msg:
4810
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4811

    
4812
      _ShutdownInstanceDisks(self, instance)
4813

    
4814

    
4815
class LUReinstallInstance(LogicalUnit):
4816
  """Reinstall an instance.
4817

4818
  """
4819
  HPATH = "instance-reinstall"
4820
  HTYPE = constants.HTYPE_INSTANCE
4821
  _OP_PARAMS = [
4822
    _PInstanceName,
4823
    ("os_type", None, ht.TMaybeString),
4824
    ("force_variant", False, ht.TBool),
4825
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
4826
    ]
4827
  REQ_BGL = False
4828

    
4829
  def ExpandNames(self):
4830
    self._ExpandAndLockInstance()
4831

    
4832
  def BuildHooksEnv(self):
4833
    """Build hooks env.
4834

4835
    This runs on master, primary and secondary nodes of the instance.
4836

4837
    """
4838
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4839
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4840
    return env, nl, nl
4841

    
4842
  def CheckPrereq(self):
4843
    """Check prerequisites.
4844

4845
    This checks that the instance is in the cluster and is not running.
4846

4847
    """
4848
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4849
    assert instance is not None, \
4850
      "Cannot retrieve locked instance %s" % self.op.instance_name
4851
    _CheckNodeOnline(self, instance.primary_node)
4852

    
4853
    if instance.disk_template == constants.DT_DISKLESS:
4854
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4855
                                 self.op.instance_name,
4856
                                 errors.ECODE_INVAL)
4857
    _CheckInstanceDown(self, instance, "cannot reinstall")
4858

    
4859
    if self.op.os_type is not None:
4860
      # OS verification
4861
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4862
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4863
      instance_os = self.op.os_type
4864
    else:
4865
      instance_os = instance.os
4866

    
4867
    nodelist = list(instance.all_nodes)
4868

    
4869
    if self.op.osparams:
4870
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
4871
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
4872
      self.os_inst = i_osdict # the new dict (without defaults)
4873
    else:
4874
      self.os_inst = None
4875

    
4876
    self.instance = instance
4877

    
4878
  def Exec(self, feedback_fn):
4879
    """Reinstall the instance.
4880

4881
    """
4882
    inst = self.instance
4883

    
4884
    if self.op.os_type is not None:
4885
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4886
      inst.os = self.op.os_type
4887
      # Write to configuration
4888
      self.cfg.Update(inst, feedback_fn)
4889

    
4890
    _StartInstanceDisks(self, inst, None)
4891
    try:
4892
      feedback_fn("Running the instance OS create scripts...")
4893
      # FIXME: pass debug option from opcode to backend
4894
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4895
                                             self.op.debug_level,
4896
                                             osparams=self.os_inst)
4897
      result.Raise("Could not install OS for instance %s on node %s" %
4898
                   (inst.name, inst.primary_node))
4899
    finally:
4900
      _ShutdownInstanceDisks(self, inst)
4901

    
4902

    
4903
class LURecreateInstanceDisks(LogicalUnit):
4904
  """Recreate an instance's missing disks.
4905

4906
  """
4907
  HPATH = "instance-recreate-disks"
4908
  HTYPE = constants.HTYPE_INSTANCE
4909
  _OP_PARAMS = [
4910
    _PInstanceName,
4911
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
4912
    ]
4913
  REQ_BGL = False
4914

    
4915
  def ExpandNames(self):
4916
    self._ExpandAndLockInstance()
4917

    
4918
  def BuildHooksEnv(self):
4919
    """Build hooks env.
4920

4921
    This runs on master, primary and secondary nodes of the instance.
4922

4923
    """
4924
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4925
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4926
    return env, nl, nl
4927

    
4928
  def CheckPrereq(self):
4929
    """Check prerequisites.
4930

4931
    This checks that the instance is in the cluster and is not running.
4932

4933
    """
4934
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4935
    assert instance is not None, \
4936
      "Cannot retrieve locked instance %s" % self.op.instance_name
4937
    _CheckNodeOnline(self, instance.primary_node)
4938

    
4939
    if instance.disk_template == constants.DT_DISKLESS:
4940
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4941
                                 self.op.instance_name, errors.ECODE_INVAL)
4942
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4943

    
4944
    if not self.op.disks:
4945
      self.op.disks = range(len(instance.disks))
4946
    else:
4947
      for idx in self.op.disks:
4948
        if idx >= len(instance.disks):
4949
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4950
                                     errors.ECODE_INVAL)
4951

    
4952
    self.instance = instance
4953

    
4954
  def Exec(self, feedback_fn):
4955
    """Recreate the disks.
4956

4957
    """
4958
    to_skip = []
4959
    for idx, _ in enumerate(self.instance.disks):
4960
      if idx not in self.op.disks: # disk idx has not been passed in
4961
        to_skip.append(idx)
4962
        continue
4963

    
4964
    _CreateDisks(self, self.instance, to_skip=to_skip)
4965

    
4966

    
4967
class LURenameInstance(LogicalUnit):
4968
  """Rename an instance.
4969

4970
  """
4971
  HPATH = "instance-rename"
4972
  HTYPE = constants.HTYPE_INSTANCE
4973
  _OP_PARAMS = [
4974
    _PInstanceName,
4975
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
4976
    ("ip_check", False, ht.TBool),
4977
    ("name_check", True, ht.TBool),
4978
    ]
4979

    
4980
  def CheckArguments(self):
4981
    """Check arguments.
4982

4983
    """
4984
    if self.op.ip_check and not self.op.name_check:
4985
      # TODO: make the ip check more flexible and not depend on the name check
4986
      raise errors.OpPrereqError("Cannot do ip check without a name check",
4987
                                 errors.ECODE_INVAL)
4988

    
4989
  def BuildHooksEnv(self):
4990
    """Build hooks env.
4991

4992
    This runs on master, primary and secondary nodes of the instance.
4993

4994
    """
4995
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4996
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4997
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4998
    return env, nl, nl
4999

    
5000
  def CheckPrereq(self):
5001
    """Check prerequisites.
5002

5003
    This checks that the instance is in the cluster and is not running.
5004

5005
    """
5006
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5007
                                                self.op.instance_name)
5008
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5009
    assert instance is not None
5010
    _CheckNodeOnline(self, instance.primary_node)
5011
    _CheckInstanceDown(self, instance, "cannot rename")
5012
    self.instance = instance
5013

    
5014
    new_name = self.op.new_name
5015
    if self.op.name_check:
5016
      hostname = netutils.GetHostname(name=new_name)
5017
      new_name = self.op.new_name = hostname.name
5018
      if (self.op.ip_check and
5019
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5020
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5021
                                   (hostname.ip, new_name),
5022
                                   errors.ECODE_NOTUNIQUE)
5023

    
5024
    instance_list = self.cfg.GetInstanceList()
5025
    if new_name in instance_list:
5026
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5027
                                 new_name, errors.ECODE_EXISTS)
5028

    
5029
  def Exec(self, feedback_fn):
5030
    """Reinstall the instance.
5031

5032
    """
5033
    inst = self.instance
5034
    old_name = inst.name
5035

    
5036
    if inst.disk_template == constants.DT_FILE:
5037
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5038

    
5039
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5040
    # Change the instance lock. This is definitely safe while we hold the BGL
5041
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5042
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5043

    
5044
    # re-read the instance from the configuration after rename
5045
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5046

    
5047
    if inst.disk_template == constants.DT_FILE:
5048
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5049
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5050
                                                     old_file_storage_dir,
5051
                                                     new_file_storage_dir)
5052
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5053
                   " (but the instance has been renamed in Ganeti)" %
5054
                   (inst.primary_node, old_file_storage_dir,
5055
                    new_file_storage_dir))
5056

    
5057
    _StartInstanceDisks(self, inst, None)
5058
    try:
5059
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5060
                                                 old_name, self.op.debug_level)
5061
      msg = result.fail_msg
5062
      if msg:
5063
        msg = ("Could not run OS rename script for instance %s on node %s"
5064
               " (but the instance has been renamed in Ganeti): %s" %
5065
               (inst.name, inst.primary_node, msg))
5066
        self.proc.LogWarning(msg)
5067
    finally:
5068
      _ShutdownInstanceDisks(self, inst)
5069

    
5070
    return inst.name
5071

    
5072

    
5073
class LURemoveInstance(LogicalUnit):
5074
  """Remove an instance.
5075

5076
  """
5077
  HPATH = "instance-remove"
5078
  HTYPE = constants.HTYPE_INSTANCE
5079
  _OP_PARAMS = [
5080
    _PInstanceName,
5081
    ("ignore_failures", False, ht.TBool),
5082
    _PShutdownTimeout,
5083
    ]
5084
  REQ_BGL = False
5085

    
5086
  def ExpandNames(self):
5087
    self._ExpandAndLockInstance()
5088
    self.needed_locks[locking.LEVEL_NODE] = []
5089
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5090

    
5091
  def DeclareLocks(self, level):
5092
    if level == locking.LEVEL_NODE:
5093
      self._LockInstancesNodes()
5094

    
5095
  def BuildHooksEnv(self):
5096
    """Build hooks env.
5097

5098
    This runs on master, primary and secondary nodes of the instance.
5099

5100
    """
5101
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5102
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5103
    nl = [self.cfg.GetMasterNode()]
5104
    nl_post = list(self.instance.all_nodes) + nl
5105
    return env, nl, nl_post
5106

    
5107
  def CheckPrereq(self):
5108
    """Check prerequisites.
5109

5110
    This checks that the instance is in the cluster.
5111

5112
    """
5113
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5114
    assert self.instance is not None, \
5115
      "Cannot retrieve locked instance %s" % self.op.instance_name
5116

    
5117
  def Exec(self, feedback_fn):
5118
    """Remove the instance.
5119

5120
    """
5121
    instance = self.instance
5122
    logging.info("Shutting down instance %s on node %s",
5123
                 instance.name, instance.primary_node)
5124

    
5125
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5126
                                             self.op.shutdown_timeout)
5127
    msg = result.fail_msg
5128
    if msg:
5129
      if self.op.ignore_failures:
5130
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5131
      else:
5132
        raise errors.OpExecError("Could not shutdown instance %s on"
5133
                                 " node %s: %s" %
5134
                                 (instance.name, instance.primary_node, msg))
5135

    
5136
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5137

    
5138

    
5139
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5140
  """Utility function to remove an instance.
5141

5142
  """
5143
  logging.info("Removing block devices for instance %s", instance.name)
5144

    
5145
  if not _RemoveDisks(lu, instance):
5146
    if not ignore_failures:
5147
      raise errors.OpExecError("Can't remove instance's disks")
5148
    feedback_fn("Warning: can't remove instance's disks")
5149

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

    
5152
  lu.cfg.RemoveInstance(instance.name)
5153

    
5154
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5155
    "Instance lock removal conflict"
5156

    
5157
  # Remove lock for the instance
5158
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5159

    
5160

    
5161
class LUQueryInstances(NoHooksLU):
5162
  """Logical unit for querying instances.
5163

5164
  """
5165
  # pylint: disable-msg=W0142
5166
  _OP_PARAMS = [
5167
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
5168
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
5169
    ("use_locking", False, ht.TBool),
5170
    ]
5171
  REQ_BGL = False
5172
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5173
                    "serial_no", "ctime", "mtime", "uuid"]
5174
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5175
                                    "admin_state",
5176
                                    "disk_template", "ip", "mac", "bridge",
5177
                                    "nic_mode", "nic_link",
5178
                                    "sda_size", "sdb_size", "vcpus", "tags",
5179
                                    "network_port", "beparams",
5180
                                    r"(disk)\.(size)/([0-9]+)",
5181
                                    r"(disk)\.(sizes)", "disk_usage",
5182
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5183
                                    r"(nic)\.(bridge)/([0-9]+)",
5184
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5185
                                    r"(disk|nic)\.(count)",
5186
                                    "hvparams", "custom_hvparams",
5187
                                    "custom_beparams", "custom_nicparams",
5188
                                    ] + _SIMPLE_FIELDS +
5189
                                  ["hv/%s" % name
5190
                                   for name in constants.HVS_PARAMETERS
5191
                                   if name not in constants.HVC_GLOBALS] +
5192
                                  ["be/%s" % name
5193
                                   for name in constants.BES_PARAMETERS])
5194
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5195
                                   "oper_ram",
5196
                                   "oper_vcpus",
5197
                                   "status")
5198

    
5199

    
5200
  def CheckArguments(self):
5201
    _CheckOutputFields(static=self._FIELDS_STATIC,
5202
                       dynamic=self._FIELDS_DYNAMIC,
5203
                       selected=self.op.output_fields)
5204

    
5205
  def ExpandNames(self):
5206
    self.needed_locks = {}
5207
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5208
    self.share_locks[locking.LEVEL_NODE] = 1
5209

    
5210
    if self.op.names:
5211
      self.wanted = _GetWantedInstances(self, self.op.names)
5212
    else:
5213
      self.wanted = locking.ALL_SET
5214

    
5215
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5216
    self.do_locking = self.do_node_query and self.op.use_locking
5217
    if self.do_locking:
5218
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5219
      self.needed_locks[locking.LEVEL_NODE] = []
5220
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5221

    
5222
  def DeclareLocks(self, level):
5223
    if level == locking.LEVEL_NODE and self.do_locking:
5224
      self._LockInstancesNodes()
5225

    
5226
  def Exec(self, feedback_fn):
5227
    """Computes the list of nodes and their attributes.
5228

5229
    """
5230
    # pylint: disable-msg=R0912
5231
    # way too many branches here
5232
    all_info = self.cfg.GetAllInstancesInfo()
5233
    if self.wanted == locking.ALL_SET:
5234
      # caller didn't specify instance names, so ordering is not important
5235
      if self.do_locking:
5236
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5237
      else:
5238
        instance_names = all_info.keys()
5239
      instance_names = utils.NiceSort(instance_names)
5240
    else:
5241
      # caller did specify names, so we must keep the ordering
5242
      if self.do_locking:
5243
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5244
      else:
5245
        tgt_set = all_info.keys()
5246
      missing = set(self.wanted).difference(tgt_set)
5247
      if missing:
5248
        raise errors.OpExecError("Some instances were removed before"
5249
                                 " retrieving their data: %s" % missing)
5250
      instance_names = self.wanted
5251

    
5252
    instance_list = [all_info[iname] for iname in instance_names]
5253

    
5254
    # begin data gathering
5255

    
5256
    nodes = frozenset([inst.primary_node for inst in instance_list])
5257
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5258

    
5259
    bad_nodes = []
5260
    off_nodes = []
5261
    if self.do_node_query:
5262
      live_data = {}
5263
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5264
      for name in nodes:
5265
        result = node_data[name]
5266
        if result.offline:
5267
          # offline nodes will be in both lists
5268
          off_nodes.append(name)
5269
        if result.fail_msg:
5270
          bad_nodes.append(name)
5271
        else:
5272
          if result.payload:
5273
            live_data.update(result.payload)
5274
          # else no instance is alive
5275
    else:
5276
      live_data = dict([(name, {}) for name in instance_names])
5277

    
5278
    # end data gathering
5279

    
5280
    HVPREFIX = "hv/"
5281
    BEPREFIX = "be/"
5282
    output = []
5283
    cluster = self.cfg.GetClusterInfo()
5284
    for instance in instance_list:
5285
      iout = []
5286
      i_hv = cluster.FillHV(instance, skip_globals=True)
5287
      i_be = cluster.FillBE(instance)
5288
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5289
      for field in self.op.output_fields:
5290
        st_match = self._FIELDS_STATIC.Matches(field)
5291
        if field in self._SIMPLE_FIELDS:
5292
          val = getattr(instance, field)
5293
        elif field == "pnode":
5294
          val = instance.primary_node
5295
        elif field == "snodes":
5296
          val = list(instance.secondary_nodes)
5297
        elif field == "admin_state":
5298
          val = instance.admin_up
5299
        elif field == "oper_state":
5300
          if instance.primary_node in bad_nodes:
5301
            val = None
5302
          else:
5303
            val = bool(live_data.get(instance.name))
5304
        elif field == "status":
5305
          if instance.primary_node in off_nodes:
5306
            val = "ERROR_nodeoffline"
5307
          elif instance.primary_node in bad_nodes:
5308
            val = "ERROR_nodedown"
5309
          else:
5310
            running = bool(live_data.get(instance.name))
5311
            if running:
5312
              if instance.admin_up:
5313
                val = "running"
5314
              else:
5315
                val = "ERROR_up"
5316
            else:
5317
              if instance.admin_up:
5318
                val = "ERROR_down"
5319
              else:
5320
                val = "ADMIN_down"
5321
        elif field == "oper_ram":
5322
          if instance.primary_node in bad_nodes:
5323
            val = None
5324
          elif instance.name in live_data:
5325
            val = live_data[instance.name].get("memory", "?")
5326
          else:
5327
            val = "-"
5328
        elif field == "oper_vcpus":
5329
          if instance.primary_node in bad_nodes:
5330
            val = None
5331
          elif instance.name in live_data:
5332
            val = live_data[instance.name].get("vcpus", "?")
5333
          else:
5334
            val = "-"
5335
        elif field == "vcpus":
5336
          val = i_be[constants.BE_VCPUS]
5337
        elif field == "disk_template":
5338
          val = instance.disk_template
5339
        elif field == "ip":
5340
          if instance.nics:
5341
            val = instance.nics[0].ip
5342
          else:
5343
            val = None
5344
        elif field == "nic_mode":
5345
          if instance.nics:
5346
            val = i_nicp[0][constants.NIC_MODE]
5347
          else:
5348
            val = None
5349
        elif field == "nic_link":
5350
          if instance.nics:
5351
            val = i_nicp[0][constants.NIC_LINK]
5352
          else:
5353
            val = None
5354
        elif field == "bridge":
5355
          if (instance.nics and
5356
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5357
            val = i_nicp[0][constants.NIC_LINK]
5358
          else:
5359
            val = None
5360
        elif field == "mac":
5361
          if instance.nics:
5362
            val = instance.nics[0].mac
5363
          else:
5364
            val = None
5365
        elif field == "custom_nicparams":
5366
          val = [nic.nicparams for nic in instance.nics]
5367
        elif field == "sda_size" or field == "sdb_size":
5368
          idx = ord(field[2]) - ord('a')
5369
          try:
5370
            val = instance.FindDisk(idx).size
5371
          except errors.OpPrereqError:
5372
            val = None
5373
        elif field == "disk_usage": # total disk usage per node
5374
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5375
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5376
        elif field == "tags":
5377
          val = list(instance.GetTags())
5378
        elif field == "custom_hvparams":
5379
          val = instance.hvparams # not filled!
5380
        elif field == "hvparams":
5381
          val = i_hv
5382
        elif (field.startswith(HVPREFIX) and
5383
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5384
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5385
          val = i_hv.get(field[len(HVPREFIX):], None)
5386
        elif field == "custom_beparams":
5387
          val = instance.beparams
5388
        elif field == "beparams":
5389
          val = i_be
5390
        elif (field.startswith(BEPREFIX) and
5391
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5392
          val = i_be.get(field[len(BEPREFIX):], None)
5393
        elif st_match and st_match.groups():
5394
          # matches a variable list
5395
          st_groups = st_match.groups()
5396
          if st_groups and st_groups[0] == "disk":
5397
            if st_groups[1] == "count":
5398
              val = len(instance.disks)
5399
            elif st_groups[1] == "sizes":
5400
              val = [disk.size for disk in instance.disks]
5401
            elif st_groups[1] == "size":
5402
              try:
5403
                val = instance.FindDisk(st_groups[2]).size
5404
              except errors.OpPrereqError:
5405
                val = None
5406
            else:
5407
              assert False, "Unhandled disk parameter"
5408
          elif st_groups[0] == "nic":
5409
            if st_groups[1] == "count":
5410
              val = len(instance.nics)
5411
            elif st_groups[1] == "macs":
5412
              val = [nic.mac for nic in instance.nics]
5413
            elif st_groups[1] == "ips":
5414
              val = [nic.ip for nic in instance.nics]
5415
            elif st_groups[1] == "modes":
5416
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5417
            elif st_groups[1] == "links":
5418
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5419
            elif st_groups[1] == "bridges":
5420
              val = []
5421
              for nicp in i_nicp:
5422
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5423
                  val.append(nicp[constants.NIC_LINK])
5424
                else:
5425
                  val.append(None)
5426
            else:
5427
              # index-based item
5428
              nic_idx = int(st_groups[2])
5429
              if nic_idx >= len(instance.nics):
5430
                val = None
5431
              else:
5432
                if st_groups[1] == "mac":
5433
                  val = instance.nics[nic_idx].mac
5434
                elif st_groups[1] == "ip":
5435
                  val = instance.nics[nic_idx].ip
5436
                elif st_groups[1] == "mode":
5437
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5438
                elif st_groups[1] == "link":
5439
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5440
                elif st_groups[1] == "bridge":
5441
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5442
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5443
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5444
                  else:
5445
                    val = None
5446
                else:
5447
                  assert False, "Unhandled NIC parameter"
5448
          else:
5449
            assert False, ("Declared but unhandled variable parameter '%s'" %
5450
                           field)
5451
        else:
5452
          assert False, "Declared but unhandled parameter '%s'" % field
5453
        iout.append(val)
5454
      output.append(iout)
5455

    
5456
    return output
5457

    
5458

    
5459
class LUFailoverInstance(LogicalUnit):
5460
  """Failover an instance.
5461

5462
  """
5463
  HPATH = "instance-failover"
5464
  HTYPE = constants.HTYPE_INSTANCE
5465
  _OP_PARAMS = [
5466
    _PInstanceName,
5467
    ("ignore_consistency", False, ht.TBool),
5468
    _PShutdownTimeout,
5469
    ]
5470
  REQ_BGL = False
5471

    
5472
  def ExpandNames(self):
5473
    self._ExpandAndLockInstance()
5474
    self.needed_locks[locking.LEVEL_NODE] = []
5475
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5476

    
5477
  def DeclareLocks(self, level):
5478
    if level == locking.LEVEL_NODE:
5479
      self._LockInstancesNodes()
5480

    
5481
  def BuildHooksEnv(self):
5482
    """Build hooks env.
5483

5484
    This runs on master, primary and secondary nodes of the instance.
5485

5486
    """
5487
    instance = self.instance
5488
    source_node = instance.primary_node
5489
    target_node = instance.secondary_nodes[0]
5490
    env = {
5491
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5492
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5493
      "OLD_PRIMARY": source_node,
5494
      "OLD_SECONDARY": target_node,
5495
      "NEW_PRIMARY": target_node,
5496
      "NEW_SECONDARY": source_node,
5497
      }
5498
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5499
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5500
    nl_post = list(nl)
5501
    nl_post.append(source_node)
5502
    return env, nl, nl_post
5503

    
5504
  def CheckPrereq(self):
5505
    """Check prerequisites.
5506

5507
    This checks that the instance is in the cluster.
5508

5509
    """
5510
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5511
    assert self.instance is not None, \
5512
      "Cannot retrieve locked instance %s" % self.op.instance_name
5513

    
5514
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5515
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5516
      raise errors.OpPrereqError("Instance's disk layout is not"
5517
                                 " network mirrored, cannot failover.",
5518
                                 errors.ECODE_STATE)
5519

    
5520
    secondary_nodes = instance.secondary_nodes
5521
    if not secondary_nodes:
5522
      raise errors.ProgrammerError("no secondary node but using "
5523
                                   "a mirrored disk template")
5524

    
5525
    target_node = secondary_nodes[0]
5526
    _CheckNodeOnline(self, target_node)
5527
    _CheckNodeNotDrained(self, target_node)
5528
    if instance.admin_up:
5529
      # check memory requirements on the secondary node
5530
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5531
                           instance.name, bep[constants.BE_MEMORY],
5532
                           instance.hypervisor)
5533
    else:
5534
      self.LogInfo("Not checking memory on the secondary node as"
5535
                   " instance will not be started")
5536

    
5537
    # check bridge existance
5538
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5539

    
5540
  def Exec(self, feedback_fn):
5541
    """Failover an instance.
5542

5543
    The failover is done by shutting it down on its present node and
5544
    starting it on the secondary.
5545

5546
    """
5547
    instance = self.instance
5548
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5549

    
5550
    source_node = instance.primary_node
5551
    target_node = instance.secondary_nodes[0]
5552

    
5553
    if instance.admin_up:
5554
      feedback_fn("* checking disk consistency between source and target")
5555
      for dev in instance.disks:
5556
        # for drbd, these are drbd over lvm
5557
        if not _CheckDiskConsistency(self, dev, target_node, False):
5558
          if not self.op.ignore_consistency:
5559
            raise errors.OpExecError("Disk %s is degraded on target node,"
5560
                                     " aborting failover." % dev.iv_name)
5561
    else:
5562
      feedback_fn("* not checking disk consistency as instance is not running")
5563

    
5564
    feedback_fn("* shutting down instance on source node")
5565
    logging.info("Shutting down instance %s on node %s",
5566
                 instance.name, source_node)
5567

    
5568
    result = self.rpc.call_instance_shutdown(source_node, instance,
5569
                                             self.op.shutdown_timeout)
5570
    msg = result.fail_msg
5571
    if msg:
5572
      if self.op.ignore_consistency or primary_node.offline:
5573
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5574
                             " Proceeding anyway. Please make sure node"
5575
                             " %s is down. Error details: %s",
5576
                             instance.name, source_node, source_node, msg)
5577
      else:
5578
        raise errors.OpExecError("Could not shutdown instance %s on"
5579
                                 " node %s: %s" %
5580
                                 (instance.name, source_node, msg))
5581

    
5582
    feedback_fn("* deactivating the instance's disks on source node")
5583
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5584
      raise errors.OpExecError("Can't shut down the instance's disks.")
5585

    
5586
    instance.primary_node = target_node
5587
    # distribute new instance config to the other nodes
5588
    self.cfg.Update(instance, feedback_fn)
5589

    
5590
    # Only start the instance if it's marked as up
5591
    if instance.admin_up:
5592
      feedback_fn("* activating the instance's disks on target node")
5593
      logging.info("Starting instance %s on node %s",
5594
                   instance.name, target_node)
5595

    
5596
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5597
                                           ignore_secondaries=True)
5598
      if not disks_ok:
5599
        _ShutdownInstanceDisks(self, instance)
5600
        raise errors.OpExecError("Can't activate the instance's disks")
5601

    
5602
      feedback_fn("* starting the instance on the target node")
5603
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5604
      msg = result.fail_msg
5605
      if msg:
5606
        _ShutdownInstanceDisks(self, instance)
5607
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5608
                                 (instance.name, target_node, msg))
5609

    
5610

    
5611
class LUMigrateInstance(LogicalUnit):
5612
  """Migrate an instance.
5613

5614
  This is migration without shutting down, compared to the failover,
5615
  which is done with shutdown.
5616

5617
  """
5618
  HPATH = "instance-migrate"
5619
  HTYPE = constants.HTYPE_INSTANCE
5620
  _OP_PARAMS = [
5621
    _PInstanceName,
5622
    _PMigrationMode,
5623
    _PMigrationLive,
5624
    ("cleanup", False, ht.TBool),
5625
    ]
5626

    
5627
  REQ_BGL = False
5628

    
5629
  def ExpandNames(self):
5630
    self._ExpandAndLockInstance()
5631

    
5632
    self.needed_locks[locking.LEVEL_NODE] = []
5633
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5634

    
5635
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5636
                                       self.op.cleanup)
5637
    self.tasklets = [self._migrater]
5638

    
5639
  def DeclareLocks(self, level):
5640
    if level == locking.LEVEL_NODE:
5641
      self._LockInstancesNodes()
5642

    
5643
  def BuildHooksEnv(self):
5644
    """Build hooks env.
5645

5646
    This runs on master, primary and secondary nodes of the instance.
5647

5648
    """
5649
    instance = self._migrater.instance
5650
    source_node = instance.primary_node
5651
    target_node = instance.secondary_nodes[0]
5652
    env = _BuildInstanceHookEnvByObject(self, instance)
5653
    env["MIGRATE_LIVE"] = self._migrater.live
5654
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5655
    env.update({
5656
        "OLD_PRIMARY": source_node,
5657
        "OLD_SECONDARY": target_node,
5658
        "NEW_PRIMARY": target_node,
5659
        "NEW_SECONDARY": source_node,
5660
        })
5661
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5662
    nl_post = list(nl)
5663
    nl_post.append(source_node)
5664
    return env, nl, nl_post
5665

    
5666

    
5667
class LUMoveInstance(LogicalUnit):
5668
  """Move an instance by data-copying.
5669

5670
  """
5671
  HPATH = "instance-move"
5672
  HTYPE = constants.HTYPE_INSTANCE
5673
  _OP_PARAMS = [
5674
    _PInstanceName,
5675
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5676
    _PShutdownTimeout,
5677
    ]
5678
  REQ_BGL = False
5679

    
5680
  def ExpandNames(self):
5681
    self._ExpandAndLockInstance()
5682
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5683
    self.op.target_node = target_node
5684
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5685
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5686

    
5687
  def DeclareLocks(self, level):
5688
    if level == locking.LEVEL_NODE:
5689
      self._LockInstancesNodes(primary_only=True)
5690

    
5691
  def BuildHooksEnv(self):
5692
    """Build hooks env.
5693

5694
    This runs on master, primary and secondary nodes of the instance.
5695

5696
    """
5697
    env = {
5698
      "TARGET_NODE": self.op.target_node,
5699
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5700
      }
5701
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5702
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5703
                                       self.op.target_node]
5704
    return env, nl, nl
5705

    
5706
  def CheckPrereq(self):
5707
    """Check prerequisites.
5708

5709
    This checks that the instance is in the cluster.
5710

5711
    """
5712
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5713
    assert self.instance is not None, \
5714
      "Cannot retrieve locked instance %s" % self.op.instance_name
5715

    
5716
    node = self.cfg.GetNodeInfo(self.op.target_node)
5717
    assert node is not None, \
5718
      "Cannot retrieve locked node %s" % self.op.target_node
5719

    
5720
    self.target_node = target_node = node.name
5721

    
5722
    if target_node == instance.primary_node:
5723
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5724
                                 (instance.name, target_node),
5725
                                 errors.ECODE_STATE)
5726

    
5727
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5728

    
5729
    for idx, dsk in enumerate(instance.disks):
5730
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5731
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5732
                                   " cannot copy" % idx, errors.ECODE_STATE)
5733

    
5734
    _CheckNodeOnline(self, target_node)
5735
    _CheckNodeNotDrained(self, target_node)
5736

    
5737
    if instance.admin_up:
5738
      # check memory requirements on the secondary node
5739
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5740
                           instance.name, bep[constants.BE_MEMORY],
5741
                           instance.hypervisor)
5742
    else:
5743
      self.LogInfo("Not checking memory on the secondary node as"
5744
                   " instance will not be started")
5745

    
5746
    # check bridge existance
5747
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5748

    
5749
  def Exec(self, feedback_fn):
5750
    """Move an instance.
5751

5752
    The move is done by shutting it down on its present node, copying
5753
    the data over (slow) and starting it on the new node.
5754

5755
    """
5756
    instance = self.instance
5757

    
5758
    source_node = instance.primary_node
5759
    target_node = self.target_node
5760

    
5761
    self.LogInfo("Shutting down instance %s on source node %s",
5762
                 instance.name, source_node)
5763

    
5764
    result = self.rpc.call_instance_shutdown(source_node, instance,
5765
                                             self.op.shutdown_timeout)
5766
    msg = result.fail_msg
5767
    if msg:
5768
      if self.op.ignore_consistency:
5769
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5770
                             " Proceeding anyway. Please make sure node"
5771
                             " %s is down. Error details: %s",
5772
                             instance.name, source_node, source_node, msg)
5773
      else:
5774
        raise errors.OpExecError("Could not shutdown instance %s on"
5775
                                 " node %s: %s" %
5776
                                 (instance.name, source_node, msg))
5777

    
5778
    # create the target disks
5779
    try:
5780
      _CreateDisks(self, instance, target_node=target_node)
5781
    except errors.OpExecError:
5782
      self.LogWarning("Device creation failed, reverting...")
5783
      try:
5784
        _RemoveDisks(self, instance, target_node=target_node)
5785
      finally:
5786
        self.cfg.ReleaseDRBDMinors(instance.name)
5787
        raise
5788

    
5789
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5790

    
5791
    errs = []
5792
    # activate, get path, copy the data over
5793
    for idx, disk in enumerate(instance.disks):
5794
      self.LogInfo("Copying data for disk %d", idx)
5795
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5796
                                               instance.name, True)
5797
      if result.fail_msg:
5798
        self.LogWarning("Can't assemble newly created disk %d: %s",
5799
                        idx, result.fail_msg)
5800
        errs.append(result.fail_msg)
5801
        break
5802
      dev_path = result.payload
5803
      result = self.rpc.call_blockdev_export(source_node, disk,
5804
                                             target_node, dev_path,
5805
                                             cluster_name)
5806
      if result.fail_msg:
5807
        self.LogWarning("Can't copy data over for disk %d: %s",
5808
                        idx, result.fail_msg)
5809
        errs.append(result.fail_msg)
5810
        break
5811

    
5812
    if errs:
5813
      self.LogWarning("Some disks failed to copy, aborting")
5814
      try:
5815
        _RemoveDisks(self, instance, target_node=target_node)
5816
      finally:
5817
        self.cfg.ReleaseDRBDMinors(instance.name)
5818
        raise errors.OpExecError("Errors during disk copy: %s" %
5819
                                 (",".join(errs),))
5820

    
5821
    instance.primary_node = target_node
5822
    self.cfg.Update(instance, feedback_fn)
5823

    
5824
    self.LogInfo("Removing the disks on the original node")
5825
    _RemoveDisks(self, instance, target_node=source_node)
5826

    
5827
    # Only start the instance if it's marked as up
5828
    if instance.admin_up:
5829
      self.LogInfo("Starting instance %s on node %s",
5830
                   instance.name, target_node)
5831

    
5832
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5833
                                           ignore_secondaries=True)
5834
      if not disks_ok:
5835
        _ShutdownInstanceDisks(self, instance)
5836
        raise errors.OpExecError("Can't activate the instance's disks")
5837

    
5838
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5839
      msg = result.fail_msg
5840
      if msg:
5841
        _ShutdownInstanceDisks(self, instance)
5842
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5843
                                 (instance.name, target_node, msg))
5844

    
5845

    
5846
class LUMigrateNode(LogicalUnit):
5847
  """Migrate all instances from a node.
5848

5849
  """
5850
  HPATH = "node-migrate"
5851
  HTYPE = constants.HTYPE_NODE
5852
  _OP_PARAMS = [
5853
    _PNodeName,
5854
    _PMigrationMode,
5855
    _PMigrationLive,
5856
    ]
5857
  REQ_BGL = False
5858

    
5859
  def ExpandNames(self):
5860
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5861

    
5862
    self.needed_locks = {
5863
      locking.LEVEL_NODE: [self.op.node_name],
5864
      }
5865

    
5866
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5867

    
5868
    # Create tasklets for migrating instances for all instances on this node
5869
    names = []
5870
    tasklets = []
5871

    
5872
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5873
      logging.debug("Migrating instance %s", inst.name)
5874
      names.append(inst.name)
5875

    
5876
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5877

    
5878
    self.tasklets = tasklets
5879

    
5880
    # Declare instance locks
5881
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5882

    
5883
  def DeclareLocks(self, level):
5884
    if level == locking.LEVEL_NODE:
5885
      self._LockInstancesNodes()
5886

    
5887
  def BuildHooksEnv(self):
5888
    """Build hooks env.
5889

5890
    This runs on the master, the primary and all the secondaries.
5891

5892
    """
5893
    env = {
5894
      "NODE_NAME": self.op.node_name,
5895
      }
5896

    
5897
    nl = [self.cfg.GetMasterNode()]
5898

    
5899
    return (env, nl, nl)
5900

    
5901

    
5902
class TLMigrateInstance(Tasklet):
5903
  """Tasklet class for instance migration.
5904

5905
  @type live: boolean
5906
  @ivar live: whether the migration will be done live or non-live;
5907
      this variable is initalized only after CheckPrereq has run
5908

5909
  """
5910
  def __init__(self, lu, instance_name, cleanup):
5911
    """Initializes this class.
5912

5913
    """
5914
    Tasklet.__init__(self, lu)
5915

    
5916
    # Parameters
5917
    self.instance_name = instance_name
5918
    self.cleanup = cleanup
5919
    self.live = False # will be overridden later
5920

    
5921
  def CheckPrereq(self):
5922
    """Check prerequisites.
5923

5924
    This checks that the instance is in the cluster.
5925

5926
    """
5927
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5928
    instance = self.cfg.GetInstanceInfo(instance_name)
5929
    assert instance is not None
5930

    
5931
    if instance.disk_template != constants.DT_DRBD8:
5932
      raise errors.OpPrereqError("Instance's disk layout is not"
5933
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5934

    
5935
    secondary_nodes = instance.secondary_nodes
5936
    if not secondary_nodes:
5937
      raise errors.ConfigurationError("No secondary node but using"
5938
                                      " drbd8 disk template")
5939

    
5940
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5941

    
5942
    target_node = secondary_nodes[0]
5943
    # check memory requirements on the secondary node
5944
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5945
                         instance.name, i_be[constants.BE_MEMORY],
5946
                         instance.hypervisor)
5947

    
5948
    # check bridge existance
5949
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5950

    
5951
    if not self.cleanup:
5952
      _CheckNodeNotDrained(self.lu, target_node)
5953
      result = self.rpc.call_instance_migratable(instance.primary_node,
5954
                                                 instance)
5955
      result.Raise("Can't migrate, please use failover",
5956
                   prereq=True, ecode=errors.ECODE_STATE)
5957

    
5958
    self.instance = instance
5959

    
5960
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5961
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5962
                                 " parameters are accepted",
5963
                                 errors.ECODE_INVAL)
5964
    if self.lu.op.live is not None:
5965
      if self.lu.op.live:
5966
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5967
      else:
5968
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
5969
      # reset the 'live' parameter to None so that repeated
5970
      # invocations of CheckPrereq do not raise an exception
5971
      self.lu.op.live = None
5972
    elif self.lu.op.mode is None:
5973
      # read the default value from the hypervisor
5974
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5975
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5976

    
5977
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5978

    
5979
  def _WaitUntilSync(self):
5980
    """Poll with custom rpc for disk sync.
5981

5982
    This uses our own step-based rpc call.
5983

5984
    """
5985
    self.feedback_fn("* wait until resync is done")
5986
    all_done = False
5987
    while not all_done:
5988
      all_done = True
5989
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5990
                                            self.nodes_ip,
5991
                                            self.instance.disks)
5992
      min_percent = 100
5993
      for node, nres in result.items():
5994
        nres.Raise("Cannot resync disks on node %s" % node)
5995
        node_done, node_percent = nres.payload
5996
        all_done = all_done and node_done
5997
        if node_percent is not None:
5998
          min_percent = min(min_percent, node_percent)
5999
      if not all_done:
6000
        if min_percent < 100:
6001
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6002
        time.sleep(2)
6003

    
6004
  def _EnsureSecondary(self, node):
6005
    """Demote a node to secondary.
6006

6007
    """
6008
    self.feedback_fn("* switching node %s to secondary mode" % node)
6009

    
6010
    for dev in self.instance.disks:
6011
      self.cfg.SetDiskID(dev, node)
6012

    
6013
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6014
                                          self.instance.disks)
6015
    result.Raise("Cannot change disk to secondary on node %s" % node)
6016

    
6017
  def _GoStandalone(self):
6018
    """Disconnect from the network.
6019

6020
    """
6021
    self.feedback_fn("* changing into standalone mode")
6022
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6023
                                               self.instance.disks)
6024
    for node, nres in result.items():
6025
      nres.Raise("Cannot disconnect disks node %s" % node)
6026

    
6027
  def _GoReconnect(self, multimaster):
6028
    """Reconnect to the network.
6029

6030
    """
6031
    if multimaster:
6032
      msg = "dual-master"
6033
    else:
6034
      msg = "single-master"
6035
    self.feedback_fn("* changing disks into %s mode" % msg)
6036
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6037
                                           self.instance.disks,
6038
                                           self.instance.name, multimaster)
6039
    for node, nres in result.items():
6040
      nres.Raise("Cannot change disks config on node %s" % node)
6041

    
6042
  def _ExecCleanup(self):
6043
    """Try to cleanup after a failed migration.
6044

6045
    The cleanup is done by:
6046
      - check that the instance is running only on one node
6047
        (and update the config if needed)
6048
      - change disks on its secondary node to secondary
6049
      - wait until disks are fully synchronized
6050
      - disconnect from the network
6051
      - change disks into single-master mode
6052
      - wait again until disks are fully synchronized
6053

6054
    """
6055
    instance = self.instance
6056
    target_node = self.target_node
6057
    source_node = self.source_node
6058

    
6059
    # check running on only one node
6060
    self.feedback_fn("* checking where the instance actually runs"
6061
                     " (if this hangs, the hypervisor might be in"
6062
                     " a bad state)")
6063
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6064
    for node, result in ins_l.items():
6065
      result.Raise("Can't contact node %s" % node)
6066

    
6067
    runningon_source = instance.name in ins_l[source_node].payload
6068
    runningon_target = instance.name in ins_l[target_node].payload
6069

    
6070
    if runningon_source and runningon_target:
6071
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6072
                               " or the hypervisor is confused. You will have"
6073
                               " to ensure manually that it runs only on one"
6074
                               " and restart this operation.")
6075

    
6076
    if not (runningon_source or runningon_target):
6077
      raise errors.OpExecError("Instance does not seem to be running at all."
6078
                               " In this case, it's safer to repair by"
6079
                               " running 'gnt-instance stop' to ensure disk"
6080
                               " shutdown, and then restarting it.")
6081

    
6082
    if runningon_target:
6083
      # the migration has actually succeeded, we need to update the config
6084
      self.feedback_fn("* instance running on secondary node (%s),"
6085
                       " updating config" % target_node)
6086
      instance.primary_node = target_node
6087
      self.cfg.Update(instance, self.feedback_fn)
6088
      demoted_node = source_node
6089
    else:
6090
      self.feedback_fn("* instance confirmed to be running on its"
6091
                       " primary node (%s)" % source_node)
6092
      demoted_node = target_node
6093

    
6094
    self._EnsureSecondary(demoted_node)
6095
    try:
6096
      self._WaitUntilSync()
6097
    except errors.OpExecError:
6098
      # we ignore here errors, since if the device is standalone, it
6099
      # won't be able to sync
6100
      pass
6101
    self._GoStandalone()
6102
    self._GoReconnect(False)
6103
    self._WaitUntilSync()
6104

    
6105
    self.feedback_fn("* done")
6106

    
6107
  def _RevertDiskStatus(self):
6108
    """Try to revert the disk status after a failed migration.
6109

6110
    """
6111
    target_node = self.target_node
6112
    try:
6113
      self._EnsureSecondary(target_node)
6114
      self._GoStandalone()
6115
      self._GoReconnect(False)
6116
      self._WaitUntilSync()
6117
    except errors.OpExecError, err:
6118
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6119
                         " drives: error '%s'\n"
6120
                         "Please look and recover the instance status" %
6121
                         str(err))
6122

    
6123
  def _AbortMigration(self):
6124
    """Call the hypervisor code to abort a started migration.
6125

6126
    """
6127
    instance = self.instance
6128
    target_node = self.target_node
6129
    migration_info = self.migration_info
6130

    
6131
    abort_result = self.rpc.call_finalize_migration(target_node,
6132
                                                    instance,
6133
                                                    migration_info,
6134
                                                    False)
6135
    abort_msg = abort_result.fail_msg
6136
    if abort_msg:
6137
      logging.error("Aborting migration failed on target node %s: %s",
6138
                    target_node, abort_msg)
6139
      # Don't raise an exception here, as we stil have to try to revert the
6140
      # disk status, even if this step failed.
6141

    
6142
  def _ExecMigration(self):
6143
    """Migrate an instance.
6144

6145
    The migrate is done by:
6146
      - change the disks into dual-master mode
6147
      - wait until disks are fully synchronized again
6148
      - migrate the instance
6149
      - change disks on the new secondary node (the old primary) to secondary
6150
      - wait until disks are fully synchronized
6151
      - change disks into single-master mode
6152

6153
    """
6154
    instance = self.instance
6155
    target_node = self.target_node
6156
    source_node = self.source_node
6157

    
6158
    self.feedback_fn("* checking disk consistency between source and target")
6159
    for dev in instance.disks:
6160
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6161
        raise errors.OpExecError("Disk %s is degraded or not fully"
6162
                                 " synchronized on target node,"
6163
                                 " aborting migrate." % dev.iv_name)
6164

    
6165
    # First get the migration information from the remote node
6166
    result = self.rpc.call_migration_info(source_node, instance)
6167
    msg = result.fail_msg
6168
    if msg:
6169
      log_err = ("Failed fetching source migration information from %s: %s" %
6170
                 (source_node, msg))
6171
      logging.error(log_err)
6172
      raise errors.OpExecError(log_err)
6173

    
6174
    self.migration_info = migration_info = result.payload
6175

    
6176
    # Then switch the disks to master/master mode
6177
    self._EnsureSecondary(target_node)
6178
    self._GoStandalone()
6179
    self._GoReconnect(True)
6180
    self._WaitUntilSync()
6181

    
6182
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6183
    result = self.rpc.call_accept_instance(target_node,
6184
                                           instance,
6185
                                           migration_info,
6186
                                           self.nodes_ip[target_node])
6187

    
6188
    msg = result.fail_msg
6189
    if msg:
6190
      logging.error("Instance pre-migration failed, trying to revert"
6191
                    " disk status: %s", msg)
6192
      self.feedback_fn("Pre-migration failed, aborting")
6193
      self._AbortMigration()
6194
      self._RevertDiskStatus()
6195
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6196
                               (instance.name, msg))
6197

    
6198
    self.feedback_fn("* migrating instance to %s" % target_node)
6199
    time.sleep(10)
6200
    result = self.rpc.call_instance_migrate(source_node, instance,
6201
                                            self.nodes_ip[target_node],
6202
                                            self.live)
6203
    msg = result.fail_msg
6204
    if msg:
6205
      logging.error("Instance migration failed, trying to revert"
6206
                    " disk status: %s", msg)
6207
      self.feedback_fn("Migration failed, aborting")
6208
      self._AbortMigration()
6209
      self._RevertDiskStatus()
6210
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6211
                               (instance.name, msg))
6212
    time.sleep(10)
6213

    
6214
    instance.primary_node = target_node
6215
    # distribute new instance config to the other nodes
6216
    self.cfg.Update(instance, self.feedback_fn)
6217

    
6218
    result = self.rpc.call_finalize_migration(target_node,
6219
                                              instance,
6220
                                              migration_info,
6221
                                              True)
6222
    msg = result.fail_msg
6223
    if msg:
6224
      logging.error("Instance migration succeeded, but finalization failed:"
6225
                    " %s", msg)
6226
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6227
                               msg)
6228

    
6229
    self._EnsureSecondary(source_node)
6230
    self._WaitUntilSync()
6231
    self._GoStandalone()
6232
    self._GoReconnect(False)
6233
    self._WaitUntilSync()
6234

    
6235
    self.feedback_fn("* done")
6236

    
6237
  def Exec(self, feedback_fn):
6238
    """Perform the migration.
6239

6240
    """
6241
    feedback_fn("Migrating instance %s" % self.instance.name)
6242

    
6243
    self.feedback_fn = feedback_fn
6244

    
6245
    self.source_node = self.instance.primary_node
6246
    self.target_node = self.instance.secondary_nodes[0]
6247
    self.all_nodes = [self.source_node, self.target_node]
6248
    self.nodes_ip = {
6249
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6250
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6251
      }
6252

    
6253
    if self.cleanup:
6254
      return self._ExecCleanup()
6255
    else:
6256
      return self._ExecMigration()
6257

    
6258

    
6259
def _CreateBlockDev(lu, node, instance, device, force_create,
6260
                    info, force_open):
6261
  """Create a tree of block devices on a given node.
6262

6263
  If this device type has to be created on secondaries, create it and
6264
  all its children.
6265

6266
  If not, just recurse to children keeping the same 'force' value.
6267

6268
  @param lu: the lu on whose behalf we execute
6269
  @param node: the node on which to create the device
6270
  @type instance: L{objects.Instance}
6271
  @param instance: the instance which owns the device
6272
  @type device: L{objects.Disk}
6273
  @param device: the device to create
6274
  @type force_create: boolean
6275
  @param force_create: whether to force creation of this device; this
6276
      will be change to True whenever we find a device which has
6277
      CreateOnSecondary() attribute
6278
  @param info: the extra 'metadata' we should attach to the device
6279
      (this will be represented as a LVM tag)
6280
  @type force_open: boolean
6281
  @param force_open: this parameter will be passes to the
6282
      L{backend.BlockdevCreate} function where it specifies
6283
      whether we run on primary or not, and it affects both
6284
      the child assembly and the device own Open() execution
6285

6286
  """
6287
  if device.CreateOnSecondary():
6288
    force_create = True
6289

    
6290
  if device.children:
6291
    for child in device.children:
6292
      _CreateBlockDev(lu, node, instance, child, force_create,
6293
                      info, force_open)
6294

    
6295
  if not force_create:
6296
    return
6297

    
6298
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6299

    
6300

    
6301
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6302
  """Create a single block device on a given node.
6303

6304
  This will not recurse over children of the device, so they must be
6305
  created in advance.
6306

6307
  @param lu: the lu on whose behalf we execute
6308
  @param node: the node on which to create the device
6309
  @type instance: L{objects.Instance}
6310
  @param instance: the instance which owns the device
6311
  @type device: L{objects.Disk}
6312
  @param device: the device to create
6313
  @param info: the extra 'metadata' we should attach to the device
6314
      (this will be represented as a LVM tag)
6315
  @type force_open: boolean
6316
  @param force_open: this parameter will be passes to the
6317
      L{backend.BlockdevCreate} function where it specifies
6318
      whether we run on primary or not, and it affects both
6319
      the child assembly and the device own Open() execution
6320

6321
  """
6322
  lu.cfg.SetDiskID(device, node)
6323
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6324
                                       instance.name, force_open, info)
6325
  result.Raise("Can't create block device %s on"
6326
               " node %s for instance %s" % (device, node, instance.name))
6327
  if device.physical_id is None:
6328
    device.physical_id = result.payload
6329

    
6330

    
6331
def _GenerateUniqueNames(lu, exts):
6332
  """Generate a suitable LV name.
6333

6334
  This will generate a logical volume name for the given instance.
6335

6336
  """
6337
  results = []
6338
  for val in exts:
6339
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6340
    results.append("%s%s" % (new_id, val))
6341
  return results
6342

    
6343

    
6344
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6345
                         p_minor, s_minor):
6346
  """Generate a drbd8 device complete with its children.
6347

6348
  """
6349
  port = lu.cfg.AllocatePort()
6350
  vgname = lu.cfg.GetVGName()
6351
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6352
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6353
                          logical_id=(vgname, names[0]))
6354
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6355
                          logical_id=(vgname, names[1]))
6356
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6357
                          logical_id=(primary, secondary, port,
6358
                                      p_minor, s_minor,
6359
                                      shared_secret),
6360
                          children=[dev_data, dev_meta],
6361
                          iv_name=iv_name)
6362
  return drbd_dev
6363

    
6364

    
6365
def _GenerateDiskTemplate(lu, template_name,
6366
                          instance_name, primary_node,
6367
                          secondary_nodes, disk_info,
6368
                          file_storage_dir, file_driver,
6369
                          base_index):
6370
  """Generate the entire disk layout for a given template type.
6371

6372
  """
6373
  #TODO: compute space requirements
6374

    
6375
  vgname = lu.cfg.GetVGName()
6376
  disk_count = len(disk_info)
6377
  disks = []
6378
  if template_name == constants.DT_DISKLESS:
6379
    pass
6380
  elif template_name == constants.DT_PLAIN:
6381
    if len(secondary_nodes) != 0:
6382
      raise errors.ProgrammerError("Wrong template configuration")
6383

    
6384
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6385
                                      for i in range(disk_count)])
6386
    for idx, disk in enumerate(disk_info):
6387
      disk_index = idx + base_index
6388
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6389
                              logical_id=(vgname, names[idx]),
6390
                              iv_name="disk/%d" % disk_index,
6391
                              mode=disk["mode"])
6392
      disks.append(disk_dev)
6393
  elif template_name == constants.DT_DRBD8:
6394
    if len(secondary_nodes) != 1:
6395
      raise errors.ProgrammerError("Wrong template configuration")
6396
    remote_node = secondary_nodes[0]
6397
    minors = lu.cfg.AllocateDRBDMinor(
6398
      [primary_node, remote_node] * len(disk_info), instance_name)
6399

    
6400
    names = []
6401
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6402
                                               for i in range(disk_count)]):
6403
      names.append(lv_prefix + "_data")
6404
      names.append(lv_prefix + "_meta")
6405
    for idx, disk in enumerate(disk_info):
6406
      disk_index = idx + base_index
6407
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6408
                                      disk["size"], names[idx*2:idx*2+2],
6409
                                      "disk/%d" % disk_index,
6410
                                      minors[idx*2], minors[idx*2+1])
6411
      disk_dev.mode = disk["mode"]
6412
      disks.append(disk_dev)
6413
  elif template_name == constants.DT_FILE:
6414
    if len(secondary_nodes) != 0:
6415
      raise errors.ProgrammerError("Wrong template configuration")
6416

    
6417
    _RequireFileStorage()
6418

    
6419
    for idx, disk in enumerate(disk_info):
6420
      disk_index = idx + base_index
6421
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6422
                              iv_name="disk/%d" % disk_index,
6423
                              logical_id=(file_driver,
6424
                                          "%s/disk%d" % (file_storage_dir,
6425
                                                         disk_index)),
6426
                              mode=disk["mode"])
6427
      disks.append(disk_dev)
6428
  else:
6429
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6430
  return disks
6431

    
6432

    
6433
def _GetInstanceInfoText(instance):
6434
  """Compute that text that should be added to the disk's metadata.
6435

6436
  """
6437
  return "originstname+%s" % instance.name
6438

    
6439

    
6440
def _CalcEta(time_taken, written, total_size):
6441
  """Calculates the ETA based on size written and total size.
6442

6443
  @param time_taken: The time taken so far
6444
  @param written: amount written so far
6445
  @param total_size: The total size of data to be written
6446
  @return: The remaining time in seconds
6447

6448
  """
6449
  avg_time = time_taken / float(written)
6450
  return (total_size - written) * avg_time
6451

    
6452

    
6453
def _WipeDisks(lu, instance):
6454
  """Wipes instance disks.
6455

6456
  @type lu: L{LogicalUnit}
6457
  @param lu: the logical unit on whose behalf we execute
6458
  @type instance: L{objects.Instance}
6459
  @param instance: the instance whose disks we should create
6460
  @return: the success of the wipe
6461

6462
  """
6463
  node = instance.primary_node
6464
  for idx, device in enumerate(instance.disks):
6465
    lu.LogInfo("* Wiping disk %d", idx)
6466
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6467

    
6468
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6469
    # MAX_WIPE_CHUNK at max
6470
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6471
                          constants.MIN_WIPE_CHUNK_PERCENT)
6472

    
6473
    offset = 0
6474
    size = device.size
6475
    last_output = 0
6476
    start_time = time.time()
6477

    
6478
    while offset < size:
6479
      wipe_size = min(wipe_chunk_size, size - offset)
6480
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6481
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6482
                   (idx, offset, wipe_size))
6483
      now = time.time()
6484
      offset += wipe_size
6485
      if now - last_output >= 60:
6486
        eta = _CalcEta(now - start_time, offset, size)
6487
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6488
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6489
        last_output = now
6490

    
6491

    
6492
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6493
  """Create all disks for an instance.
6494

6495
  This abstracts away some work from AddInstance.
6496

6497
  @type lu: L{LogicalUnit}
6498
  @param lu: the logical unit on whose behalf we execute
6499
  @type instance: L{objects.Instance}
6500
  @param instance: the instance whose disks we should create
6501
  @type to_skip: list
6502
  @param to_skip: list of indices to skip
6503
  @type target_node: string
6504
  @param target_node: if passed, overrides the target node for creation
6505
  @rtype: boolean
6506
  @return: the success of the creation
6507

6508
  """
6509
  info = _GetInstanceInfoText(instance)
6510
  if target_node is None:
6511
    pnode = instance.primary_node
6512
    all_nodes = instance.all_nodes
6513
  else:
6514
    pnode = target_node
6515
    all_nodes = [pnode]
6516

    
6517
  if instance.disk_template == constants.DT_FILE:
6518
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6519
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6520

    
6521
    result.Raise("Failed to create directory '%s' on"
6522
                 " node %s" % (file_storage_dir, pnode))
6523

    
6524
  # Note: this needs to be kept in sync with adding of disks in
6525
  # LUSetInstanceParams
6526
  for idx, device in enumerate(instance.disks):
6527
    if to_skip and idx in to_skip:
6528
      continue
6529
    logging.info("Creating volume %s for instance %s",
6530
                 device.iv_name, instance.name)
6531
    #HARDCODE
6532
    for node in all_nodes:
6533
      f_create = node == pnode
6534
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6535

    
6536

    
6537
def _RemoveDisks(lu, instance, target_node=None):
6538
  """Remove all disks for an instance.
6539

6540
  This abstracts away some work from `AddInstance()` and
6541
  `RemoveInstance()`. Note that in case some of the devices couldn't
6542
  be removed, the removal will continue with the other ones (compare
6543
  with `_CreateDisks()`).
6544

6545
  @type lu: L{LogicalUnit}
6546
  @param lu: the logical unit on whose behalf we execute
6547
  @type instance: L{objects.Instance}
6548
  @param instance: the instance whose disks we should remove
6549
  @type target_node: string
6550
  @param target_node: used to override the node on which to remove the disks
6551
  @rtype: boolean
6552
  @return: the success of the removal
6553

6554
  """
6555
  logging.info("Removing block devices for instance %s", instance.name)
6556

    
6557
  all_result = True
6558
  for device in instance.disks:
6559
    if target_node:
6560
      edata = [(target_node, device)]
6561
    else:
6562
      edata = device.ComputeNodeTree(instance.primary_node)
6563
    for node, disk in edata:
6564
      lu.cfg.SetDiskID(disk, node)
6565
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6566
      if msg:
6567
        lu.LogWarning("Could not remove block device %s on node %s,"
6568
                      " continuing anyway: %s", device.iv_name, node, msg)
6569
        all_result = False
6570

    
6571
  if instance.disk_template == constants.DT_FILE:
6572
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6573
    if target_node:
6574
      tgt = target_node
6575
    else:
6576
      tgt = instance.primary_node
6577
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6578
    if result.fail_msg:
6579
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6580
                    file_storage_dir, instance.primary_node, result.fail_msg)
6581
      all_result = False
6582

    
6583
  return all_result
6584

    
6585

    
6586
def _ComputeDiskSize(disk_template, disks):
6587
  """Compute disk size requirements in the volume group
6588

6589
  """
6590
  # Required free disk space as a function of disk and swap space
6591
  req_size_dict = {
6592
    constants.DT_DISKLESS: None,
6593
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6594
    # 128 MB are added for drbd metadata for each disk
6595
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6596
    constants.DT_FILE: None,
6597
  }
6598

    
6599
  if disk_template not in req_size_dict:
6600
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6601
                                 " is unknown" %  disk_template)
6602

    
6603
  return req_size_dict[disk_template]
6604

    
6605

    
6606
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6607
  """Hypervisor parameter validation.
6608

6609
  This function abstract the hypervisor parameter validation to be
6610
  used in both instance create and instance modify.
6611

6612
  @type lu: L{LogicalUnit}
6613
  @param lu: the logical unit for which we check
6614
  @type nodenames: list
6615
  @param nodenames: the list of nodes on which we should check
6616
  @type hvname: string
6617
  @param hvname: the name of the hypervisor we should use
6618
  @type hvparams: dict
6619
  @param hvparams: the parameters which we need to check
6620
  @raise errors.OpPrereqError: if the parameters are not valid
6621

6622
  """
6623
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6624
                                                  hvname,
6625
                                                  hvparams)
6626
  for node in nodenames:
6627
    info = hvinfo[node]
6628
    if info.offline:
6629
      continue
6630
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6631

    
6632

    
6633
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6634
  """OS parameters validation.
6635

6636
  @type lu: L{LogicalUnit}
6637
  @param lu: the logical unit for which we check
6638
  @type required: boolean
6639
  @param required: whether the validation should fail if the OS is not
6640
      found
6641
  @type nodenames: list
6642
  @param nodenames: the list of nodes on which we should check
6643
  @type osname: string
6644
  @param osname: the name of the hypervisor we should use
6645
  @type osparams: dict
6646
  @param osparams: the parameters which we need to check
6647
  @raise errors.OpPrereqError: if the parameters are not valid
6648

6649
  """
6650
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6651
                                   [constants.OS_VALIDATE_PARAMETERS],
6652
                                   osparams)
6653
  for node, nres in result.items():
6654
    # we don't check for offline cases since this should be run only
6655
    # against the master node and/or an instance's nodes
6656
    nres.Raise("OS Parameters validation failed on node %s" % node)
6657
    if not nres.payload:
6658
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6659
                 osname, node)
6660

    
6661

    
6662
class LUCreateInstance(LogicalUnit):
6663
  """Create an instance.
6664

6665
  """
6666
  HPATH = "instance-add"
6667
  HTYPE = constants.HTYPE_INSTANCE
6668
  _OP_PARAMS = [
6669
    _PInstanceName,
6670
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6671
    ("start", True, ht.TBool),
6672
    ("wait_for_sync", True, ht.TBool),
6673
    ("ip_check", True, ht.TBool),
6674
    ("name_check", True, ht.TBool),
6675
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6676
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6677
    ("hvparams", ht.EmptyDict, ht.TDict),
6678
    ("beparams", ht.EmptyDict, ht.TDict),
6679
    ("osparams", ht.EmptyDict, ht.TDict),
6680
    ("no_install", None, ht.TMaybeBool),
6681
    ("os_type", None, ht.TMaybeString),
6682
    ("force_variant", False, ht.TBool),
6683
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6684
    ("source_x509_ca", None, ht.TMaybeString),
6685
    ("source_instance_name", None, ht.TMaybeString),
6686
    ("src_node", None, ht.TMaybeString),
6687
    ("src_path", None, ht.TMaybeString),
6688
    ("pnode", None, ht.TMaybeString),
6689
    ("snode", None, ht.TMaybeString),
6690
    ("iallocator", None, ht.TMaybeString),
6691
    ("hypervisor", None, ht.TMaybeString),
6692
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6693
    ("identify_defaults", False, ht.TBool),
6694
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6695
    ("file_storage_dir", None, ht.TMaybeString),
6696
    ]
6697
  REQ_BGL = False
6698

    
6699
  def CheckArguments(self):
6700
    """Check arguments.
6701

6702
    """
6703
    # do not require name_check to ease forward/backward compatibility
6704
    # for tools
6705
    if self.op.no_install and self.op.start:
6706
      self.LogInfo("No-installation mode selected, disabling startup")
6707
      self.op.start = False
6708
    # validate/normalize the instance name
6709
    self.op.instance_name = \
6710
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6711

    
6712
    if self.op.ip_check and not self.op.name_check:
6713
      # TODO: make the ip check more flexible and not depend on the name check
6714
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6715
                                 errors.ECODE_INVAL)
6716

    
6717
    # check nics' parameter names
6718
    for nic in self.op.nics:
6719
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6720

    
6721
    # check disks. parameter names and consistent adopt/no-adopt strategy
6722
    has_adopt = has_no_adopt = False
6723
    for disk in self.op.disks:
6724
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6725
      if "adopt" in disk:
6726
        has_adopt = True
6727
      else:
6728
        has_no_adopt = True
6729
    if has_adopt and has_no_adopt:
6730
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6731
                                 errors.ECODE_INVAL)
6732
    if has_adopt:
6733
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6734
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6735
                                   " '%s' disk template" %
6736
                                   self.op.disk_template,
6737
                                   errors.ECODE_INVAL)
6738
      if self.op.iallocator is not None:
6739
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6740
                                   " iallocator script", errors.ECODE_INVAL)
6741
      if self.op.mode == constants.INSTANCE_IMPORT:
6742
        raise errors.OpPrereqError("Disk adoption not allowed for"
6743
                                   " instance import", errors.ECODE_INVAL)
6744

    
6745
    self.adopt_disks = has_adopt
6746

    
6747
    # instance name verification
6748
    if self.op.name_check:
6749
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6750
      self.op.instance_name = self.hostname1.name
6751
      # used in CheckPrereq for ip ping check
6752
      self.check_ip = self.hostname1.ip
6753
    else:
6754
      self.check_ip = None
6755

    
6756
    # file storage checks
6757
    if (self.op.file_driver and
6758
        not self.op.file_driver in constants.FILE_DRIVER):
6759
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6760
                                 self.op.file_driver, errors.ECODE_INVAL)
6761

    
6762
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6763
      raise errors.OpPrereqError("File storage directory path not absolute",
6764
                                 errors.ECODE_INVAL)
6765

    
6766
    ### Node/iallocator related checks
6767
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6768

    
6769
    if self.op.pnode is not None:
6770
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6771
        if self.op.snode is None:
6772
          raise errors.OpPrereqError("The networked disk templates need"
6773
                                     " a mirror node", errors.ECODE_INVAL)
6774
      elif self.op.snode:
6775
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6776
                        " template")
6777
        self.op.snode = None
6778

    
6779
    self._cds = _GetClusterDomainSecret()
6780

    
6781
    if self.op.mode == constants.INSTANCE_IMPORT:
6782
      # On import force_variant must be True, because if we forced it at
6783
      # initial install, our only chance when importing it back is that it
6784
      # works again!
6785
      self.op.force_variant = True
6786

    
6787
      if self.op.no_install:
6788
        self.LogInfo("No-installation mode has no effect during import")
6789

    
6790
    elif self.op.mode == constants.INSTANCE_CREATE:
6791
      if self.op.os_type is None:
6792
        raise errors.OpPrereqError("No guest OS specified",
6793
                                   errors.ECODE_INVAL)
6794
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6795
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6796
                                   " installation" % self.op.os_type,
6797
                                   errors.ECODE_STATE)
6798
      if self.op.disk_template is None:
6799
        raise errors.OpPrereqError("No disk template specified",
6800
                                   errors.ECODE_INVAL)
6801

    
6802
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6803
      # Check handshake to ensure both clusters have the same domain secret
6804
      src_handshake = self.op.source_handshake
6805
      if not src_handshake:
6806
        raise errors.OpPrereqError("Missing source handshake",
6807
                                   errors.ECODE_INVAL)
6808

    
6809
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6810
                                                           src_handshake)
6811
      if errmsg:
6812
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6813
                                   errors.ECODE_INVAL)
6814

    
6815
      # Load and check source CA
6816
      self.source_x509_ca_pem = self.op.source_x509_ca
6817
      if not self.source_x509_ca_pem:
6818
        raise errors.OpPrereqError("Missing source X509 CA",
6819
                                   errors.ECODE_INVAL)
6820

    
6821
      try:
6822
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6823
                                                    self._cds)
6824
      except OpenSSL.crypto.Error, err:
6825
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6826
                                   (err, ), errors.ECODE_INVAL)
6827

    
6828
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6829
      if errcode is not None:
6830
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6831
                                   errors.ECODE_INVAL)
6832

    
6833
      self.source_x509_ca = cert
6834

    
6835
      src_instance_name = self.op.source_instance_name
6836
      if not src_instance_name:
6837
        raise errors.OpPrereqError("Missing source instance name",
6838
                                   errors.ECODE_INVAL)
6839

    
6840
      self.source_instance_name = \
6841
          netutils.GetHostname(name=src_instance_name).name
6842

    
6843
    else:
6844
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6845
                                 self.op.mode, errors.ECODE_INVAL)
6846

    
6847
  def ExpandNames(self):
6848
    """ExpandNames for CreateInstance.
6849

6850
    Figure out the right locks for instance creation.
6851

6852
    """
6853
    self.needed_locks = {}
6854

    
6855
    instance_name = self.op.instance_name
6856
    # this is just a preventive check, but someone might still add this
6857
    # instance in the meantime, and creation will fail at lock-add time
6858
    if instance_name in self.cfg.GetInstanceList():
6859
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6860
                                 instance_name, errors.ECODE_EXISTS)
6861

    
6862
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6863

    
6864
    if self.op.iallocator:
6865
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6866
    else:
6867
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6868
      nodelist = [self.op.pnode]
6869
      if self.op.snode is not None:
6870
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6871
        nodelist.append(self.op.snode)
6872
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6873

    
6874
    # in case of import lock the source node too
6875
    if self.op.mode == constants.INSTANCE_IMPORT:
6876
      src_node = self.op.src_node
6877
      src_path = self.op.src_path
6878

    
6879
      if src_path is None:
6880
        self.op.src_path = src_path = self.op.instance_name
6881

    
6882
      if src_node is None:
6883
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6884
        self.op.src_node = None
6885
        if os.path.isabs(src_path):
6886
          raise errors.OpPrereqError("Importing an instance from an absolute"
6887
                                     " path requires a source node option.",
6888
                                     errors.ECODE_INVAL)
6889
      else:
6890
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6891
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6892
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6893
        if not os.path.isabs(src_path):
6894
          self.op.src_path = src_path = \
6895
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6896

    
6897
  def _RunAllocator(self):
6898
    """Run the allocator based on input opcode.
6899

6900
    """
6901
    nics = [n.ToDict() for n in self.nics]
6902
    ial = IAllocator(self.cfg, self.rpc,
6903
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6904
                     name=self.op.instance_name,
6905
                     disk_template=self.op.disk_template,
6906
                     tags=[],
6907
                     os=self.op.os_type,
6908
                     vcpus=self.be_full[constants.BE_VCPUS],
6909
                     mem_size=self.be_full[constants.BE_MEMORY],
6910
                     disks=self.disks,
6911
                     nics=nics,
6912
                     hypervisor=self.op.hypervisor,
6913
                     )
6914

    
6915
    ial.Run(self.op.iallocator)
6916

    
6917
    if not ial.success:
6918
      raise errors.OpPrereqError("Can't compute nodes using"
6919
                                 " iallocator '%s': %s" %
6920
                                 (self.op.iallocator, ial.info),
6921
                                 errors.ECODE_NORES)
6922
    if len(ial.result) != ial.required_nodes:
6923
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6924
                                 " of nodes (%s), required %s" %
6925
                                 (self.op.iallocator, len(ial.result),
6926
                                  ial.required_nodes), errors.ECODE_FAULT)
6927
    self.op.pnode = ial.result[0]
6928
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6929
                 self.op.instance_name, self.op.iallocator,
6930
                 utils.CommaJoin(ial.result))
6931
    if ial.required_nodes == 2:
6932
      self.op.snode = ial.result[1]
6933

    
6934
  def BuildHooksEnv(self):
6935
    """Build hooks env.
6936

6937
    This runs on master, primary and secondary nodes of the instance.
6938

6939
    """
6940
    env = {
6941
      "ADD_MODE": self.op.mode,
6942
      }
6943
    if self.op.mode == constants.INSTANCE_IMPORT:
6944
      env["SRC_NODE"] = self.op.src_node
6945
      env["SRC_PATH"] = self.op.src_path
6946
      env["SRC_IMAGES"] = self.src_images
6947

    
6948
    env.update(_BuildInstanceHookEnv(
6949
      name=self.op.instance_name,
6950
      primary_node=self.op.pnode,
6951
      secondary_nodes=self.secondaries,
6952
      status=self.op.start,
6953
      os_type=self.op.os_type,
6954
      memory=self.be_full[constants.BE_MEMORY],
6955
      vcpus=self.be_full[constants.BE_VCPUS],
6956
      nics=_NICListToTuple(self, self.nics),
6957
      disk_template=self.op.disk_template,
6958
      disks=[(d["size"], d["mode"]) for d in self.disks],
6959
      bep=self.be_full,
6960
      hvp=self.hv_full,
6961
      hypervisor_name=self.op.hypervisor,
6962
    ))
6963

    
6964
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6965
          self.secondaries)
6966
    return env, nl, nl
6967

    
6968
  def _ReadExportInfo(self):
6969
    """Reads the export information from disk.
6970

6971
    It will override the opcode source node and path with the actual
6972
    information, if these two were not specified before.
6973

6974
    @return: the export information
6975

6976
    """
6977
    assert self.op.mode == constants.INSTANCE_IMPORT
6978

    
6979
    src_node = self.op.src_node
6980
    src_path = self.op.src_path
6981

    
6982
    if src_node is None:
6983
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6984
      exp_list = self.rpc.call_export_list(locked_nodes)
6985
      found = False
6986
      for node in exp_list:
6987
        if exp_list[node].fail_msg:
6988
          continue
6989
        if src_path in exp_list[node].payload:
6990
          found = True
6991
          self.op.src_node = src_node = node
6992
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6993
                                                       src_path)
6994
          break
6995
      if not found:
6996
        raise errors.OpPrereqError("No export found for relative path %s" %
6997
                                    src_path, errors.ECODE_INVAL)
6998

    
6999
    _CheckNodeOnline(self, src_node)
7000
    result = self.rpc.call_export_info(src_node, src_path)
7001
    result.Raise("No export or invalid export found in dir %s" % src_path)
7002

    
7003
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7004
    if not export_info.has_section(constants.INISECT_EXP):
7005
      raise errors.ProgrammerError("Corrupted export config",
7006
                                   errors.ECODE_ENVIRON)
7007

    
7008
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7009
    if (int(ei_version) != constants.EXPORT_VERSION):
7010
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7011
                                 (ei_version, constants.EXPORT_VERSION),
7012
                                 errors.ECODE_ENVIRON)
7013
    return export_info
7014

    
7015
  def _ReadExportParams(self, einfo):
7016
    """Use export parameters as defaults.
7017

7018
    In case the opcode doesn't specify (as in override) some instance
7019
    parameters, then try to use them from the export information, if
7020
    that declares them.
7021

7022
    """
7023
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7024

    
7025
    if self.op.disk_template is None:
7026
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7027
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7028
                                          "disk_template")
7029
      else:
7030
        raise errors.OpPrereqError("No disk template specified and the export"
7031
                                   " is missing the disk_template information",
7032
                                   errors.ECODE_INVAL)
7033

    
7034
    if not self.op.disks:
7035
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7036
        disks = []
7037
        # TODO: import the disk iv_name too
7038
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7039
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7040
          disks.append({"size": disk_sz})
7041
        self.op.disks = disks
7042
      else:
7043
        raise errors.OpPrereqError("No disk info specified and the export"
7044
                                   " is missing the disk information",
7045
                                   errors.ECODE_INVAL)
7046

    
7047
    if (not self.op.nics and
7048
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7049
      nics = []
7050
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7051
        ndict = {}
7052
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7053
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7054
          ndict[name] = v
7055
        nics.append(ndict)
7056
      self.op.nics = nics
7057

    
7058
    if (self.op.hypervisor is None and
7059
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7060
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7061
    if einfo.has_section(constants.INISECT_HYP):
7062
      # use the export parameters but do not override the ones
7063
      # specified by the user
7064
      for name, value in einfo.items(constants.INISECT_HYP):
7065
        if name not in self.op.hvparams:
7066
          self.op.hvparams[name] = value
7067

    
7068
    if einfo.has_section(constants.INISECT_BEP):
7069
      # use the parameters, without overriding
7070
      for name, value in einfo.items(constants.INISECT_BEP):
7071
        if name not in self.op.beparams:
7072
          self.op.beparams[name] = value
7073
    else:
7074
      # try to read the parameters old style, from the main section
7075
      for name in constants.BES_PARAMETERS:
7076
        if (name not in self.op.beparams and
7077
            einfo.has_option(constants.INISECT_INS, name)):
7078
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7079

    
7080
    if einfo.has_section(constants.INISECT_OSP):
7081
      # use the parameters, without overriding
7082
      for name, value in einfo.items(constants.INISECT_OSP):
7083
        if name not in self.op.osparams:
7084
          self.op.osparams[name] = value
7085

    
7086
  def _RevertToDefaults(self, cluster):
7087
    """Revert the instance parameters to the default values.
7088

7089
    """
7090
    # hvparams
7091
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7092
    for name in self.op.hvparams.keys():
7093
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7094
        del self.op.hvparams[name]
7095
    # beparams
7096
    be_defs = cluster.SimpleFillBE({})
7097
    for name in self.op.beparams.keys():
7098
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7099
        del self.op.beparams[name]
7100
    # nic params
7101
    nic_defs = cluster.SimpleFillNIC({})
7102
    for nic in self.op.nics:
7103
      for name in constants.NICS_PARAMETERS:
7104
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7105
          del nic[name]
7106
    # osparams
7107
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7108
    for name in self.op.osparams.keys():
7109
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7110
        del self.op.osparams[name]
7111

    
7112
  def CheckPrereq(self):
7113
    """Check prerequisites.
7114

7115
    """
7116
    if self.op.mode == constants.INSTANCE_IMPORT:
7117
      export_info = self._ReadExportInfo()
7118
      self._ReadExportParams(export_info)
7119

    
7120
    _CheckDiskTemplate(self.op.disk_template)
7121

    
7122
    if (not self.cfg.GetVGName() and
7123
        self.op.disk_template not in constants.DTS_NOT_LVM):
7124
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7125
                                 " instances", errors.ECODE_STATE)
7126

    
7127
    if self.op.hypervisor is None:
7128
      self.op.hypervisor = self.cfg.GetHypervisorType()
7129

    
7130
    cluster = self.cfg.GetClusterInfo()
7131
    enabled_hvs = cluster.enabled_hypervisors
7132
    if self.op.hypervisor not in enabled_hvs:
7133
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7134
                                 " cluster (%s)" % (self.op.hypervisor,
7135
                                  ",".join(enabled_hvs)),
7136
                                 errors.ECODE_STATE)
7137

    
7138
    # check hypervisor parameter syntax (locally)
7139
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7140
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7141
                                      self.op.hvparams)
7142
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7143
    hv_type.CheckParameterSyntax(filled_hvp)
7144
    self.hv_full = filled_hvp
7145
    # check that we don't specify global parameters on an instance
7146
    _CheckGlobalHvParams(self.op.hvparams)
7147

    
7148
    # fill and remember the beparams dict
7149
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7150
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7151

    
7152
    # build os parameters
7153
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7154

    
7155
    # now that hvp/bep are in final format, let's reset to defaults,
7156
    # if told to do so
7157
    if self.op.identify_defaults:
7158
      self._RevertToDefaults(cluster)
7159

    
7160
    # NIC buildup
7161
    self.nics = []
7162
    for idx, nic in enumerate(self.op.nics):
7163
      nic_mode_req = nic.get("mode", None)
7164
      nic_mode = nic_mode_req
7165
      if nic_mode is None:
7166
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7167

    
7168
      # in routed mode, for the first nic, the default ip is 'auto'
7169
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7170
        default_ip_mode = constants.VALUE_AUTO
7171
      else:
7172
        default_ip_mode = constants.VALUE_NONE
7173

    
7174
      # ip validity checks
7175
      ip = nic.get("ip", default_ip_mode)
7176
      if ip is None or ip.lower() == constants.VALUE_NONE:
7177
        nic_ip = None
7178
      elif ip.lower() == constants.VALUE_AUTO:
7179
        if not self.op.name_check:
7180
          raise errors.OpPrereqError("IP address set to auto but name checks"
7181
                                     " have been skipped",
7182
                                     errors.ECODE_INVAL)
7183
        nic_ip = self.hostname1.ip
7184
      else:
7185
        if not netutils.IPAddress.IsValid(ip):
7186
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7187
                                     errors.ECODE_INVAL)
7188
        nic_ip = ip
7189

    
7190
      # TODO: check the ip address for uniqueness
7191
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7192
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7193
                                   errors.ECODE_INVAL)
7194

    
7195
      # MAC address verification
7196
      mac = nic.get("mac", constants.VALUE_AUTO)
7197
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7198
        mac = utils.NormalizeAndValidateMac(mac)
7199

    
7200
        try:
7201
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7202
        except errors.ReservationError:
7203
          raise errors.OpPrereqError("MAC address %s already in use"
7204
                                     " in cluster" % mac,
7205
                                     errors.ECODE_NOTUNIQUE)
7206

    
7207
      # bridge verification
7208
      bridge = nic.get("bridge", None)
7209
      link = nic.get("link", None)
7210
      if bridge and link:
7211
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7212
                                   " at the same time", errors.ECODE_INVAL)
7213
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7214
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7215
                                   errors.ECODE_INVAL)
7216
      elif bridge:
7217
        link = bridge
7218

    
7219
      nicparams = {}
7220
      if nic_mode_req:
7221
        nicparams[constants.NIC_MODE] = nic_mode_req
7222
      if link:
7223
        nicparams[constants.NIC_LINK] = link
7224

    
7225
      check_params = cluster.SimpleFillNIC(nicparams)
7226
      objects.NIC.CheckParameterSyntax(check_params)
7227
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7228

    
7229
    # disk checks/pre-build
7230
    self.disks = []
7231
    for disk in self.op.disks:
7232
      mode = disk.get("mode", constants.DISK_RDWR)
7233
      if mode not in constants.DISK_ACCESS_SET:
7234
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7235
                                   mode, errors.ECODE_INVAL)
7236
      size = disk.get("size", None)
7237
      if size is None:
7238
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7239
      try:
7240
        size = int(size)
7241
      except (TypeError, ValueError):
7242
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7243
                                   errors.ECODE_INVAL)
7244
      new_disk = {"size": size, "mode": mode}
7245
      if "adopt" in disk:
7246
        new_disk["adopt"] = disk["adopt"]
7247
      self.disks.append(new_disk)
7248

    
7249
    if self.op.mode == constants.INSTANCE_IMPORT:
7250

    
7251
      # Check that the new instance doesn't have less disks than the export
7252
      instance_disks = len(self.disks)
7253
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7254
      if instance_disks < export_disks:
7255
        raise errors.OpPrereqError("Not enough disks to import."
7256
                                   " (instance: %d, export: %d)" %
7257
                                   (instance_disks, export_disks),
7258
                                   errors.ECODE_INVAL)
7259

    
7260
      disk_images = []
7261
      for idx in range(export_disks):
7262
        option = 'disk%d_dump' % idx
7263
        if export_info.has_option(constants.INISECT_INS, option):
7264
          # FIXME: are the old os-es, disk sizes, etc. useful?
7265
          export_name = export_info.get(constants.INISECT_INS, option)
7266
          image = utils.PathJoin(self.op.src_path, export_name)
7267
          disk_images.append(image)
7268
        else:
7269
          disk_images.append(False)
7270

    
7271
      self.src_images = disk_images
7272

    
7273
      old_name = export_info.get(constants.INISECT_INS, 'name')
7274
      try:
7275
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7276
      except (TypeError, ValueError), err:
7277
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7278
                                   " an integer: %s" % str(err),
7279
                                   errors.ECODE_STATE)
7280
      if self.op.instance_name == old_name:
7281
        for idx, nic in enumerate(self.nics):
7282
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7283
            nic_mac_ini = 'nic%d_mac' % idx
7284
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7285

    
7286
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7287

    
7288
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7289
    if self.op.ip_check:
7290
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7291
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7292
                                   (self.check_ip, self.op.instance_name),
7293
                                   errors.ECODE_NOTUNIQUE)
7294

    
7295
    #### mac address generation
7296
    # By generating here the mac address both the allocator and the hooks get
7297
    # the real final mac address rather than the 'auto' or 'generate' value.
7298
    # There is a race condition between the generation and the instance object
7299
    # creation, which means that we know the mac is valid now, but we're not
7300
    # sure it will be when we actually add the instance. If things go bad
7301
    # adding the instance will abort because of a duplicate mac, and the
7302
    # creation job will fail.
7303
    for nic in self.nics:
7304
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7305
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7306

    
7307
    #### allocator run
7308

    
7309
    if self.op.iallocator is not None:
7310
      self._RunAllocator()
7311

    
7312
    #### node related checks
7313

    
7314
    # check primary node
7315
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7316
    assert self.pnode is not None, \
7317
      "Cannot retrieve locked node %s" % self.op.pnode
7318
    if pnode.offline:
7319
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7320
                                 pnode.name, errors.ECODE_STATE)
7321
    if pnode.drained:
7322
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7323
                                 pnode.name, errors.ECODE_STATE)
7324

    
7325
    self.secondaries = []
7326

    
7327
    # mirror node verification
7328
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7329
      if self.op.snode == pnode.name:
7330
        raise errors.OpPrereqError("The secondary node cannot be the"
7331
                                   " primary node.", errors.ECODE_INVAL)
7332
      _CheckNodeOnline(self, self.op.snode)
7333
      _CheckNodeNotDrained(self, self.op.snode)
7334
      self.secondaries.append(self.op.snode)
7335

    
7336
    nodenames = [pnode.name] + self.secondaries
7337

    
7338
    req_size = _ComputeDiskSize(self.op.disk_template,
7339
                                self.disks)
7340

    
7341
    # Check lv size requirements, if not adopting
7342
    if req_size is not None and not self.adopt_disks:
7343
      _CheckNodesFreeDisk(self, nodenames, req_size)
7344

    
7345
    if self.adopt_disks: # instead, we must check the adoption data
7346
      all_lvs = set([i["adopt"] for i in self.disks])
7347
      if len(all_lvs) != len(self.disks):
7348
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7349
                                   errors.ECODE_INVAL)
7350
      for lv_name in all_lvs:
7351
        try:
7352
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7353
        except errors.ReservationError:
7354
          raise errors.OpPrereqError("LV named %s used by another instance" %
7355
                                     lv_name, errors.ECODE_NOTUNIQUE)
7356

    
7357
      node_lvs = self.rpc.call_lv_list([pnode.name],
7358
                                       self.cfg.GetVGName())[pnode.name]
7359
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7360
      node_lvs = node_lvs.payload
7361
      delta = all_lvs.difference(node_lvs.keys())
7362
      if delta:
7363
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7364
                                   utils.CommaJoin(delta),
7365
                                   errors.ECODE_INVAL)
7366
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7367
      if online_lvs:
7368
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7369
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7370
                                   errors.ECODE_STATE)
7371
      # update the size of disk based on what is found
7372
      for dsk in self.disks:
7373
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7374

    
7375
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7376

    
7377
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7378
    # check OS parameters (remotely)
7379
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7380

    
7381
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7382

    
7383
    # memory check on primary node
7384
    if self.op.start:
7385
      _CheckNodeFreeMemory(self, self.pnode.name,
7386
                           "creating instance %s" % self.op.instance_name,
7387
                           self.be_full[constants.BE_MEMORY],
7388
                           self.op.hypervisor)
7389

    
7390
    self.dry_run_result = list(nodenames)
7391

    
7392
  def Exec(self, feedback_fn):
7393
    """Create and add the instance to the cluster.
7394

7395
    """
7396
    instance = self.op.instance_name
7397
    pnode_name = self.pnode.name
7398

    
7399
    ht_kind = self.op.hypervisor
7400
    if ht_kind in constants.HTS_REQ_PORT:
7401
      network_port = self.cfg.AllocatePort()
7402
    else:
7403
      network_port = None
7404

    
7405
    if constants.ENABLE_FILE_STORAGE:
7406
      # this is needed because os.path.join does not accept None arguments
7407
      if self.op.file_storage_dir is None:
7408
        string_file_storage_dir = ""
7409
      else:
7410
        string_file_storage_dir = self.op.file_storage_dir
7411

    
7412
      # build the full file storage dir path
7413
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7414
                                        string_file_storage_dir, instance)
7415
    else:
7416
      file_storage_dir = ""
7417

    
7418
    disks = _GenerateDiskTemplate(self,
7419
                                  self.op.disk_template,
7420
                                  instance, pnode_name,
7421
                                  self.secondaries,
7422
                                  self.disks,
7423
                                  file_storage_dir,
7424
                                  self.op.file_driver,
7425
                                  0)
7426

    
7427
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7428
                            primary_node=pnode_name,
7429
                            nics=self.nics, disks=disks,
7430
                            disk_template=self.op.disk_template,
7431
                            admin_up=False,
7432
                            network_port=network_port,
7433
                            beparams=self.op.beparams,
7434
                            hvparams=self.op.hvparams,
7435
                            hypervisor=self.op.hypervisor,
7436
                            osparams=self.op.osparams,
7437
                            )
7438

    
7439
    if self.adopt_disks:
7440
      # rename LVs to the newly-generated names; we need to construct
7441
      # 'fake' LV disks with the old data, plus the new unique_id
7442
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7443
      rename_to = []
7444
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7445
        rename_to.append(t_dsk.logical_id)
7446
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7447
        self.cfg.SetDiskID(t_dsk, pnode_name)
7448
      result = self.rpc.call_blockdev_rename(pnode_name,
7449
                                             zip(tmp_disks, rename_to))
7450
      result.Raise("Failed to rename adoped LVs")
7451
    else:
7452
      feedback_fn("* creating instance disks...")
7453
      try:
7454
        _CreateDisks(self, iobj)
7455
      except errors.OpExecError:
7456
        self.LogWarning("Device creation failed, reverting...")
7457
        try:
7458
          _RemoveDisks(self, iobj)
7459
        finally:
7460
          self.cfg.ReleaseDRBDMinors(instance)
7461
          raise
7462

    
7463
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7464
        feedback_fn("* wiping instance disks...")
7465
        try:
7466
          _WipeDisks(self, iobj)
7467
        except errors.OpExecError:
7468
          self.LogWarning("Device wiping failed, reverting...")
7469
          try:
7470
            _RemoveDisks(self, iobj)
7471
          finally:
7472
            self.cfg.ReleaseDRBDMinors(instance)
7473
            raise
7474

    
7475
    feedback_fn("adding instance %s to cluster config" % instance)
7476

    
7477
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7478

    
7479
    # Declare that we don't want to remove the instance lock anymore, as we've
7480
    # added the instance to the config
7481
    del self.remove_locks[locking.LEVEL_INSTANCE]
7482
    # Unlock all the nodes
7483
    if self.op.mode == constants.INSTANCE_IMPORT:
7484
      nodes_keep = [self.op.src_node]
7485
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7486
                       if node != self.op.src_node]
7487
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7488
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7489
    else:
7490
      self.context.glm.release(locking.LEVEL_NODE)
7491
      del self.acquired_locks[locking.LEVEL_NODE]
7492

    
7493
    if self.op.wait_for_sync:
7494
      disk_abort = not _WaitForSync(self, iobj)
7495
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7496
      # make sure the disks are not degraded (still sync-ing is ok)
7497
      time.sleep(15)
7498
      feedback_fn("* checking mirrors status")
7499
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7500
    else:
7501
      disk_abort = False
7502

    
7503
    if disk_abort:
7504
      _RemoveDisks(self, iobj)
7505
      self.cfg.RemoveInstance(iobj.name)
7506
      # Make sure the instance lock gets removed
7507
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7508
      raise errors.OpExecError("There are some degraded disks for"
7509
                               " this instance")
7510

    
7511
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7512
      if self.op.mode == constants.INSTANCE_CREATE:
7513
        if not self.op.no_install:
7514
          feedback_fn("* running the instance OS create scripts...")
7515
          # FIXME: pass debug option from opcode to backend
7516
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7517
                                                 self.op.debug_level)
7518
          result.Raise("Could not add os for instance %s"
7519
                       " on node %s" % (instance, pnode_name))
7520

    
7521
      elif self.op.mode == constants.INSTANCE_IMPORT:
7522
        feedback_fn("* running the instance OS import scripts...")
7523

    
7524
        transfers = []
7525

    
7526
        for idx, image in enumerate(self.src_images):
7527
          if not image:
7528
            continue
7529

    
7530
          # FIXME: pass debug option from opcode to backend
7531
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7532
                                             constants.IEIO_FILE, (image, ),
7533
                                             constants.IEIO_SCRIPT,
7534
                                             (iobj.disks[idx], idx),
7535
                                             None)
7536
          transfers.append(dt)
7537

    
7538
        import_result = \
7539
          masterd.instance.TransferInstanceData(self, feedback_fn,
7540
                                                self.op.src_node, pnode_name,
7541
                                                self.pnode.secondary_ip,
7542
                                                iobj, transfers)
7543
        if not compat.all(import_result):
7544
          self.LogWarning("Some disks for instance %s on node %s were not"
7545
                          " imported successfully" % (instance, pnode_name))
7546

    
7547
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7548
        feedback_fn("* preparing remote import...")
7549
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7550
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7551

    
7552
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7553
                                                     self.source_x509_ca,
7554
                                                     self._cds, timeouts)
7555
        if not compat.all(disk_results):
7556
          # TODO: Should the instance still be started, even if some disks
7557
          # failed to import (valid for local imports, too)?
7558
          self.LogWarning("Some disks for instance %s on node %s were not"
7559
                          " imported successfully" % (instance, pnode_name))
7560

    
7561
        # Run rename script on newly imported instance
7562
        assert iobj.name == instance
7563
        feedback_fn("Running rename script for %s" % instance)
7564
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7565
                                                   self.source_instance_name,
7566
                                                   self.op.debug_level)
7567
        if result.fail_msg:
7568
          self.LogWarning("Failed to run rename script for %s on node"
7569
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7570

    
7571
      else:
7572
        # also checked in the prereq part
7573
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7574
                                     % self.op.mode)
7575

    
7576
    if self.op.start:
7577
      iobj.admin_up = True
7578
      self.cfg.Update(iobj, feedback_fn)
7579
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7580
      feedback_fn("* starting instance...")
7581
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7582
      result.Raise("Could not start instance")
7583

    
7584
    return list(iobj.all_nodes)
7585

    
7586

    
7587
class LUConnectConsole(NoHooksLU):
7588
  """Connect to an instance's console.
7589

7590
  This is somewhat special in that it returns the command line that
7591
  you need to run on the master node in order to connect to the
7592
  console.
7593

7594
  """
7595
  _OP_PARAMS = [
7596
    _PInstanceName
7597
    ]
7598
  REQ_BGL = False
7599

    
7600
  def ExpandNames(self):
7601
    self._ExpandAndLockInstance()
7602

    
7603
  def CheckPrereq(self):
7604
    """Check prerequisites.
7605

7606
    This checks that the instance is in the cluster.
7607

7608
    """
7609
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7610
    assert self.instance is not None, \
7611
      "Cannot retrieve locked instance %s" % self.op.instance_name
7612
    _CheckNodeOnline(self, self.instance.primary_node)
7613

    
7614
  def Exec(self, feedback_fn):
7615
    """Connect to the console of an instance
7616

7617
    """
7618
    instance = self.instance
7619
    node = instance.primary_node
7620

    
7621
    node_insts = self.rpc.call_instance_list([node],
7622
                                             [instance.hypervisor])[node]
7623
    node_insts.Raise("Can't get node information from %s" % node)
7624

    
7625
    if instance.name not in node_insts.payload:
7626
      if instance.admin_up:
7627
        state = "ERROR_down"
7628
      else:
7629
        state = "ADMIN_down"
7630
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7631
                               (instance.name, state))
7632

    
7633
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7634

    
7635
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7636
    cluster = self.cfg.GetClusterInfo()
7637
    # beparams and hvparams are passed separately, to avoid editing the
7638
    # instance and then saving the defaults in the instance itself.
7639
    hvparams = cluster.FillHV(instance)
7640
    beparams = cluster.FillBE(instance)
7641
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7642

    
7643
    # build ssh cmdline
7644
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7645

    
7646

    
7647
class LUReplaceDisks(LogicalUnit):
7648
  """Replace the disks of an instance.
7649

7650
  """
7651
  HPATH = "mirrors-replace"
7652
  HTYPE = constants.HTYPE_INSTANCE
7653
  _OP_PARAMS = [
7654
    _PInstanceName,
7655
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7656
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7657
    ("remote_node", None, ht.TMaybeString),
7658
    ("iallocator", None, ht.TMaybeString),
7659
    ("early_release", False, ht.TBool),
7660
    ]
7661
  REQ_BGL = False
7662

    
7663
  def CheckArguments(self):
7664
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7665
                                  self.op.iallocator)
7666

    
7667
  def ExpandNames(self):
7668
    self._ExpandAndLockInstance()
7669

    
7670
    if self.op.iallocator is not None:
7671
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7672

    
7673
    elif self.op.remote_node is not None:
7674
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7675
      self.op.remote_node = remote_node
7676

    
7677
      # Warning: do not remove the locking of the new secondary here
7678
      # unless DRBD8.AddChildren is changed to work in parallel;
7679
      # currently it doesn't since parallel invocations of
7680
      # FindUnusedMinor will conflict
7681
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7682
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7683

    
7684
    else:
7685
      self.needed_locks[locking.LEVEL_NODE] = []
7686
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7687

    
7688
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7689
                                   self.op.iallocator, self.op.remote_node,
7690
                                   self.op.disks, False, self.op.early_release)
7691

    
7692
    self.tasklets = [self.replacer]
7693

    
7694
  def DeclareLocks(self, level):
7695
    # If we're not already locking all nodes in the set we have to declare the
7696
    # instance's primary/secondary nodes.
7697
    if (level == locking.LEVEL_NODE and
7698
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7699
      self._LockInstancesNodes()
7700

    
7701
  def BuildHooksEnv(self):
7702
    """Build hooks env.
7703

7704
    This runs on the master, the primary and all the secondaries.
7705

7706
    """
7707
    instance = self.replacer.instance
7708
    env = {
7709
      "MODE": self.op.mode,
7710
      "NEW_SECONDARY": self.op.remote_node,
7711
      "OLD_SECONDARY": instance.secondary_nodes[0],
7712
      }
7713
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7714
    nl = [
7715
      self.cfg.GetMasterNode(),
7716
      instance.primary_node,
7717
      ]
7718
    if self.op.remote_node is not None:
7719
      nl.append(self.op.remote_node)
7720
    return env, nl, nl
7721

    
7722

    
7723
class TLReplaceDisks(Tasklet):
7724
  """Replaces disks for an instance.
7725

7726
  Note: Locking is not within the scope of this class.
7727

7728
  """
7729
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7730
               disks, delay_iallocator, early_release):
7731
    """Initializes this class.
7732

7733
    """
7734
    Tasklet.__init__(self, lu)
7735

    
7736
    # Parameters
7737
    self.instance_name = instance_name
7738
    self.mode = mode
7739
    self.iallocator_name = iallocator_name
7740
    self.remote_node = remote_node
7741
    self.disks = disks
7742
    self.delay_iallocator = delay_iallocator
7743
    self.early_release = early_release
7744

    
7745
    # Runtime data
7746
    self.instance = None
7747
    self.new_node = None
7748
    self.target_node = None
7749
    self.other_node = None
7750
    self.remote_node_info = None
7751
    self.node_secondary_ip = None
7752

    
7753
  @staticmethod
7754
  def CheckArguments(mode, remote_node, iallocator):
7755
    """Helper function for users of this class.
7756

7757
    """
7758
    # check for valid parameter combination
7759
    if mode == constants.REPLACE_DISK_CHG:
7760
      if remote_node is None and iallocator is None:
7761
        raise errors.OpPrereqError("When changing the secondary either an"
7762
                                   " iallocator script must be used or the"
7763
                                   " new node given", errors.ECODE_INVAL)
7764

    
7765
      if remote_node is not None and iallocator is not None:
7766
        raise errors.OpPrereqError("Give either the iallocator or the new"
7767
                                   " secondary, not both", errors.ECODE_INVAL)
7768

    
7769
    elif remote_node is not None or iallocator is not None:
7770
      # Not replacing the secondary
7771
      raise errors.OpPrereqError("The iallocator and new node options can"
7772
                                 " only be used when changing the"
7773
                                 " secondary node", errors.ECODE_INVAL)
7774

    
7775
  @staticmethod
7776
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7777
    """Compute a new secondary node using an IAllocator.
7778

7779
    """
7780
    ial = IAllocator(lu.cfg, lu.rpc,
7781
                     mode=constants.IALLOCATOR_MODE_RELOC,
7782
                     name=instance_name,
7783
                     relocate_from=relocate_from)
7784

    
7785
    ial.Run(iallocator_name)
7786

    
7787
    if not ial.success:
7788
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7789
                                 " %s" % (iallocator_name, ial.info),
7790
                                 errors.ECODE_NORES)
7791

    
7792
    if len(ial.result) != ial.required_nodes:
7793
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7794
                                 " of nodes (%s), required %s" %
7795
                                 (iallocator_name,
7796
                                  len(ial.result), ial.required_nodes),
7797
                                 errors.ECODE_FAULT)
7798

    
7799
    remote_node_name = ial.result[0]
7800

    
7801
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7802
               instance_name, remote_node_name)
7803

    
7804
    return remote_node_name
7805

    
7806
  def _FindFaultyDisks(self, node_name):
7807
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7808
                                    node_name, True)
7809

    
7810
  def CheckPrereq(self):
7811
    """Check prerequisites.
7812

7813
    This checks that the instance is in the cluster.
7814

7815
    """
7816
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7817
    assert instance is not None, \
7818
      "Cannot retrieve locked instance %s" % self.instance_name
7819

    
7820
    if instance.disk_template != constants.DT_DRBD8:
7821
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7822
                                 " instances", errors.ECODE_INVAL)
7823

    
7824
    if len(instance.secondary_nodes) != 1:
7825
      raise errors.OpPrereqError("The instance has a strange layout,"
7826
                                 " expected one secondary but found %d" %
7827
                                 len(instance.secondary_nodes),
7828
                                 errors.ECODE_FAULT)
7829

    
7830
    if not self.delay_iallocator:
7831
      self._CheckPrereq2()
7832

    
7833
  def _CheckPrereq2(self):
7834
    """Check prerequisites, second part.
7835

7836
    This function should always be part of CheckPrereq. It was separated and is
7837
    now called from Exec because during node evacuation iallocator was only
7838
    called with an unmodified cluster model, not taking planned changes into
7839
    account.
7840

7841
    """
7842
    instance = self.instance
7843
    secondary_node = instance.secondary_nodes[0]
7844

    
7845
    if self.iallocator_name is None:
7846
      remote_node = self.remote_node
7847
    else:
7848
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7849
                                       instance.name, instance.secondary_nodes)
7850

    
7851
    if remote_node is not None:
7852
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7853
      assert self.remote_node_info is not None, \
7854
        "Cannot retrieve locked node %s" % remote_node
7855
    else:
7856
      self.remote_node_info = None
7857

    
7858
    if remote_node == self.instance.primary_node:
7859
      raise errors.OpPrereqError("The specified node is the primary node of"
7860
                                 " the instance.", errors.ECODE_INVAL)
7861

    
7862
    if remote_node == secondary_node:
7863
      raise errors.OpPrereqError("The specified node is already the"
7864
                                 " secondary node of the instance.",
7865
                                 errors.ECODE_INVAL)
7866

    
7867
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7868
                                    constants.REPLACE_DISK_CHG):
7869
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7870
                                 errors.ECODE_INVAL)
7871

    
7872
    if self.mode == constants.REPLACE_DISK_AUTO:
7873
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7874
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7875

    
7876
      if faulty_primary and faulty_secondary:
7877
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7878
                                   " one node and can not be repaired"
7879
                                   " automatically" % self.instance_name,
7880
                                   errors.ECODE_STATE)
7881

    
7882
      if faulty_primary:
7883
        self.disks = faulty_primary
7884
        self.target_node = instance.primary_node
7885
        self.other_node = secondary_node
7886
        check_nodes = [self.target_node, self.other_node]
7887
      elif faulty_secondary:
7888
        self.disks = faulty_secondary
7889
        self.target_node = secondary_node
7890
        self.other_node = instance.primary_node
7891
        check_nodes = [self.target_node, self.other_node]
7892
      else:
7893
        self.disks = []
7894
        check_nodes = []
7895

    
7896
    else:
7897
      # Non-automatic modes
7898
      if self.mode == constants.REPLACE_DISK_PRI:
7899
        self.target_node = instance.primary_node
7900
        self.other_node = secondary_node
7901
        check_nodes = [self.target_node, self.other_node]
7902

    
7903
      elif self.mode == constants.REPLACE_DISK_SEC:
7904
        self.target_node = secondary_node
7905
        self.other_node = instance.primary_node
7906
        check_nodes = [self.target_node, self.other_node]
7907

    
7908
      elif self.mode == constants.REPLACE_DISK_CHG:
7909
        self.new_node = remote_node
7910
        self.other_node = instance.primary_node
7911
        self.target_node = secondary_node
7912
        check_nodes = [self.new_node, self.other_node]
7913

    
7914
        _CheckNodeNotDrained(self.lu, remote_node)
7915

    
7916
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7917
        assert old_node_info is not None
7918
        if old_node_info.offline and not self.early_release:
7919
          # doesn't make sense to delay the release
7920
          self.early_release = True
7921
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7922
                          " early-release mode", secondary_node)
7923

    
7924
      else:
7925
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7926
                                     self.mode)
7927

    
7928
      # If not specified all disks should be replaced
7929
      if not self.disks:
7930
        self.disks = range(len(self.instance.disks))
7931

    
7932
    for node in check_nodes:
7933
      _CheckNodeOnline(self.lu, node)
7934

    
7935
    # Check whether disks are valid
7936
    for disk_idx in self.disks:
7937
      instance.FindDisk(disk_idx)
7938

    
7939
    # Get secondary node IP addresses
7940
    node_2nd_ip = {}
7941

    
7942
    for node_name in [self.target_node, self.other_node, self.new_node]:
7943
      if node_name is not None:
7944
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7945

    
7946
    self.node_secondary_ip = node_2nd_ip
7947

    
7948
  def Exec(self, feedback_fn):
7949
    """Execute disk replacement.
7950

7951
    This dispatches the disk replacement to the appropriate handler.
7952

7953
    """
7954
    if self.delay_iallocator:
7955
      self._CheckPrereq2()
7956

    
7957
    if not self.disks:
7958
      feedback_fn("No disks need replacement")
7959
      return
7960

    
7961
    feedback_fn("Replacing disk(s) %s for %s" %
7962
                (utils.CommaJoin(self.disks), self.instance.name))
7963

    
7964
    activate_disks = (not self.instance.admin_up)
7965

    
7966
    # Activate the instance disks if we're replacing them on a down instance
7967
    if activate_disks:
7968
      _StartInstanceDisks(self.lu, self.instance, True)
7969

    
7970
    try:
7971
      # Should we replace the secondary node?
7972
      if self.new_node is not None:
7973
        fn = self._ExecDrbd8Secondary
7974
      else:
7975
        fn = self._ExecDrbd8DiskOnly
7976

    
7977
      return fn(feedback_fn)
7978

    
7979
    finally:
7980
      # Deactivate the instance disks if we're replacing them on a
7981
      # down instance
7982
      if activate_disks:
7983
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7984

    
7985
  def _CheckVolumeGroup(self, nodes):
7986
    self.lu.LogInfo("Checking volume groups")
7987

    
7988
    vgname = self.cfg.GetVGName()
7989

    
7990
    # Make sure volume group exists on all involved nodes
7991
    results = self.rpc.call_vg_list(nodes)
7992
    if not results:
7993
      raise errors.OpExecError("Can't list volume groups on the nodes")
7994

    
7995
    for node in nodes:
7996
      res = results[node]
7997
      res.Raise("Error checking node %s" % node)
7998
      if vgname not in res.payload:
7999
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8000
                                 (vgname, node))
8001

    
8002
  def _CheckDisksExistence(self, nodes):
8003
    # Check disk existence
8004
    for idx, dev in enumerate(self.instance.disks):
8005
      if idx not in self.disks:
8006
        continue
8007

    
8008
      for node in nodes:
8009
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8010
        self.cfg.SetDiskID(dev, node)
8011

    
8012
        result = self.rpc.call_blockdev_find(node, dev)
8013

    
8014
        msg = result.fail_msg
8015
        if msg or not result.payload:
8016
          if not msg:
8017
            msg = "disk not found"
8018
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8019
                                   (idx, node, msg))
8020

    
8021
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8022
    for idx, dev in enumerate(self.instance.disks):
8023
      if idx not in self.disks:
8024
        continue
8025

    
8026
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8027
                      (idx, node_name))
8028

    
8029
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8030
                                   ldisk=ldisk):
8031
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8032
                                 " replace disks for instance %s" %
8033
                                 (node_name, self.instance.name))
8034

    
8035
  def _CreateNewStorage(self, node_name):
8036
    vgname = self.cfg.GetVGName()
8037
    iv_names = {}
8038

    
8039
    for idx, dev in enumerate(self.instance.disks):
8040
      if idx not in self.disks:
8041
        continue
8042

    
8043
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8044

    
8045
      self.cfg.SetDiskID(dev, node_name)
8046

    
8047
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8048
      names = _GenerateUniqueNames(self.lu, lv_names)
8049

    
8050
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8051
                             logical_id=(vgname, names[0]))
8052
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8053
                             logical_id=(vgname, names[1]))
8054

    
8055
      new_lvs = [lv_data, lv_meta]
8056
      old_lvs = dev.children
8057
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8058

    
8059
      # we pass force_create=True to force the LVM creation
8060
      for new_lv in new_lvs:
8061
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8062
                        _GetInstanceInfoText(self.instance), False)
8063

    
8064
    return iv_names
8065

    
8066
  def _CheckDevices(self, node_name, iv_names):
8067
    for name, (dev, _, _) in iv_names.iteritems():
8068
      self.cfg.SetDiskID(dev, node_name)
8069

    
8070
      result = self.rpc.call_blockdev_find(node_name, dev)
8071

    
8072
      msg = result.fail_msg
8073
      if msg or not result.payload:
8074
        if not msg:
8075
          msg = "disk not found"
8076
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8077
                                 (name, msg))
8078

    
8079
      if result.payload.is_degraded:
8080
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8081

    
8082
  def _RemoveOldStorage(self, node_name, iv_names):
8083
    for name, (_, old_lvs, _) in iv_names.iteritems():
8084
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8085

    
8086
      for lv in old_lvs:
8087
        self.cfg.SetDiskID(lv, node_name)
8088

    
8089
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8090
        if msg:
8091
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8092
                             hint="remove unused LVs manually")
8093

    
8094
  def _ReleaseNodeLock(self, node_name):
8095
    """Releases the lock for a given node."""
8096
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8097

    
8098
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8099
    """Replace a disk on the primary or secondary for DRBD 8.
8100

8101
    The algorithm for replace is quite complicated:
8102

8103
      1. for each disk to be replaced:
8104

8105
        1. create new LVs on the target node with unique names
8106
        1. detach old LVs from the drbd device
8107
        1. rename old LVs to name_replaced.<time_t>
8108
        1. rename new LVs to old LVs
8109
        1. attach the new LVs (with the old names now) to the drbd device
8110

8111
      1. wait for sync across all devices
8112

8113
      1. for each modified disk:
8114

8115
        1. remove old LVs (which have the name name_replaces.<time_t>)
8116

8117
    Failures are not very well handled.
8118

8119
    """
8120
    steps_total = 6
8121

    
8122
    # Step: check device activation
8123
    self.lu.LogStep(1, steps_total, "Check device existence")
8124
    self._CheckDisksExistence([self.other_node, self.target_node])
8125
    self._CheckVolumeGroup([self.target_node, self.other_node])
8126

    
8127
    # Step: check other node consistency
8128
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8129
    self._CheckDisksConsistency(self.other_node,
8130
                                self.other_node == self.instance.primary_node,
8131
                                False)
8132

    
8133
    # Step: create new storage
8134
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8135
    iv_names = self._CreateNewStorage(self.target_node)
8136

    
8137
    # Step: for each lv, detach+rename*2+attach
8138
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8139
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8140
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8141

    
8142
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8143
                                                     old_lvs)
8144
      result.Raise("Can't detach drbd from local storage on node"
8145
                   " %s for device %s" % (self.target_node, dev.iv_name))
8146
      #dev.children = []
8147
      #cfg.Update(instance)
8148

    
8149
      # ok, we created the new LVs, so now we know we have the needed
8150
      # storage; as such, we proceed on the target node to rename
8151
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8152
      # using the assumption that logical_id == physical_id (which in
8153
      # turn is the unique_id on that node)
8154

    
8155
      # FIXME(iustin): use a better name for the replaced LVs
8156
      temp_suffix = int(time.time())
8157
      ren_fn = lambda d, suff: (d.physical_id[0],
8158
                                d.physical_id[1] + "_replaced-%s" % suff)
8159

    
8160
      # Build the rename list based on what LVs exist on the node
8161
      rename_old_to_new = []
8162
      for to_ren in old_lvs:
8163
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8164
        if not result.fail_msg and result.payload:
8165
          # device exists
8166
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8167

    
8168
      self.lu.LogInfo("Renaming the old LVs on the target node")
8169
      result = self.rpc.call_blockdev_rename(self.target_node,
8170
                                             rename_old_to_new)
8171
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8172

    
8173
      # Now we rename the new LVs to the old LVs
8174
      self.lu.LogInfo("Renaming the new LVs on the target node")
8175
      rename_new_to_old = [(new, old.physical_id)
8176
                           for old, new in zip(old_lvs, new_lvs)]
8177
      result = self.rpc.call_blockdev_rename(self.target_node,
8178
                                             rename_new_to_old)
8179
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8180

    
8181
      for old, new in zip(old_lvs, new_lvs):
8182
        new.logical_id = old.logical_id
8183
        self.cfg.SetDiskID(new, self.target_node)
8184

    
8185
      for disk in old_lvs:
8186
        disk.logical_id = ren_fn(disk, temp_suffix)
8187
        self.cfg.SetDiskID(disk, self.target_node)
8188

    
8189
      # Now that the new lvs have the old name, we can add them to the device
8190
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8191
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8192
                                                  new_lvs)
8193
      msg = result.fail_msg
8194
      if msg:
8195
        for new_lv in new_lvs:
8196
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8197
                                               new_lv).fail_msg
8198
          if msg2:
8199
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8200
                               hint=("cleanup manually the unused logical"
8201
                                     "volumes"))
8202
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8203

    
8204
      dev.children = new_lvs
8205

    
8206
      self.cfg.Update(self.instance, feedback_fn)
8207

    
8208
    cstep = 5
8209
    if self.early_release:
8210
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8211
      cstep += 1
8212
      self._RemoveOldStorage(self.target_node, iv_names)
8213
      # WARNING: we release both node locks here, do not do other RPCs
8214
      # than WaitForSync to the primary node
8215
      self._ReleaseNodeLock([self.target_node, self.other_node])
8216

    
8217
    # Wait for sync
8218
    # This can fail as the old devices are degraded and _WaitForSync
8219
    # does a combined result over all disks, so we don't check its return value
8220
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8221
    cstep += 1
8222
    _WaitForSync(self.lu, self.instance)
8223

    
8224
    # Check all devices manually
8225
    self._CheckDevices(self.instance.primary_node, iv_names)
8226

    
8227
    # Step: remove old storage
8228
    if not self.early_release:
8229
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8230
      cstep += 1
8231
      self._RemoveOldStorage(self.target_node, iv_names)
8232

    
8233
  def _ExecDrbd8Secondary(self, feedback_fn):
8234
    """Replace the secondary node for DRBD 8.
8235

8236
    The algorithm for replace is quite complicated:
8237
      - for all disks of the instance:
8238
        - create new LVs on the new node with same names
8239
        - shutdown the drbd device on the old secondary
8240
        - disconnect the drbd network on the primary
8241
        - create the drbd device on the new secondary
8242
        - network attach the drbd on the primary, using an artifice:
8243
          the drbd code for Attach() will connect to the network if it
8244
          finds a device which is connected to the good local disks but
8245
          not network enabled
8246
      - wait for sync across all devices
8247
      - remove all disks from the old secondary
8248

8249
    Failures are not very well handled.
8250

8251
    """
8252
    steps_total = 6
8253

    
8254
    # Step: check device activation
8255
    self.lu.LogStep(1, steps_total, "Check device existence")
8256
    self._CheckDisksExistence([self.instance.primary_node])
8257
    self._CheckVolumeGroup([self.instance.primary_node])
8258

    
8259
    # Step: check other node consistency
8260
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8261
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8262

    
8263
    # Step: create new storage
8264
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8265
    for idx, dev in enumerate(self.instance.disks):
8266
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8267
                      (self.new_node, idx))
8268
      # we pass force_create=True to force LVM creation
8269
      for new_lv in dev.children:
8270
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8271
                        _GetInstanceInfoText(self.instance), False)
8272

    
8273
    # Step 4: dbrd minors and drbd setups changes
8274
    # after this, we must manually remove the drbd minors on both the
8275
    # error and the success paths
8276
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8277
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8278
                                         for dev in self.instance.disks],
8279
                                        self.instance.name)
8280
    logging.debug("Allocated minors %r", minors)
8281

    
8282
    iv_names = {}
8283
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8284
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8285
                      (self.new_node, idx))
8286
      # create new devices on new_node; note that we create two IDs:
8287
      # one without port, so the drbd will be activated without
8288
      # networking information on the new node at this stage, and one
8289
      # with network, for the latter activation in step 4
8290
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8291
      if self.instance.primary_node == o_node1:
8292
        p_minor = o_minor1
8293
      else:
8294
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8295
        p_minor = o_minor2
8296

    
8297
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8298
                      p_minor, new_minor, o_secret)
8299
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8300
                    p_minor, new_minor, o_secret)
8301

    
8302
      iv_names[idx] = (dev, dev.children, new_net_id)
8303
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8304
                    new_net_id)
8305
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8306
                              logical_id=new_alone_id,
8307
                              children=dev.children,
8308
                              size=dev.size)
8309
      try:
8310
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8311
                              _GetInstanceInfoText(self.instance), False)
8312
      except errors.GenericError:
8313
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8314
        raise
8315

    
8316
    # We have new devices, shutdown the drbd on the old secondary
8317
    for idx, dev in enumerate(self.instance.disks):
8318
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8319
      self.cfg.SetDiskID(dev, self.target_node)
8320
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8321
      if msg:
8322
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8323
                           "node: %s" % (idx, msg),
8324
                           hint=("Please cleanup this device manually as"
8325
                                 " soon as possible"))
8326

    
8327
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8328
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8329
                                               self.node_secondary_ip,
8330
                                               self.instance.disks)\
8331
                                              [self.instance.primary_node]
8332

    
8333
    msg = result.fail_msg
8334
    if msg:
8335
      # detaches didn't succeed (unlikely)
8336
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8337
      raise errors.OpExecError("Can't detach the disks from the network on"
8338
                               " old node: %s" % (msg,))
8339

    
8340
    # if we managed to detach at least one, we update all the disks of
8341
    # the instance to point to the new secondary
8342
    self.lu.LogInfo("Updating instance configuration")
8343
    for dev, _, new_logical_id in iv_names.itervalues():
8344
      dev.logical_id = new_logical_id
8345
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8346

    
8347
    self.cfg.Update(self.instance, feedback_fn)
8348

    
8349
    # and now perform the drbd attach
8350
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8351
                    " (standalone => connected)")
8352
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8353
                                            self.new_node],
8354
                                           self.node_secondary_ip,
8355
                                           self.instance.disks,
8356
                                           self.instance.name,
8357
                                           False)
8358
    for to_node, to_result in result.items():
8359
      msg = to_result.fail_msg
8360
      if msg:
8361
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8362
                           to_node, msg,
8363
                           hint=("please do a gnt-instance info to see the"
8364
                                 " status of disks"))
8365
    cstep = 5
8366
    if self.early_release:
8367
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8368
      cstep += 1
8369
      self._RemoveOldStorage(self.target_node, iv_names)
8370
      # WARNING: we release all node locks here, do not do other RPCs
8371
      # than WaitForSync to the primary node
8372
      self._ReleaseNodeLock([self.instance.primary_node,
8373
                             self.target_node,
8374
                             self.new_node])
8375

    
8376
    # Wait for sync
8377
    # This can fail as the old devices are degraded and _WaitForSync
8378
    # does a combined result over all disks, so we don't check its return value
8379
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8380
    cstep += 1
8381
    _WaitForSync(self.lu, self.instance)
8382

    
8383
    # Check all devices manually
8384
    self._CheckDevices(self.instance.primary_node, iv_names)
8385

    
8386
    # Step: remove old storage
8387
    if not self.early_release:
8388
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8389
      self._RemoveOldStorage(self.target_node, iv_names)
8390

    
8391

    
8392
class LURepairNodeStorage(NoHooksLU):
8393
  """Repairs the volume group on a node.
8394

8395
  """
8396
  _OP_PARAMS = [
8397
    _PNodeName,
8398
    ("storage_type", ht.NoDefault, _CheckStorageType),
8399
    ("name", ht.NoDefault, ht.TNonEmptyString),
8400
    ("ignore_consistency", False, ht.TBool),
8401
    ]
8402
  REQ_BGL = False
8403

    
8404
  def CheckArguments(self):
8405
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8406

    
8407
    storage_type = self.op.storage_type
8408

    
8409
    if (constants.SO_FIX_CONSISTENCY not in
8410
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8411
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8412
                                 " repaired" % storage_type,
8413
                                 errors.ECODE_INVAL)
8414

    
8415
  def ExpandNames(self):
8416
    self.needed_locks = {
8417
      locking.LEVEL_NODE: [self.op.node_name],
8418
      }
8419

    
8420
  def _CheckFaultyDisks(self, instance, node_name):
8421
    """Ensure faulty disks abort the opcode or at least warn."""
8422
    try:
8423
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8424
                                  node_name, True):
8425
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8426
                                   " node '%s'" % (instance.name, node_name),
8427
                                   errors.ECODE_STATE)
8428
    except errors.OpPrereqError, err:
8429
      if self.op.ignore_consistency:
8430
        self.proc.LogWarning(str(err.args[0]))
8431
      else:
8432
        raise
8433

    
8434
  def CheckPrereq(self):
8435
    """Check prerequisites.
8436

8437
    """
8438
    # Check whether any instance on this node has faulty disks
8439
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8440
      if not inst.admin_up:
8441
        continue
8442
      check_nodes = set(inst.all_nodes)
8443
      check_nodes.discard(self.op.node_name)
8444
      for inst_node_name in check_nodes:
8445
        self._CheckFaultyDisks(inst, inst_node_name)
8446

    
8447
  def Exec(self, feedback_fn):
8448
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8449
                (self.op.name, self.op.node_name))
8450

    
8451
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8452
    result = self.rpc.call_storage_execute(self.op.node_name,
8453
                                           self.op.storage_type, st_args,
8454
                                           self.op.name,
8455
                                           constants.SO_FIX_CONSISTENCY)
8456
    result.Raise("Failed to repair storage unit '%s' on %s" %
8457
                 (self.op.name, self.op.node_name))
8458

    
8459

    
8460
class LUNodeEvacuationStrategy(NoHooksLU):
8461
  """Computes the node evacuation strategy.
8462

8463
  """
8464
  _OP_PARAMS = [
8465
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8466
    ("remote_node", None, ht.TMaybeString),
8467
    ("iallocator", None, ht.TMaybeString),
8468
    ]
8469
  REQ_BGL = False
8470

    
8471
  def CheckArguments(self):
8472
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8473

    
8474
  def ExpandNames(self):
8475
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8476
    self.needed_locks = locks = {}
8477
    if self.op.remote_node is None:
8478
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8479
    else:
8480
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8481
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8482

    
8483
  def Exec(self, feedback_fn):
8484
    if self.op.remote_node is not None:
8485
      instances = []
8486
      for node in self.op.nodes:
8487
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8488
      result = []
8489
      for i in instances:
8490
        if i.primary_node == self.op.remote_node:
8491
          raise errors.OpPrereqError("Node %s is the primary node of"
8492
                                     " instance %s, cannot use it as"
8493
                                     " secondary" %
8494
                                     (self.op.remote_node, i.name),
8495
                                     errors.ECODE_INVAL)
8496
        result.append([i.name, self.op.remote_node])
8497
    else:
8498
      ial = IAllocator(self.cfg, self.rpc,
8499
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8500
                       evac_nodes=self.op.nodes)
8501
      ial.Run(self.op.iallocator, validate=True)
8502
      if not ial.success:
8503
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8504
                                 errors.ECODE_NORES)
8505
      result = ial.result
8506
    return result
8507

    
8508

    
8509
class LUGrowDisk(LogicalUnit):
8510
  """Grow a disk of an instance.
8511

8512
  """
8513
  HPATH = "disk-grow"
8514
  HTYPE = constants.HTYPE_INSTANCE
8515
  _OP_PARAMS = [
8516
    _PInstanceName,
8517
    ("disk", ht.NoDefault, ht.TInt),
8518
    ("amount", ht.NoDefault, ht.TInt),
8519
    ("wait_for_sync", True, ht.TBool),
8520
    ]
8521
  REQ_BGL = False
8522

    
8523
  def ExpandNames(self):
8524
    self._ExpandAndLockInstance()
8525
    self.needed_locks[locking.LEVEL_NODE] = []
8526
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8527

    
8528
  def DeclareLocks(self, level):
8529
    if level == locking.LEVEL_NODE:
8530
      self._LockInstancesNodes()
8531

    
8532
  def BuildHooksEnv(self):
8533
    """Build hooks env.
8534

8535
    This runs on the master, the primary and all the secondaries.
8536

8537
    """
8538
    env = {
8539
      "DISK": self.op.disk,
8540
      "AMOUNT": self.op.amount,
8541
      }
8542
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8543
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8544
    return env, nl, nl
8545

    
8546
  def CheckPrereq(self):
8547
    """Check prerequisites.
8548

8549
    This checks that the instance is in the cluster.
8550

8551
    """
8552
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8553
    assert instance is not None, \
8554
      "Cannot retrieve locked instance %s" % self.op.instance_name
8555
    nodenames = list(instance.all_nodes)
8556
    for node in nodenames:
8557
      _CheckNodeOnline(self, node)
8558

    
8559
    self.instance = instance
8560

    
8561
    if instance.disk_template not in constants.DTS_GROWABLE:
8562
      raise errors.OpPrereqError("Instance's disk layout does not support"
8563
                                 " growing.", errors.ECODE_INVAL)
8564

    
8565
    self.disk = instance.FindDisk(self.op.disk)
8566

    
8567
    if instance.disk_template != constants.DT_FILE:
8568
      # TODO: check the free disk space for file, when that feature will be
8569
      # supported
8570
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8571

    
8572
  def Exec(self, feedback_fn):
8573
    """Execute disk grow.
8574

8575
    """
8576
    instance = self.instance
8577
    disk = self.disk
8578

    
8579
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8580
    if not disks_ok:
8581
      raise errors.OpExecError("Cannot activate block device to grow")
8582

    
8583
    for node in instance.all_nodes:
8584
      self.cfg.SetDiskID(disk, node)
8585
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8586
      result.Raise("Grow request failed to node %s" % node)
8587

    
8588
      # TODO: Rewrite code to work properly
8589
      # DRBD goes into sync mode for a short amount of time after executing the
8590
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8591
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8592
      # time is a work-around.
8593
      time.sleep(5)
8594

    
8595
    disk.RecordGrow(self.op.amount)
8596
    self.cfg.Update(instance, feedback_fn)
8597
    if self.op.wait_for_sync:
8598
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8599
      if disk_abort:
8600
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8601
                             " status.\nPlease check the instance.")
8602
      if not instance.admin_up:
8603
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8604
    elif not instance.admin_up:
8605
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8606
                           " not supposed to be running because no wait for"
8607
                           " sync mode was requested.")
8608

    
8609

    
8610
class LUQueryInstanceData(NoHooksLU):
8611
  """Query runtime instance data.
8612

8613
  """
8614
  _OP_PARAMS = [
8615
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8616
    ("static", False, ht.TBool),
8617
    ]
8618
  REQ_BGL = False
8619

    
8620
  def ExpandNames(self):
8621
    self.needed_locks = {}
8622
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8623

    
8624
    if self.op.instances:
8625
      self.wanted_names = []
8626
      for name in self.op.instances:
8627
        full_name = _ExpandInstanceName(self.cfg, name)
8628
        self.wanted_names.append(full_name)
8629
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8630
    else:
8631
      self.wanted_names = None
8632
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8633

    
8634
    self.needed_locks[locking.LEVEL_NODE] = []
8635
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8636

    
8637
  def DeclareLocks(self, level):
8638
    if level == locking.LEVEL_NODE:
8639
      self._LockInstancesNodes()
8640

    
8641
  def CheckPrereq(self):
8642
    """Check prerequisites.
8643

8644
    This only checks the optional instance list against the existing names.
8645

8646
    """
8647
    if self.wanted_names is None:
8648
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8649

    
8650
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8651
                             in self.wanted_names]
8652

    
8653
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8654
    """Returns the status of a block device
8655

8656
    """
8657
    if self.op.static or not node:
8658
      return None
8659

    
8660
    self.cfg.SetDiskID(dev, node)
8661

    
8662
    result = self.rpc.call_blockdev_find(node, dev)
8663
    if result.offline:
8664
      return None
8665

    
8666
    result.Raise("Can't compute disk status for %s" % instance_name)
8667

    
8668
    status = result.payload
8669
    if status is None:
8670
      return None
8671

    
8672
    return (status.dev_path, status.major, status.minor,
8673
            status.sync_percent, status.estimated_time,
8674
            status.is_degraded, status.ldisk_status)
8675

    
8676
  def _ComputeDiskStatus(self, instance, snode, dev):
8677
    """Compute block device status.
8678

8679
    """
8680
    if dev.dev_type in constants.LDS_DRBD:
8681
      # we change the snode then (otherwise we use the one passed in)
8682
      if dev.logical_id[0] == instance.primary_node:
8683
        snode = dev.logical_id[1]
8684
      else:
8685
        snode = dev.logical_id[0]
8686

    
8687
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8688
                                              instance.name, dev)
8689
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8690

    
8691
    if dev.children:
8692
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8693
                      for child in dev.children]
8694
    else:
8695
      dev_children = []
8696

    
8697
    data = {
8698
      "iv_name": dev.iv_name,
8699
      "dev_type": dev.dev_type,
8700
      "logical_id": dev.logical_id,
8701
      "physical_id": dev.physical_id,
8702
      "pstatus": dev_pstatus,
8703
      "sstatus": dev_sstatus,
8704
      "children": dev_children,
8705
      "mode": dev.mode,
8706
      "size": dev.size,
8707
      }
8708

    
8709
    return data
8710

    
8711
  def Exec(self, feedback_fn):
8712
    """Gather and return data"""
8713
    result = {}
8714

    
8715
    cluster = self.cfg.GetClusterInfo()
8716

    
8717
    for instance in self.wanted_instances:
8718
      if not self.op.static:
8719
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8720
                                                  instance.name,
8721
                                                  instance.hypervisor)
8722
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8723
        remote_info = remote_info.payload
8724
        if remote_info and "state" in remote_info:
8725
          remote_state = "up"
8726
        else:
8727
          remote_state = "down"
8728
      else:
8729
        remote_state = None
8730
      if instance.admin_up:
8731
        config_state = "up"
8732
      else:
8733
        config_state = "down"
8734

    
8735
      disks = [self._ComputeDiskStatus(instance, None, device)
8736
               for device in instance.disks]
8737

    
8738
      idict = {
8739
        "name": instance.name,
8740
        "config_state": config_state,
8741
        "run_state": remote_state,
8742
        "pnode": instance.primary_node,
8743
        "snodes": instance.secondary_nodes,
8744
        "os": instance.os,
8745
        # this happens to be the same format used for hooks
8746
        "nics": _NICListToTuple(self, instance.nics),
8747
        "disk_template": instance.disk_template,
8748
        "disks": disks,
8749
        "hypervisor": instance.hypervisor,
8750
        "network_port": instance.network_port,
8751
        "hv_instance": instance.hvparams,
8752
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8753
        "be_instance": instance.beparams,
8754
        "be_actual": cluster.FillBE(instance),
8755
        "os_instance": instance.osparams,
8756
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8757
        "serial_no": instance.serial_no,
8758
        "mtime": instance.mtime,
8759
        "ctime": instance.ctime,
8760
        "uuid": instance.uuid,
8761
        }
8762

    
8763
      result[instance.name] = idict
8764

    
8765
    return result
8766

    
8767

    
8768
class LUSetInstanceParams(LogicalUnit):
8769
  """Modifies an instances's parameters.
8770

8771
  """
8772
  HPATH = "instance-modify"
8773
  HTYPE = constants.HTYPE_INSTANCE
8774
  _OP_PARAMS = [
8775
    _PInstanceName,
8776
    ("nics", ht.EmptyList, ht.TList),
8777
    ("disks", ht.EmptyList, ht.TList),
8778
    ("beparams", ht.EmptyDict, ht.TDict),
8779
    ("hvparams", ht.EmptyDict, ht.TDict),
8780
    ("disk_template", None, ht.TMaybeString),
8781
    ("remote_node", None, ht.TMaybeString),
8782
    ("os_name", None, ht.TMaybeString),
8783
    ("force_variant", False, ht.TBool),
8784
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8785
    _PForce,
8786
    ]
8787
  REQ_BGL = False
8788

    
8789
  def CheckArguments(self):
8790
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8791
            self.op.hvparams or self.op.beparams or self.op.os_name):
8792
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8793

    
8794
    if self.op.hvparams:
8795
      _CheckGlobalHvParams(self.op.hvparams)
8796

    
8797
    # Disk validation
8798
    disk_addremove = 0
8799
    for disk_op, disk_dict in self.op.disks:
8800
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8801
      if disk_op == constants.DDM_REMOVE:
8802
        disk_addremove += 1
8803
        continue
8804
      elif disk_op == constants.DDM_ADD:
8805
        disk_addremove += 1
8806
      else:
8807
        if not isinstance(disk_op, int):
8808
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8809
        if not isinstance(disk_dict, dict):
8810
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8811
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8812

    
8813
      if disk_op == constants.DDM_ADD:
8814
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8815
        if mode not in constants.DISK_ACCESS_SET:
8816
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8817
                                     errors.ECODE_INVAL)
8818
        size = disk_dict.get('size', None)
8819
        if size is None:
8820
          raise errors.OpPrereqError("Required disk parameter size missing",
8821
                                     errors.ECODE_INVAL)
8822
        try:
8823
          size = int(size)
8824
        except (TypeError, ValueError), err:
8825
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8826
                                     str(err), errors.ECODE_INVAL)
8827
        disk_dict['size'] = size
8828
      else:
8829
        # modification of disk
8830
        if 'size' in disk_dict:
8831
          raise errors.OpPrereqError("Disk size change not possible, use"
8832
                                     " grow-disk", errors.ECODE_INVAL)
8833

    
8834
    if disk_addremove > 1:
8835
      raise errors.OpPrereqError("Only one disk add or remove operation"
8836
                                 " supported at a time", errors.ECODE_INVAL)
8837

    
8838
    if self.op.disks and self.op.disk_template is not None:
8839
      raise errors.OpPrereqError("Disk template conversion and other disk"
8840
                                 " changes not supported at the same time",
8841
                                 errors.ECODE_INVAL)
8842

    
8843
    if self.op.disk_template:
8844
      _CheckDiskTemplate(self.op.disk_template)
8845
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8846
          self.op.remote_node is None):
8847
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8848
                                   " one requires specifying a secondary node",
8849
                                   errors.ECODE_INVAL)
8850

    
8851
    # NIC validation
8852
    nic_addremove = 0
8853
    for nic_op, nic_dict in self.op.nics:
8854
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8855
      if nic_op == constants.DDM_REMOVE:
8856
        nic_addremove += 1
8857
        continue
8858
      elif nic_op == constants.DDM_ADD:
8859
        nic_addremove += 1
8860
      else:
8861
        if not isinstance(nic_op, int):
8862
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8863
        if not isinstance(nic_dict, dict):
8864
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8865
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8866

    
8867
      # nic_dict should be a dict
8868
      nic_ip = nic_dict.get('ip', None)
8869
      if nic_ip is not None:
8870
        if nic_ip.lower() == constants.VALUE_NONE:
8871
          nic_dict['ip'] = None
8872
        else:
8873
          if not netutils.IPAddress.IsValid(nic_ip):
8874
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8875
                                       errors.ECODE_INVAL)
8876

    
8877
      nic_bridge = nic_dict.get('bridge', None)
8878
      nic_link = nic_dict.get('link', None)
8879
      if nic_bridge and nic_link:
8880
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8881
                                   " at the same time", errors.ECODE_INVAL)
8882
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8883
        nic_dict['bridge'] = None
8884
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8885
        nic_dict['link'] = None
8886

    
8887
      if nic_op == constants.DDM_ADD:
8888
        nic_mac = nic_dict.get('mac', None)
8889
        if nic_mac is None:
8890
          nic_dict['mac'] = constants.VALUE_AUTO
8891

    
8892
      if 'mac' in nic_dict:
8893
        nic_mac = nic_dict['mac']
8894
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8895
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8896

    
8897
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8898
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8899
                                     " modifying an existing nic",
8900
                                     errors.ECODE_INVAL)
8901

    
8902
    if nic_addremove > 1:
8903
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8904
                                 " supported at a time", errors.ECODE_INVAL)
8905

    
8906
  def ExpandNames(self):
8907
    self._ExpandAndLockInstance()
8908
    self.needed_locks[locking.LEVEL_NODE] = []
8909
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8910

    
8911
  def DeclareLocks(self, level):
8912
    if level == locking.LEVEL_NODE:
8913
      self._LockInstancesNodes()
8914
      if self.op.disk_template and self.op.remote_node:
8915
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8916
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8917

    
8918
  def BuildHooksEnv(self):
8919
    """Build hooks env.
8920

8921
    This runs on the master, primary and secondaries.
8922

8923
    """
8924
    args = dict()
8925
    if constants.BE_MEMORY in self.be_new:
8926
      args['memory'] = self.be_new[constants.BE_MEMORY]
8927
    if constants.BE_VCPUS in self.be_new:
8928
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8929
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8930
    # information at all.
8931
    if self.op.nics:
8932
      args['nics'] = []
8933
      nic_override = dict(self.op.nics)
8934
      for idx, nic in enumerate(self.instance.nics):
8935
        if idx in nic_override:
8936
          this_nic_override = nic_override[idx]
8937
        else:
8938
          this_nic_override = {}
8939
        if 'ip' in this_nic_override:
8940
          ip = this_nic_override['ip']
8941
        else:
8942
          ip = nic.ip
8943
        if 'mac' in this_nic_override:
8944
          mac = this_nic_override['mac']
8945
        else:
8946
          mac = nic.mac
8947
        if idx in self.nic_pnew:
8948
          nicparams = self.nic_pnew[idx]
8949
        else:
8950
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8951
        mode = nicparams[constants.NIC_MODE]
8952
        link = nicparams[constants.NIC_LINK]
8953
        args['nics'].append((ip, mac, mode, link))
8954
      if constants.DDM_ADD in nic_override:
8955
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8956
        mac = nic_override[constants.DDM_ADD]['mac']
8957
        nicparams = self.nic_pnew[constants.DDM_ADD]
8958
        mode = nicparams[constants.NIC_MODE]
8959
        link = nicparams[constants.NIC_LINK]
8960
        args['nics'].append((ip, mac, mode, link))
8961
      elif constants.DDM_REMOVE in nic_override:
8962
        del args['nics'][-1]
8963

    
8964
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8965
    if self.op.disk_template:
8966
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8967
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8968
    return env, nl, nl
8969

    
8970
  def CheckPrereq(self):
8971
    """Check prerequisites.
8972

8973
    This only checks the instance list against the existing names.
8974

8975
    """
8976
    # checking the new params on the primary/secondary nodes
8977

    
8978
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8979
    cluster = self.cluster = self.cfg.GetClusterInfo()
8980
    assert self.instance is not None, \
8981
      "Cannot retrieve locked instance %s" % self.op.instance_name
8982
    pnode = instance.primary_node
8983
    nodelist = list(instance.all_nodes)
8984

    
8985
    # OS change
8986
    if self.op.os_name and not self.op.force:
8987
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8988
                      self.op.force_variant)
8989
      instance_os = self.op.os_name
8990
    else:
8991
      instance_os = instance.os
8992

    
8993
    if self.op.disk_template:
8994
      if instance.disk_template == self.op.disk_template:
8995
        raise errors.OpPrereqError("Instance already has disk template %s" %
8996
                                   instance.disk_template, errors.ECODE_INVAL)
8997

    
8998
      if (instance.disk_template,
8999
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9000
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9001
                                   " %s to %s" % (instance.disk_template,
9002
                                                  self.op.disk_template),
9003
                                   errors.ECODE_INVAL)
9004
      _CheckInstanceDown(self, instance, "cannot change disk template")
9005
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9006
        if self.op.remote_node == pnode:
9007
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9008
                                     " as the primary node of the instance" %
9009
                                     self.op.remote_node, errors.ECODE_STATE)
9010
        _CheckNodeOnline(self, self.op.remote_node)
9011
        _CheckNodeNotDrained(self, self.op.remote_node)
9012
        disks = [{"size": d.size} for d in instance.disks]
9013
        required = _ComputeDiskSize(self.op.disk_template, disks)
9014
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
9015

    
9016
    # hvparams processing
9017
    if self.op.hvparams:
9018
      hv_type = instance.hypervisor
9019
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9020
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9021
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9022

    
9023
      # local check
9024
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9025
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9026
      self.hv_new = hv_new # the new actual values
9027
      self.hv_inst = i_hvdict # the new dict (without defaults)
9028
    else:
9029
      self.hv_new = self.hv_inst = {}
9030

    
9031
    # beparams processing
9032
    if self.op.beparams:
9033
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9034
                                   use_none=True)
9035
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9036
      be_new = cluster.SimpleFillBE(i_bedict)
9037
      self.be_new = be_new # the new actual values
9038
      self.be_inst = i_bedict # the new dict (without defaults)
9039
    else:
9040
      self.be_new = self.be_inst = {}
9041

    
9042
    # osparams processing
9043
    if self.op.osparams:
9044
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9045
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9046
      self.os_inst = i_osdict # the new dict (without defaults)
9047
    else:
9048
      self.os_inst = {}
9049

    
9050
    self.warn = []
9051

    
9052
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9053
      mem_check_list = [pnode]
9054
      if be_new[constants.BE_AUTO_BALANCE]:
9055
        # either we changed auto_balance to yes or it was from before
9056
        mem_check_list.extend(instance.secondary_nodes)
9057
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9058
                                                  instance.hypervisor)
9059
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
9060
                                         instance.hypervisor)
9061
      pninfo = nodeinfo[pnode]
9062
      msg = pninfo.fail_msg
9063
      if msg:
9064
        # Assume the primary node is unreachable and go ahead
9065
        self.warn.append("Can't get info from primary node %s: %s" %
9066
                         (pnode,  msg))
9067
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9068
        self.warn.append("Node data from primary node %s doesn't contain"
9069
                         " free memory information" % pnode)
9070
      elif instance_info.fail_msg:
9071
        self.warn.append("Can't get instance runtime information: %s" %
9072
                        instance_info.fail_msg)
9073
      else:
9074
        if instance_info.payload:
9075
          current_mem = int(instance_info.payload['memory'])
9076
        else:
9077
          # Assume instance not running
9078
          # (there is a slight race condition here, but it's not very probable,
9079
          # and we have no other way to check)
9080
          current_mem = 0
9081
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9082
                    pninfo.payload['memory_free'])
9083
        if miss_mem > 0:
9084
          raise errors.OpPrereqError("This change will prevent the instance"
9085
                                     " from starting, due to %d MB of memory"
9086
                                     " missing on its primary node" % miss_mem,
9087
                                     errors.ECODE_NORES)
9088

    
9089
      if be_new[constants.BE_AUTO_BALANCE]:
9090
        for node, nres in nodeinfo.items():
9091
          if node not in instance.secondary_nodes:
9092
            continue
9093
          msg = nres.fail_msg
9094
          if msg:
9095
            self.warn.append("Can't get info from secondary node %s: %s" %
9096
                             (node, msg))
9097
          elif not isinstance(nres.payload.get('memory_free', None), int):
9098
            self.warn.append("Secondary node %s didn't return free"
9099
                             " memory information" % node)
9100
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9101
            self.warn.append("Not enough memory to failover instance to"
9102
                             " secondary node %s" % node)
9103

    
9104
    # NIC processing
9105
    self.nic_pnew = {}
9106
    self.nic_pinst = {}
9107
    for nic_op, nic_dict in self.op.nics:
9108
      if nic_op == constants.DDM_REMOVE:
9109
        if not instance.nics:
9110
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9111
                                     errors.ECODE_INVAL)
9112
        continue
9113
      if nic_op != constants.DDM_ADD:
9114
        # an existing nic
9115
        if not instance.nics:
9116
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9117
                                     " no NICs" % nic_op,
9118
                                     errors.ECODE_INVAL)
9119
        if nic_op < 0 or nic_op >= len(instance.nics):
9120
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9121
                                     " are 0 to %d" %
9122
                                     (nic_op, len(instance.nics) - 1),
9123
                                     errors.ECODE_INVAL)
9124
        old_nic_params = instance.nics[nic_op].nicparams
9125
        old_nic_ip = instance.nics[nic_op].ip
9126
      else:
9127
        old_nic_params = {}
9128
        old_nic_ip = None
9129

    
9130
      update_params_dict = dict([(key, nic_dict[key])
9131
                                 for key in constants.NICS_PARAMETERS
9132
                                 if key in nic_dict])
9133

    
9134
      if 'bridge' in nic_dict:
9135
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9136

    
9137
      new_nic_params = _GetUpdatedParams(old_nic_params,
9138
                                         update_params_dict)
9139
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9140
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9141
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9142
      self.nic_pinst[nic_op] = new_nic_params
9143
      self.nic_pnew[nic_op] = new_filled_nic_params
9144
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9145

    
9146
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9147
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9148
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9149
        if msg:
9150
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9151
          if self.op.force:
9152
            self.warn.append(msg)
9153
          else:
9154
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9155
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9156
        if 'ip' in nic_dict:
9157
          nic_ip = nic_dict['ip']
9158
        else:
9159
          nic_ip = old_nic_ip
9160
        if nic_ip is None:
9161
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9162
                                     ' on a routed nic', errors.ECODE_INVAL)
9163
      if 'mac' in nic_dict:
9164
        nic_mac = nic_dict['mac']
9165
        if nic_mac is None:
9166
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9167
                                     errors.ECODE_INVAL)
9168
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9169
          # otherwise generate the mac
9170
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9171
        else:
9172
          # or validate/reserve the current one
9173
          try:
9174
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9175
          except errors.ReservationError:
9176
            raise errors.OpPrereqError("MAC address %s already in use"
9177
                                       " in cluster" % nic_mac,
9178
                                       errors.ECODE_NOTUNIQUE)
9179

    
9180
    # DISK processing
9181
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9182
      raise errors.OpPrereqError("Disk operations not supported for"
9183
                                 " diskless instances",
9184
                                 errors.ECODE_INVAL)
9185
    for disk_op, _ in self.op.disks:
9186
      if disk_op == constants.DDM_REMOVE:
9187
        if len(instance.disks) == 1:
9188
          raise errors.OpPrereqError("Cannot remove the last disk of"
9189
                                     " an instance", errors.ECODE_INVAL)
9190
        _CheckInstanceDown(self, instance, "cannot remove disks")
9191

    
9192
      if (disk_op == constants.DDM_ADD and
9193
          len(instance.nics) >= constants.MAX_DISKS):
9194
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9195
                                   " add more" % constants.MAX_DISKS,
9196
                                   errors.ECODE_STATE)
9197
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9198
        # an existing disk
9199
        if disk_op < 0 or disk_op >= len(instance.disks):
9200
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9201
                                     " are 0 to %d" %
9202
                                     (disk_op, len(instance.disks)),
9203
                                     errors.ECODE_INVAL)
9204

    
9205
    return
9206

    
9207
  def _ConvertPlainToDrbd(self, feedback_fn):
9208
    """Converts an instance from plain to drbd.
9209

9210
    """
9211
    feedback_fn("Converting template to drbd")
9212
    instance = self.instance
9213
    pnode = instance.primary_node
9214
    snode = self.op.remote_node
9215

    
9216
    # create a fake disk info for _GenerateDiskTemplate
9217
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9218
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9219
                                      instance.name, pnode, [snode],
9220
                                      disk_info, None, None, 0)
9221
    info = _GetInstanceInfoText(instance)
9222
    feedback_fn("Creating aditional volumes...")
9223
    # first, create the missing data and meta devices
9224
    for disk in new_disks:
9225
      # unfortunately this is... not too nice
9226
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9227
                            info, True)
9228
      for child in disk.children:
9229
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9230
    # at this stage, all new LVs have been created, we can rename the
9231
    # old ones
9232
    feedback_fn("Renaming original volumes...")
9233
    rename_list = [(o, n.children[0].logical_id)
9234
                   for (o, n) in zip(instance.disks, new_disks)]
9235
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9236
    result.Raise("Failed to rename original LVs")
9237

    
9238
    feedback_fn("Initializing DRBD devices...")
9239
    # all child devices are in place, we can now create the DRBD devices
9240
    for disk in new_disks:
9241
      for node in [pnode, snode]:
9242
        f_create = node == pnode
9243
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9244

    
9245
    # at this point, the instance has been modified
9246
    instance.disk_template = constants.DT_DRBD8
9247
    instance.disks = new_disks
9248
    self.cfg.Update(instance, feedback_fn)
9249

    
9250
    # disks are created, waiting for sync
9251
    disk_abort = not _WaitForSync(self, instance)
9252
    if disk_abort:
9253
      raise errors.OpExecError("There are some degraded disks for"
9254
                               " this instance, please cleanup manually")
9255

    
9256
  def _ConvertDrbdToPlain(self, feedback_fn):
9257
    """Converts an instance from drbd to plain.
9258

9259
    """
9260
    instance = self.instance
9261
    assert len(instance.secondary_nodes) == 1
9262
    pnode = instance.primary_node
9263
    snode = instance.secondary_nodes[0]
9264
    feedback_fn("Converting template to plain")
9265

    
9266
    old_disks = instance.disks
9267
    new_disks = [d.children[0] for d in old_disks]
9268

    
9269
    # copy over size and mode
9270
    for parent, child in zip(old_disks, new_disks):
9271
      child.size = parent.size
9272
      child.mode = parent.mode
9273

    
9274
    # update instance structure
9275
    instance.disks = new_disks
9276
    instance.disk_template = constants.DT_PLAIN
9277
    self.cfg.Update(instance, feedback_fn)
9278

    
9279
    feedback_fn("Removing volumes on the secondary node...")
9280
    for disk in old_disks:
9281
      self.cfg.SetDiskID(disk, snode)
9282
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9283
      if msg:
9284
        self.LogWarning("Could not remove block device %s on node %s,"
9285
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9286

    
9287
    feedback_fn("Removing unneeded volumes on the primary node...")
9288
    for idx, disk in enumerate(old_disks):
9289
      meta = disk.children[1]
9290
      self.cfg.SetDiskID(meta, pnode)
9291
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9292
      if msg:
9293
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9294
                        " continuing anyway: %s", idx, pnode, msg)
9295

    
9296

    
9297
  def Exec(self, feedback_fn):
9298
    """Modifies an instance.
9299

9300
    All parameters take effect only at the next restart of the instance.
9301

9302
    """
9303
    # Process here the warnings from CheckPrereq, as we don't have a
9304
    # feedback_fn there.
9305
    for warn in self.warn:
9306
      feedback_fn("WARNING: %s" % warn)
9307

    
9308
    result = []
9309
    instance = self.instance
9310
    # disk changes
9311
    for disk_op, disk_dict in self.op.disks:
9312
      if disk_op == constants.DDM_REMOVE:
9313
        # remove the last disk
9314
        device = instance.disks.pop()
9315
        device_idx = len(instance.disks)
9316
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9317
          self.cfg.SetDiskID(disk, node)
9318
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9319
          if msg:
9320
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9321
                            " continuing anyway", device_idx, node, msg)
9322
        result.append(("disk/%d" % device_idx, "remove"))
9323
      elif disk_op == constants.DDM_ADD:
9324
        # add a new disk
9325
        if instance.disk_template == constants.DT_FILE:
9326
          file_driver, file_path = instance.disks[0].logical_id
9327
          file_path = os.path.dirname(file_path)
9328
        else:
9329
          file_driver = file_path = None
9330
        disk_idx_base = len(instance.disks)
9331
        new_disk = _GenerateDiskTemplate(self,
9332
                                         instance.disk_template,
9333
                                         instance.name, instance.primary_node,
9334
                                         instance.secondary_nodes,
9335
                                         [disk_dict],
9336
                                         file_path,
9337
                                         file_driver,
9338
                                         disk_idx_base)[0]
9339
        instance.disks.append(new_disk)
9340
        info = _GetInstanceInfoText(instance)
9341

    
9342
        logging.info("Creating volume %s for instance %s",
9343
                     new_disk.iv_name, instance.name)
9344
        # Note: this needs to be kept in sync with _CreateDisks
9345
        #HARDCODE
9346
        for node in instance.all_nodes:
9347
          f_create = node == instance.primary_node
9348
          try:
9349
            _CreateBlockDev(self, node, instance, new_disk,
9350
                            f_create, info, f_create)
9351
          except errors.OpExecError, err:
9352
            self.LogWarning("Failed to create volume %s (%s) on"
9353
                            " node %s: %s",
9354
                            new_disk.iv_name, new_disk, node, err)
9355
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9356
                       (new_disk.size, new_disk.mode)))
9357
      else:
9358
        # change a given disk
9359
        instance.disks[disk_op].mode = disk_dict['mode']
9360
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9361

    
9362
    if self.op.disk_template:
9363
      r_shut = _ShutdownInstanceDisks(self, instance)
9364
      if not r_shut:
9365
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9366
                                 " proceed with disk template conversion")
9367
      mode = (instance.disk_template, self.op.disk_template)
9368
      try:
9369
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9370
      except:
9371
        self.cfg.ReleaseDRBDMinors(instance.name)
9372
        raise
9373
      result.append(("disk_template", self.op.disk_template))
9374

    
9375
    # NIC changes
9376
    for nic_op, nic_dict in self.op.nics:
9377
      if nic_op == constants.DDM_REMOVE:
9378
        # remove the last nic
9379
        del instance.nics[-1]
9380
        result.append(("nic.%d" % len(instance.nics), "remove"))
9381
      elif nic_op == constants.DDM_ADD:
9382
        # mac and bridge should be set, by now
9383
        mac = nic_dict['mac']
9384
        ip = nic_dict.get('ip', None)
9385
        nicparams = self.nic_pinst[constants.DDM_ADD]
9386
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9387
        instance.nics.append(new_nic)
9388
        result.append(("nic.%d" % (len(instance.nics) - 1),
9389
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9390
                       (new_nic.mac, new_nic.ip,
9391
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9392
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9393
                       )))
9394
      else:
9395
        for key in 'mac', 'ip':
9396
          if key in nic_dict:
9397
            setattr(instance.nics[nic_op], key, nic_dict[key])
9398
        if nic_op in self.nic_pinst:
9399
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9400
        for key, val in nic_dict.iteritems():
9401
          result.append(("nic.%s/%d" % (key, nic_op), val))
9402

    
9403
    # hvparams changes
9404
    if self.op.hvparams:
9405
      instance.hvparams = self.hv_inst
9406
      for key, val in self.op.hvparams.iteritems():
9407
        result.append(("hv/%s" % key, val))
9408

    
9409
    # beparams changes
9410
    if self.op.beparams:
9411
      instance.beparams = self.be_inst
9412
      for key, val in self.op.beparams.iteritems():
9413
        result.append(("be/%s" % key, val))
9414

    
9415
    # OS change
9416
    if self.op.os_name:
9417
      instance.os = self.op.os_name
9418

    
9419
    # osparams changes
9420
    if self.op.osparams:
9421
      instance.osparams = self.os_inst
9422
      for key, val in self.op.osparams.iteritems():
9423
        result.append(("os/%s" % key, val))
9424

    
9425
    self.cfg.Update(instance, feedback_fn)
9426

    
9427
    return result
9428

    
9429
  _DISK_CONVERSIONS = {
9430
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9431
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9432
    }
9433

    
9434

    
9435
class LUQueryExports(NoHooksLU):
9436
  """Query the exports list
9437

9438
  """
9439
  _OP_PARAMS = [
9440
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9441
    ("use_locking", False, ht.TBool),
9442
    ]
9443
  REQ_BGL = False
9444

    
9445
  def ExpandNames(self):
9446
    self.needed_locks = {}
9447
    self.share_locks[locking.LEVEL_NODE] = 1
9448
    if not self.op.nodes:
9449
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9450
    else:
9451
      self.needed_locks[locking.LEVEL_NODE] = \
9452
        _GetWantedNodes(self, self.op.nodes)
9453

    
9454
  def Exec(self, feedback_fn):
9455
    """Compute the list of all the exported system images.
9456

9457
    @rtype: dict
9458
    @return: a dictionary with the structure node->(export-list)
9459
        where export-list is a list of the instances exported on
9460
        that node.
9461

9462
    """
9463
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9464
    rpcresult = self.rpc.call_export_list(self.nodes)
9465
    result = {}
9466
    for node in rpcresult:
9467
      if rpcresult[node].fail_msg:
9468
        result[node] = False
9469
      else:
9470
        result[node] = rpcresult[node].payload
9471

    
9472
    return result
9473

    
9474

    
9475
class LUPrepareExport(NoHooksLU):
9476
  """Prepares an instance for an export and returns useful information.
9477

9478
  """
9479
  _OP_PARAMS = [
9480
    _PInstanceName,
9481
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9482
    ]
9483
  REQ_BGL = False
9484

    
9485
  def ExpandNames(self):
9486
    self._ExpandAndLockInstance()
9487

    
9488
  def CheckPrereq(self):
9489
    """Check prerequisites.
9490

9491
    """
9492
    instance_name = self.op.instance_name
9493

    
9494
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9495
    assert self.instance is not None, \
9496
          "Cannot retrieve locked instance %s" % self.op.instance_name
9497
    _CheckNodeOnline(self, self.instance.primary_node)
9498

    
9499
    self._cds = _GetClusterDomainSecret()
9500

    
9501
  def Exec(self, feedback_fn):
9502
    """Prepares an instance for an export.
9503

9504
    """
9505
    instance = self.instance
9506

    
9507
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9508
      salt = utils.GenerateSecret(8)
9509

    
9510
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9511
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9512
                                              constants.RIE_CERT_VALIDITY)
9513
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9514

    
9515
      (name, cert_pem) = result.payload
9516

    
9517
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9518
                                             cert_pem)
9519

    
9520
      return {
9521
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9522
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9523
                          salt),
9524
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9525
        }
9526

    
9527
    return None
9528

    
9529

    
9530
class LUExportInstance(LogicalUnit):
9531
  """Export an instance to an image in the cluster.
9532

9533
  """
9534
  HPATH = "instance-export"
9535
  HTYPE = constants.HTYPE_INSTANCE
9536
  _OP_PARAMS = [
9537
    _PInstanceName,
9538
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9539
    ("shutdown", True, ht.TBool),
9540
    _PShutdownTimeout,
9541
    ("remove_instance", False, ht.TBool),
9542
    ("ignore_remove_failures", False, ht.TBool),
9543
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9544
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9545
    ("destination_x509_ca", None, ht.TMaybeString),
9546
    ]
9547
  REQ_BGL = False
9548

    
9549
  def CheckArguments(self):
9550
    """Check the arguments.
9551

9552
    """
9553
    self.x509_key_name = self.op.x509_key_name
9554
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9555

    
9556
    if self.op.remove_instance and not self.op.shutdown:
9557
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9558
                                 " down before")
9559

    
9560
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9561
      if not self.x509_key_name:
9562
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9563
                                   errors.ECODE_INVAL)
9564

    
9565
      if not self.dest_x509_ca_pem:
9566
        raise errors.OpPrereqError("Missing destination X509 CA",
9567
                                   errors.ECODE_INVAL)
9568

    
9569
  def ExpandNames(self):
9570
    self._ExpandAndLockInstance()
9571

    
9572
    # Lock all nodes for local exports
9573
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9574
      # FIXME: lock only instance primary and destination node
9575
      #
9576
      # Sad but true, for now we have do lock all nodes, as we don't know where
9577
      # the previous export might be, and in this LU we search for it and
9578
      # remove it from its current node. In the future we could fix this by:
9579
      #  - making a tasklet to search (share-lock all), then create the
9580
      #    new one, then one to remove, after
9581
      #  - removing the removal operation altogether
9582
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9583

    
9584
  def DeclareLocks(self, level):
9585
    """Last minute lock declaration."""
9586
    # All nodes are locked anyway, so nothing to do here.
9587

    
9588
  def BuildHooksEnv(self):
9589
    """Build hooks env.
9590

9591
    This will run on the master, primary node and target node.
9592

9593
    """
9594
    env = {
9595
      "EXPORT_MODE": self.op.mode,
9596
      "EXPORT_NODE": self.op.target_node,
9597
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9598
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9599
      # TODO: Generic function for boolean env variables
9600
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9601
      }
9602

    
9603
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9604

    
9605
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9606

    
9607
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9608
      nl.append(self.op.target_node)
9609

    
9610
    return env, nl, nl
9611

    
9612
  def CheckPrereq(self):
9613
    """Check prerequisites.
9614

9615
    This checks that the instance and node names are valid.
9616

9617
    """
9618
    instance_name = self.op.instance_name
9619

    
9620
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9621
    assert self.instance is not None, \
9622
          "Cannot retrieve locked instance %s" % self.op.instance_name
9623
    _CheckNodeOnline(self, self.instance.primary_node)
9624

    
9625
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9626
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9627
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9628
      assert self.dst_node is not None
9629

    
9630
      _CheckNodeOnline(self, self.dst_node.name)
9631
      _CheckNodeNotDrained(self, self.dst_node.name)
9632

    
9633
      self._cds = None
9634
      self.dest_disk_info = None
9635
      self.dest_x509_ca = None
9636

    
9637
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9638
      self.dst_node = None
9639

    
9640
      if len(self.op.target_node) != len(self.instance.disks):
9641
        raise errors.OpPrereqError(("Received destination information for %s"
9642
                                    " disks, but instance %s has %s disks") %
9643
                                   (len(self.op.target_node), instance_name,
9644
                                    len(self.instance.disks)),
9645
                                   errors.ECODE_INVAL)
9646

    
9647
      cds = _GetClusterDomainSecret()
9648

    
9649
      # Check X509 key name
9650
      try:
9651
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9652
      except (TypeError, ValueError), err:
9653
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9654

    
9655
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9656
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9657
                                   errors.ECODE_INVAL)
9658

    
9659
      # Load and verify CA
9660
      try:
9661
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9662
      except OpenSSL.crypto.Error, err:
9663
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9664
                                   (err, ), errors.ECODE_INVAL)
9665

    
9666
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9667
      if errcode is not None:
9668
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9669
                                   (msg, ), errors.ECODE_INVAL)
9670

    
9671
      self.dest_x509_ca = cert
9672

    
9673
      # Verify target information
9674
      disk_info = []
9675
      for idx, disk_data in enumerate(self.op.target_node):
9676
        try:
9677
          (host, port, magic) = \
9678
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9679
        except errors.GenericError, err:
9680
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9681
                                     (idx, err), errors.ECODE_INVAL)
9682

    
9683
        disk_info.append((host, port, magic))
9684

    
9685
      assert len(disk_info) == len(self.op.target_node)
9686
      self.dest_disk_info = disk_info
9687

    
9688
    else:
9689
      raise errors.ProgrammerError("Unhandled export mode %r" %
9690
                                   self.op.mode)
9691

    
9692
    # instance disk type verification
9693
    # TODO: Implement export support for file-based disks
9694
    for disk in self.instance.disks:
9695
      if disk.dev_type == constants.LD_FILE:
9696
        raise errors.OpPrereqError("Export not supported for instances with"
9697
                                   " file-based disks", errors.ECODE_INVAL)
9698

    
9699
  def _CleanupExports(self, feedback_fn):
9700
    """Removes exports of current instance from all other nodes.
9701

9702
    If an instance in a cluster with nodes A..D was exported to node C, its
9703
    exports will be removed from the nodes A, B and D.
9704

9705
    """
9706
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9707

    
9708
    nodelist = self.cfg.GetNodeList()
9709
    nodelist.remove(self.dst_node.name)
9710

    
9711
    # on one-node clusters nodelist will be empty after the removal
9712
    # if we proceed the backup would be removed because OpQueryExports
9713
    # substitutes an empty list with the full cluster node list.
9714
    iname = self.instance.name
9715
    if nodelist:
9716
      feedback_fn("Removing old exports for instance %s" % iname)
9717
      exportlist = self.rpc.call_export_list(nodelist)
9718
      for node in exportlist:
9719
        if exportlist[node].fail_msg:
9720
          continue
9721
        if iname in exportlist[node].payload:
9722
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9723
          if msg:
9724
            self.LogWarning("Could not remove older export for instance %s"
9725
                            " on node %s: %s", iname, node, msg)
9726

    
9727
  def Exec(self, feedback_fn):
9728
    """Export an instance to an image in the cluster.
9729

9730
    """
9731
    assert self.op.mode in constants.EXPORT_MODES
9732

    
9733
    instance = self.instance
9734
    src_node = instance.primary_node
9735

    
9736
    if self.op.shutdown:
9737
      # shutdown the instance, but not the disks
9738
      feedback_fn("Shutting down instance %s" % instance.name)
9739
      result = self.rpc.call_instance_shutdown(src_node, instance,
9740
                                               self.op.shutdown_timeout)
9741
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9742
      result.Raise("Could not shutdown instance %s on"
9743
                   " node %s" % (instance.name, src_node))
9744

    
9745
    # set the disks ID correctly since call_instance_start needs the
9746
    # correct drbd minor to create the symlinks
9747
    for disk in instance.disks:
9748
      self.cfg.SetDiskID(disk, src_node)
9749

    
9750
    activate_disks = (not instance.admin_up)
9751

    
9752
    if activate_disks:
9753
      # Activate the instance disks if we'exporting a stopped instance
9754
      feedback_fn("Activating disks for %s" % instance.name)
9755
      _StartInstanceDisks(self, instance, None)
9756

    
9757
    try:
9758
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9759
                                                     instance)
9760

    
9761
      helper.CreateSnapshots()
9762
      try:
9763
        if (self.op.shutdown and instance.admin_up and
9764
            not self.op.remove_instance):
9765
          assert not activate_disks
9766
          feedback_fn("Starting instance %s" % instance.name)
9767
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9768
          msg = result.fail_msg
9769
          if msg:
9770
            feedback_fn("Failed to start instance: %s" % msg)
9771
            _ShutdownInstanceDisks(self, instance)
9772
            raise errors.OpExecError("Could not start instance: %s" % msg)
9773

    
9774
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9775
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9776
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9777
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9778
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9779

    
9780
          (key_name, _, _) = self.x509_key_name
9781

    
9782
          dest_ca_pem = \
9783
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9784
                                            self.dest_x509_ca)
9785

    
9786
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9787
                                                     key_name, dest_ca_pem,
9788
                                                     timeouts)
9789
      finally:
9790
        helper.Cleanup()
9791

    
9792
      # Check for backwards compatibility
9793
      assert len(dresults) == len(instance.disks)
9794
      assert compat.all(isinstance(i, bool) for i in dresults), \
9795
             "Not all results are boolean: %r" % dresults
9796

    
9797
    finally:
9798
      if activate_disks:
9799
        feedback_fn("Deactivating disks for %s" % instance.name)
9800
        _ShutdownInstanceDisks(self, instance)
9801

    
9802
    if not (compat.all(dresults) and fin_resu):
9803
      failures = []
9804
      if not fin_resu:
9805
        failures.append("export finalization")
9806
      if not compat.all(dresults):
9807
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9808
                               if not dsk)
9809
        failures.append("disk export: disk(s) %s" % fdsk)
9810

    
9811
      raise errors.OpExecError("Export failed, errors in %s" %
9812
                               utils.CommaJoin(failures))
9813

    
9814
    # At this point, the export was successful, we can cleanup/finish
9815

    
9816
    # Remove instance if requested
9817
    if self.op.remove_instance:
9818
      feedback_fn("Removing instance %s" % instance.name)
9819
      _RemoveInstance(self, feedback_fn, instance,
9820
                      self.op.ignore_remove_failures)
9821

    
9822
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9823
      self._CleanupExports(feedback_fn)
9824

    
9825
    return fin_resu, dresults
9826

    
9827

    
9828
class LURemoveExport(NoHooksLU):
9829
  """Remove exports related to the named instance.
9830

9831
  """
9832
  _OP_PARAMS = [
9833
    _PInstanceName,
9834
    ]
9835
  REQ_BGL = False
9836

    
9837
  def ExpandNames(self):
9838
    self.needed_locks = {}
9839
    # We need all nodes to be locked in order for RemoveExport to work, but we
9840
    # don't need to lock the instance itself, as nothing will happen to it (and
9841
    # we can remove exports also for a removed instance)
9842
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9843

    
9844
  def Exec(self, feedback_fn):
9845
    """Remove any export.
9846

9847
    """
9848
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9849
    # If the instance was not found we'll try with the name that was passed in.
9850
    # This will only work if it was an FQDN, though.
9851
    fqdn_warn = False
9852
    if not instance_name:
9853
      fqdn_warn = True
9854
      instance_name = self.op.instance_name
9855

    
9856
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9857
    exportlist = self.rpc.call_export_list(locked_nodes)
9858
    found = False
9859
    for node in exportlist:
9860
      msg = exportlist[node].fail_msg
9861
      if msg:
9862
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9863
        continue
9864
      if instance_name in exportlist[node].payload:
9865
        found = True
9866
        result = self.rpc.call_export_remove(node, instance_name)
9867
        msg = result.fail_msg
9868
        if msg:
9869
          logging.error("Could not remove export for instance %s"
9870
                        " on node %s: %s", instance_name, node, msg)
9871

    
9872
    if fqdn_warn and not found:
9873
      feedback_fn("Export not found. If trying to remove an export belonging"
9874
                  " to a deleted instance please use its Fully Qualified"
9875
                  " Domain Name.")
9876

    
9877

    
9878
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9879
  """Generic tags LU.
9880

9881
  This is an abstract class which is the parent of all the other tags LUs.
9882

9883
  """
9884

    
9885
  def ExpandNames(self):
9886
    self.needed_locks = {}
9887
    if self.op.kind == constants.TAG_NODE:
9888
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9889
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9890
    elif self.op.kind == constants.TAG_INSTANCE:
9891
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9892
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9893

    
9894
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
9895
    # not possible to acquire the BGL based on opcode parameters)
9896

    
9897
  def CheckPrereq(self):
9898
    """Check prerequisites.
9899

9900
    """
9901
    if self.op.kind == constants.TAG_CLUSTER:
9902
      self.target = self.cfg.GetClusterInfo()
9903
    elif self.op.kind == constants.TAG_NODE:
9904
      self.target = self.cfg.GetNodeInfo(self.op.name)
9905
    elif self.op.kind == constants.TAG_INSTANCE:
9906
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9907
    else:
9908
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9909
                                 str(self.op.kind), errors.ECODE_INVAL)
9910

    
9911

    
9912
class LUGetTags(TagsLU):
9913
  """Returns the tags of a given object.
9914

9915
  """
9916
  _OP_PARAMS = [
9917
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9918
    # Name is only meaningful for nodes and instances
9919
    ("name", ht.NoDefault, ht.TMaybeString),
9920
    ]
9921
  REQ_BGL = False
9922

    
9923
  def ExpandNames(self):
9924
    TagsLU.ExpandNames(self)
9925

    
9926
    # Share locks as this is only a read operation
9927
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9928

    
9929
  def Exec(self, feedback_fn):
9930
    """Returns the tag list.
9931

9932
    """
9933
    return list(self.target.GetTags())
9934

    
9935

    
9936
class LUSearchTags(NoHooksLU):
9937
  """Searches the tags for a given pattern.
9938

9939
  """
9940
  _OP_PARAMS = [
9941
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
9942
    ]
9943
  REQ_BGL = False
9944

    
9945
  def ExpandNames(self):
9946
    self.needed_locks = {}
9947

    
9948
  def CheckPrereq(self):
9949
    """Check prerequisites.
9950

9951
    This checks the pattern passed for validity by compiling it.
9952

9953
    """
9954
    try:
9955
      self.re = re.compile(self.op.pattern)
9956
    except re.error, err:
9957
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9958
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9959

    
9960
  def Exec(self, feedback_fn):
9961
    """Returns the tag list.
9962

9963
    """
9964
    cfg = self.cfg
9965
    tgts = [("/cluster", cfg.GetClusterInfo())]
9966
    ilist = cfg.GetAllInstancesInfo().values()
9967
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9968
    nlist = cfg.GetAllNodesInfo().values()
9969
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9970
    results = []
9971
    for path, target in tgts:
9972
      for tag in target.GetTags():
9973
        if self.re.search(tag):
9974
          results.append((path, tag))
9975
    return results
9976

    
9977

    
9978
class LUAddTags(TagsLU):
9979
  """Sets a tag on a given object.
9980

9981
  """
9982
  _OP_PARAMS = [
9983
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9984
    # Name is only meaningful for nodes and instances
9985
    ("name", ht.NoDefault, ht.TMaybeString),
9986
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
9987
    ]
9988
  REQ_BGL = False
9989

    
9990
  def CheckPrereq(self):
9991
    """Check prerequisites.
9992

9993
    This checks the type and length of the tag name and value.
9994

9995
    """
9996
    TagsLU.CheckPrereq(self)
9997
    for tag in self.op.tags:
9998
      objects.TaggableObject.ValidateTag(tag)
9999

    
10000
  def Exec(self, feedback_fn):
10001
    """Sets the tag.
10002

10003
    """
10004
    try:
10005
      for tag in self.op.tags:
10006
        self.target.AddTag(tag)
10007
    except errors.TagError, err:
10008
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10009
    self.cfg.Update(self.target, feedback_fn)
10010

    
10011

    
10012
class LUDelTags(TagsLU):
10013
  """Delete a list of tags from a given object.
10014

10015
  """
10016
  _OP_PARAMS = [
10017
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10018
    # Name is only meaningful for nodes and instances
10019
    ("name", ht.NoDefault, ht.TMaybeString),
10020
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10021
    ]
10022
  REQ_BGL = False
10023

    
10024
  def CheckPrereq(self):
10025
    """Check prerequisites.
10026

10027
    This checks that we have the given tag.
10028

10029
    """
10030
    TagsLU.CheckPrereq(self)
10031
    for tag in self.op.tags:
10032
      objects.TaggableObject.ValidateTag(tag)
10033
    del_tags = frozenset(self.op.tags)
10034
    cur_tags = self.target.GetTags()
10035

    
10036
    diff_tags = del_tags - cur_tags
10037
    if diff_tags:
10038
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10039
      raise errors.OpPrereqError("Tag(s) %s not found" %
10040
                                 (utils.CommaJoin(diff_names), ),
10041
                                 errors.ECODE_NOENT)
10042

    
10043
  def Exec(self, feedback_fn):
10044
    """Remove the tag from the object.
10045

10046
    """
10047
    for tag in self.op.tags:
10048
      self.target.RemoveTag(tag)
10049
    self.cfg.Update(self.target, feedback_fn)
10050

    
10051

    
10052
class LUTestDelay(NoHooksLU):
10053
  """Sleep for a specified amount of time.
10054

10055
  This LU sleeps on the master and/or nodes for a specified amount of
10056
  time.
10057

10058
  """
10059
  _OP_PARAMS = [
10060
    ("duration", ht.NoDefault, ht.TFloat),
10061
    ("on_master", True, ht.TBool),
10062
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10063
    ("repeat", 0, ht.TPositiveInt)
10064
    ]
10065
  REQ_BGL = False
10066

    
10067
  def ExpandNames(self):
10068
    """Expand names and set required locks.
10069

10070
    This expands the node list, if any.
10071

10072
    """
10073
    self.needed_locks = {}
10074
    if self.op.on_nodes:
10075
      # _GetWantedNodes can be used here, but is not always appropriate to use
10076
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10077
      # more information.
10078
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10079
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10080

    
10081
  def _TestDelay(self):
10082
    """Do the actual sleep.
10083

10084
    """
10085
    if self.op.on_master:
10086
      if not utils.TestDelay(self.op.duration):
10087
        raise errors.OpExecError("Error during master delay test")
10088
    if self.op.on_nodes:
10089
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10090
      for node, node_result in result.items():
10091
        node_result.Raise("Failure during rpc call to node %s" % node)
10092

    
10093
  def Exec(self, feedback_fn):
10094
    """Execute the test delay opcode, with the wanted repetitions.
10095

10096
    """
10097
    if self.op.repeat == 0:
10098
      self._TestDelay()
10099
    else:
10100
      top_value = self.op.repeat - 1
10101
      for i in range(self.op.repeat):
10102
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10103
        self._TestDelay()
10104

    
10105

    
10106
class LUTestJobqueue(NoHooksLU):
10107
  """Utility LU to test some aspects of the job queue.
10108

10109
  """
10110
  _OP_PARAMS = [
10111
    ("notify_waitlock", False, ht.TBool),
10112
    ("notify_exec", False, ht.TBool),
10113
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
10114
    ("fail", False, ht.TBool),
10115
    ]
10116
  REQ_BGL = False
10117

    
10118
  # Must be lower than default timeout for WaitForJobChange to see whether it
10119
  # notices changed jobs
10120
  _CLIENT_CONNECT_TIMEOUT = 20.0
10121
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10122

    
10123
  @classmethod
10124
  def _NotifyUsingSocket(cls, cb, errcls):
10125
    """Opens a Unix socket and waits for another program to connect.
10126

10127
    @type cb: callable
10128
    @param cb: Callback to send socket name to client
10129
    @type errcls: class
10130
    @param errcls: Exception class to use for errors
10131

10132
    """
10133
    # Using a temporary directory as there's no easy way to create temporary
10134
    # sockets without writing a custom loop around tempfile.mktemp and
10135
    # socket.bind
10136
    tmpdir = tempfile.mkdtemp()
10137
    try:
10138
      tmpsock = utils.PathJoin(tmpdir, "sock")
10139

    
10140
      logging.debug("Creating temporary socket at %s", tmpsock)
10141
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10142
      try:
10143
        sock.bind(tmpsock)
10144
        sock.listen(1)
10145

    
10146
        # Send details to client
10147
        cb(tmpsock)
10148

    
10149
        # Wait for client to connect before continuing
10150
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10151
        try:
10152
          (conn, _) = sock.accept()
10153
        except socket.error, err:
10154
          raise errcls("Client didn't connect in time (%s)" % err)
10155
      finally:
10156
        sock.close()
10157
    finally:
10158
      # Remove as soon as client is connected
10159
      shutil.rmtree(tmpdir)
10160

    
10161
    # Wait for client to close
10162
    try:
10163
      try:
10164
        # pylint: disable-msg=E1101
10165
        # Instance of '_socketobject' has no ... member
10166
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10167
        conn.recv(1)
10168
      except socket.error, err:
10169
        raise errcls("Client failed to confirm notification (%s)" % err)
10170
    finally:
10171
      conn.close()
10172

    
10173
  def _SendNotification(self, test, arg, sockname):
10174
    """Sends a notification to the client.
10175

10176
    @type test: string
10177
    @param test: Test name
10178
    @param arg: Test argument (depends on test)
10179
    @type sockname: string
10180
    @param sockname: Socket path
10181

10182
    """
10183
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10184

    
10185
  def _Notify(self, prereq, test, arg):
10186
    """Notifies the client of a test.
10187

10188
    @type prereq: bool
10189
    @param prereq: Whether this is a prereq-phase test
10190
    @type test: string
10191
    @param test: Test name
10192
    @param arg: Test argument (depends on test)
10193

10194
    """
10195
    if prereq:
10196
      errcls = errors.OpPrereqError
10197
    else:
10198
      errcls = errors.OpExecError
10199

    
10200
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10201
                                                  test, arg),
10202
                                   errcls)
10203

    
10204
  def CheckArguments(self):
10205
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10206
    self.expandnames_calls = 0
10207

    
10208
  def ExpandNames(self):
10209
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10210
    if checkargs_calls < 1:
10211
      raise errors.ProgrammerError("CheckArguments was not called")
10212

    
10213
    self.expandnames_calls += 1
10214

    
10215
    if self.op.notify_waitlock:
10216
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10217

    
10218
    self.LogInfo("Expanding names")
10219

    
10220
    # Get lock on master node (just to get a lock, not for a particular reason)
10221
    self.needed_locks = {
10222
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10223
      }
10224

    
10225
  def Exec(self, feedback_fn):
10226
    if self.expandnames_calls < 1:
10227
      raise errors.ProgrammerError("ExpandNames was not called")
10228

    
10229
    if self.op.notify_exec:
10230
      self._Notify(False, constants.JQT_EXEC, None)
10231

    
10232
    self.LogInfo("Executing")
10233

    
10234
    if self.op.log_messages:
10235
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10236
      for idx, msg in enumerate(self.op.log_messages):
10237
        self.LogInfo("Sending log message %s", idx + 1)
10238
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10239
        # Report how many test messages have been sent
10240
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10241

    
10242
    if self.op.fail:
10243
      raise errors.OpExecError("Opcode failure was requested")
10244

    
10245
    return True
10246

    
10247

    
10248
class IAllocator(object):
10249
  """IAllocator framework.
10250

10251
  An IAllocator instance has three sets of attributes:
10252
    - cfg that is needed to query the cluster
10253
    - input data (all members of the _KEYS class attribute are required)
10254
    - four buffer attributes (in|out_data|text), that represent the
10255
      input (to the external script) in text and data structure format,
10256
      and the output from it, again in two formats
10257
    - the result variables from the script (success, info, nodes) for
10258
      easy usage
10259

10260
  """
10261
  # pylint: disable-msg=R0902
10262
  # lots of instance attributes
10263
  _ALLO_KEYS = [
10264
    "name", "mem_size", "disks", "disk_template",
10265
    "os", "tags", "nics", "vcpus", "hypervisor",
10266
    ]
10267
  _RELO_KEYS = [
10268
    "name", "relocate_from",
10269
    ]
10270
  _EVAC_KEYS = [
10271
    "evac_nodes",
10272
    ]
10273

    
10274
  def __init__(self, cfg, rpc, mode, **kwargs):
10275
    self.cfg = cfg
10276
    self.rpc = rpc
10277
    # init buffer variables
10278
    self.in_text = self.out_text = self.in_data = self.out_data = None
10279
    # init all input fields so that pylint is happy
10280
    self.mode = mode
10281
    self.mem_size = self.disks = self.disk_template = None
10282
    self.os = self.tags = self.nics = self.vcpus = None
10283
    self.hypervisor = None
10284
    self.relocate_from = None
10285
    self.name = None
10286
    self.evac_nodes = None
10287
    # computed fields
10288
    self.required_nodes = None
10289
    # init result fields
10290
    self.success = self.info = self.result = None
10291
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10292
      keyset = self._ALLO_KEYS
10293
      fn = self._AddNewInstance
10294
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10295
      keyset = self._RELO_KEYS
10296
      fn = self._AddRelocateInstance
10297
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10298
      keyset = self._EVAC_KEYS
10299
      fn = self._AddEvacuateNodes
10300
    else:
10301
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10302
                                   " IAllocator" % self.mode)
10303
    for key in kwargs:
10304
      if key not in keyset:
10305
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10306
                                     " IAllocator" % key)
10307
      setattr(self, key, kwargs[key])
10308

    
10309
    for key in keyset:
10310
      if key not in kwargs:
10311
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10312
                                     " IAllocator" % key)
10313
    self._BuildInputData(fn)
10314

    
10315
  def _ComputeClusterData(self):
10316
    """Compute the generic allocator input data.
10317

10318
    This is the data that is independent of the actual operation.
10319

10320
    """
10321
    cfg = self.cfg
10322
    cluster_info = cfg.GetClusterInfo()
10323
    # cluster data
10324
    data = {
10325
      "version": constants.IALLOCATOR_VERSION,
10326
      "cluster_name": cfg.GetClusterName(),
10327
      "cluster_tags": list(cluster_info.GetTags()),
10328
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10329
      # we don't have job IDs
10330
      }
10331
    iinfo = cfg.GetAllInstancesInfo().values()
10332
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10333

    
10334
    # node data
10335
    node_list = cfg.GetNodeList()
10336

    
10337
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10338
      hypervisor_name = self.hypervisor
10339
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10340
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10341
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10342
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10343

    
10344
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10345
                                        hypervisor_name)
10346
    node_iinfo = \
10347
      self.rpc.call_all_instances_info(node_list,
10348
                                       cluster_info.enabled_hypervisors)
10349

    
10350
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10351

    
10352
    data["nodes"] = self._ComputeNodeData(cfg, node_data, node_iinfo, i_list)
10353

    
10354
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10355

    
10356
    self.in_data = data
10357

    
10358
  @staticmethod
10359
  def _ComputeNodeGroupData(cfg):
10360
    """Compute node groups data.
10361

10362
    """
10363
    ng = {}
10364
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10365
      ng[guuid] = { "name": gdata.name }
10366
    return ng
10367

    
10368
  @staticmethod
10369
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10370
    """Compute global node data.
10371

10372
    """
10373
    node_results = {}
10374
    for nname, nresult in node_data.items():
10375
      # first fill in static (config-based) values
10376
      ninfo = cfg.GetNodeInfo(nname)
10377
      pnr = {
10378
        "tags": list(ninfo.GetTags()),
10379
        "primary_ip": ninfo.primary_ip,
10380
        "secondary_ip": ninfo.secondary_ip,
10381
        "offline": ninfo.offline,
10382
        "drained": ninfo.drained,
10383
        "master_candidate": ninfo.master_candidate,
10384
        "group": ninfo.group,
10385
        "master_capable": ninfo.master_capable,
10386
        "vm_capable": ninfo.vm_capable,
10387
        }
10388

    
10389
      if not (ninfo.offline or ninfo.drained):
10390
        nresult.Raise("Can't get data for node %s" % nname)
10391
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10392
                                nname)
10393
        remote_info = nresult.payload
10394

    
10395
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10396
                     'vg_size', 'vg_free', 'cpu_total']:
10397
          if attr not in remote_info:
10398
            raise errors.OpExecError("Node '%s' didn't return attribute"
10399
                                     " '%s'" % (nname, attr))
10400
          if not isinstance(remote_info[attr], int):
10401
            raise errors.OpExecError("Node '%s' returned invalid value"
10402
                                     " for '%s': %s" %
10403
                                     (nname, attr, remote_info[attr]))
10404
        # compute memory used by primary instances
10405
        i_p_mem = i_p_up_mem = 0
10406
        for iinfo, beinfo in i_list:
10407
          if iinfo.primary_node == nname:
10408
            i_p_mem += beinfo[constants.BE_MEMORY]
10409
            if iinfo.name not in node_iinfo[nname].payload:
10410
              i_used_mem = 0
10411
            else:
10412
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10413
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10414
            remote_info['memory_free'] -= max(0, i_mem_diff)
10415

    
10416
            if iinfo.admin_up:
10417
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10418

    
10419
        # compute memory used by instances
10420
        pnr_dyn = {
10421
          "total_memory": remote_info['memory_total'],
10422
          "reserved_memory": remote_info['memory_dom0'],
10423
          "free_memory": remote_info['memory_free'],
10424
          "total_disk": remote_info['vg_size'],
10425
          "free_disk": remote_info['vg_free'],
10426
          "total_cpus": remote_info['cpu_total'],
10427
          "i_pri_memory": i_p_mem,
10428
          "i_pri_up_memory": i_p_up_mem,
10429
          }
10430
        pnr.update(pnr_dyn)
10431

    
10432
      node_results[nname] = pnr
10433

    
10434
    return node_results
10435

    
10436
  @staticmethod
10437
  def _ComputeInstanceData(cluster_info, i_list):
10438
    """Compute global instance data.
10439

10440
    """
10441
    instance_data = {}
10442
    for iinfo, beinfo in i_list:
10443
      nic_data = []
10444
      for nic in iinfo.nics:
10445
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10446
        nic_dict = {"mac": nic.mac,
10447
                    "ip": nic.ip,
10448
                    "mode": filled_params[constants.NIC_MODE],
10449
                    "link": filled_params[constants.NIC_LINK],
10450
                   }
10451
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10452
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10453
        nic_data.append(nic_dict)
10454
      pir = {
10455
        "tags": list(iinfo.GetTags()),
10456
        "admin_up": iinfo.admin_up,
10457
        "vcpus": beinfo[constants.BE_VCPUS],
10458
        "memory": beinfo[constants.BE_MEMORY],
10459
        "os": iinfo.os,
10460
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10461
        "nics": nic_data,
10462
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10463
        "disk_template": iinfo.disk_template,
10464
        "hypervisor": iinfo.hypervisor,
10465
        }
10466
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10467
                                                 pir["disks"])
10468
      instance_data[iinfo.name] = pir
10469

    
10470
    return instance_data
10471

    
10472
  def _AddNewInstance(self):
10473
    """Add new instance data to allocator structure.
10474

10475
    This in combination with _AllocatorGetClusterData will create the
10476
    correct structure needed as input for the allocator.
10477

10478
    The checks for the completeness of the opcode must have already been
10479
    done.
10480

10481
    """
10482
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10483

    
10484
    if self.disk_template in constants.DTS_NET_MIRROR:
10485
      self.required_nodes = 2
10486
    else:
10487
      self.required_nodes = 1
10488
    request = {
10489
      "name": self.name,
10490
      "disk_template": self.disk_template,
10491
      "tags": self.tags,
10492
      "os": self.os,
10493
      "vcpus": self.vcpus,
10494
      "memory": self.mem_size,
10495
      "disks": self.disks,
10496
      "disk_space_total": disk_space,
10497
      "nics": self.nics,
10498
      "required_nodes": self.required_nodes,
10499
      }
10500
    return request
10501

    
10502
  def _AddRelocateInstance(self):
10503
    """Add relocate instance data to allocator structure.
10504

10505
    This in combination with _IAllocatorGetClusterData will create the
10506
    correct structure needed as input for the allocator.
10507

10508
    The checks for the completeness of the opcode must have already been
10509
    done.
10510

10511
    """
10512
    instance = self.cfg.GetInstanceInfo(self.name)
10513
    if instance is None:
10514
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10515
                                   " IAllocator" % self.name)
10516

    
10517
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10518
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10519
                                 errors.ECODE_INVAL)
10520

    
10521
    if len(instance.secondary_nodes) != 1:
10522
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10523
                                 errors.ECODE_STATE)
10524

    
10525
    self.required_nodes = 1
10526
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10527
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10528

    
10529
    request = {
10530
      "name": self.name,
10531
      "disk_space_total": disk_space,
10532
      "required_nodes": self.required_nodes,
10533
      "relocate_from": self.relocate_from,
10534
      }
10535
    return request
10536

    
10537
  def _AddEvacuateNodes(self):
10538
    """Add evacuate nodes data to allocator structure.
10539

10540
    """
10541
    request = {
10542
      "evac_nodes": self.evac_nodes
10543
      }
10544
    return request
10545

    
10546
  def _BuildInputData(self, fn):
10547
    """Build input data structures.
10548

10549
    """
10550
    self._ComputeClusterData()
10551

    
10552
    request = fn()
10553
    request["type"] = self.mode
10554
    self.in_data["request"] = request
10555

    
10556
    self.in_text = serializer.Dump(self.in_data)
10557

    
10558
  def Run(self, name, validate=True, call_fn=None):
10559
    """Run an instance allocator and return the results.
10560

10561
    """
10562
    if call_fn is None:
10563
      call_fn = self.rpc.call_iallocator_runner
10564

    
10565
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10566
    result.Raise("Failure while running the iallocator script")
10567

    
10568
    self.out_text = result.payload
10569
    if validate:
10570
      self._ValidateResult()
10571

    
10572
  def _ValidateResult(self):
10573
    """Process the allocator results.
10574

10575
    This will process and if successful save the result in
10576
    self.out_data and the other parameters.
10577

10578
    """
10579
    try:
10580
      rdict = serializer.Load(self.out_text)
10581
    except Exception, err:
10582
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10583

    
10584
    if not isinstance(rdict, dict):
10585
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10586

    
10587
    # TODO: remove backwards compatiblity in later versions
10588
    if "nodes" in rdict and "result" not in rdict:
10589
      rdict["result"] = rdict["nodes"]
10590
      del rdict["nodes"]
10591

    
10592
    for key in "success", "info", "result":
10593
      if key not in rdict:
10594
        raise errors.OpExecError("Can't parse iallocator results:"
10595
                                 " missing key '%s'" % key)
10596
      setattr(self, key, rdict[key])
10597

    
10598
    if not isinstance(rdict["result"], list):
10599
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10600
                               " is not a list")
10601
    self.out_data = rdict
10602

    
10603

    
10604
class LUTestAllocator(NoHooksLU):
10605
  """Run allocator tests.
10606

10607
  This LU runs the allocator tests
10608

10609
  """
10610
  _OP_PARAMS = [
10611
    ("direction", ht.NoDefault,
10612
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10613
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10614
    ("name", ht.NoDefault, ht.TNonEmptyString),
10615
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10616
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10617
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10618
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10619
    ("hypervisor", None, ht.TMaybeString),
10620
    ("allocator", None, ht.TMaybeString),
10621
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10622
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10623
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10624
    ("os", None, ht.TMaybeString),
10625
    ("disk_template", None, ht.TMaybeString),
10626
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10627
    ]
10628

    
10629
  def CheckPrereq(self):
10630
    """Check prerequisites.
10631

10632
    This checks the opcode parameters depending on the director and mode test.
10633

10634
    """
10635
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10636
      for attr in ["mem_size", "disks", "disk_template",
10637
                   "os", "tags", "nics", "vcpus"]:
10638
        if not hasattr(self.op, attr):
10639
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10640
                                     attr, errors.ECODE_INVAL)
10641
      iname = self.cfg.ExpandInstanceName(self.op.name)
10642
      if iname is not None:
10643
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10644
                                   iname, errors.ECODE_EXISTS)
10645
      if not isinstance(self.op.nics, list):
10646
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10647
                                   errors.ECODE_INVAL)
10648
      if not isinstance(self.op.disks, list):
10649
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10650
                                   errors.ECODE_INVAL)
10651
      for row in self.op.disks:
10652
        if (not isinstance(row, dict) or
10653
            "size" not in row or
10654
            not isinstance(row["size"], int) or
10655
            "mode" not in row or
10656
            row["mode"] not in ['r', 'w']):
10657
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10658
                                     " parameter", errors.ECODE_INVAL)
10659
      if self.op.hypervisor is None:
10660
        self.op.hypervisor = self.cfg.GetHypervisorType()
10661
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10662
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10663
      self.op.name = fname
10664
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10665
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10666
      if not hasattr(self.op, "evac_nodes"):
10667
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10668
                                   " opcode input", errors.ECODE_INVAL)
10669
    else:
10670
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10671
                                 self.op.mode, errors.ECODE_INVAL)
10672

    
10673
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10674
      if self.op.allocator is None:
10675
        raise errors.OpPrereqError("Missing allocator name",
10676
                                   errors.ECODE_INVAL)
10677
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10678
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10679
                                 self.op.direction, errors.ECODE_INVAL)
10680

    
10681
  def Exec(self, feedback_fn):
10682
    """Run the allocator test.
10683

10684
    """
10685
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10686
      ial = IAllocator(self.cfg, self.rpc,
10687
                       mode=self.op.mode,
10688
                       name=self.op.name,
10689
                       mem_size=self.op.mem_size,
10690
                       disks=self.op.disks,
10691
                       disk_template=self.op.disk_template,
10692
                       os=self.op.os,
10693
                       tags=self.op.tags,
10694
                       nics=self.op.nics,
10695
                       vcpus=self.op.vcpus,
10696
                       hypervisor=self.op.hypervisor,
10697
                       )
10698
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10699
      ial = IAllocator(self.cfg, self.rpc,
10700
                       mode=self.op.mode,
10701
                       name=self.op.name,
10702
                       relocate_from=list(self.relocate_from),
10703
                       )
10704
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10705
      ial = IAllocator(self.cfg, self.rpc,
10706
                       mode=self.op.mode,
10707
                       evac_nodes=self.op.evac_nodes)
10708
    else:
10709
      raise errors.ProgrammerError("Uncatched mode %s in"
10710
                                   " LUTestAllocator.Exec", self.op.mode)
10711

    
10712
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10713
      result = ial.in_text
10714
    else:
10715
      ial.Run(self.op.allocator, validate=False)
10716
      result = ial.out_text
10717
    return result