Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ b18ecea2

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

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

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

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

    
87

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

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

101
  Note that all commands require root permissions.
102

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

108
  """
109
  HPATH = None
110
  HTYPE = None
111
  _OP_PARAMS = []
112
  REQ_BGL = True
113

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

117
    This needs to be overridden in derived classes in order to check op
118
    validity.
119

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

    
147
    # Tasklets
148
    self.tasklets = None
149

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

    
177
    self.CheckArguments()
178

    
179
  def __GetSSH(self):
180
    """Returns the SshRunner object
181

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

    
187
  ssh = property(fget=__GetSSH)
188

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

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

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

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

204
    """
205
    pass
206

    
207
  def ExpandNames(self):
208
    """Expand names for this LU.
209

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

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

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

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

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

232
    Examples::
233

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

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

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

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

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

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

271
    """
272

    
273
  def CheckPrereq(self):
274
    """Check prerequisites for this LU.
275

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

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

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

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

    
296
  def Exec(self, feedback_fn):
297
    """Execute the LU.
298

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

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

    
311
  def BuildHooksEnv(self):
312
    """Build hooks environment for this LU.
313

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

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

325
    No nodes should be returned as an empty list (and not None).
326

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

330
    """
331
    raise NotImplementedError
332

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

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

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

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

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

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

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

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

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

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

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

390
    If should be called in DeclareLocks in a way similar to::
391

392
      if level == locking.LEVEL_NODE:
393
        self._LockInstancesNodes()
394

395
    @type primary_only: boolean
396
    @param primary_only: only lock primary nodes of locked instances
397

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

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

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

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

    
419
    del self.recalculate_locks[locking.LEVEL_NODE]
420

    
421

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

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

428
  """
429
  HPATH = None
430
  HTYPE = None
431

    
432
  def BuildHooksEnv(self):
433
    """Empty BuildHooksEnv for NoHooksLu.
434

435
    This just raises an error.
436

437
    """
438
    assert False, "BuildHooksEnv called for NoHooksLUs"
439

    
440

    
441
class Tasklet:
442
  """Tasklet base class.
443

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

448
  Subclasses must follow these rules:
449
    - Implement CheckPrereq
450
    - Implement Exec
451

452
  """
453
  def __init__(self, lu):
454
    self.lu = lu
455

    
456
    # Shortcuts
457
    self.cfg = lu.cfg
458
    self.rpc = lu.rpc
459

    
460
  def CheckPrereq(self):
461
    """Check prerequisites for this tasklets.
462

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

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

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

473
    """
474
    pass
475

    
476
  def Exec(self, feedback_fn):
477
    """Execute the tasklet.
478

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

483
    """
484
    raise NotImplementedError
485

    
486

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

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

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

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

    
506

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

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

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

    
526

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

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

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

    
559

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

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

568
  """
569
  f = utils.FieldSet()
570
  f.Extend(static)
571
  f.Extend(dynamic)
572

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

    
578

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

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

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

    
593

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

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

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

    
606

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

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

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

    
619

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

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

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

    
637

    
638
def _RequireFileStorage():
639
  """Checks that file storage is enabled.
640

641
  @raise errors.OpPrereqError: when file storage is disabled
642

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

    
648

    
649
def _CheckDiskTemplate(template):
650
  """Ensure a given disk template is valid.
651

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

    
661

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

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

    
673

    
674
def _GetClusterDomainSecret():
675
  """Reads the cluster domain secret.
676

677
  """
678
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
679
                               strict=True)
680

    
681

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

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

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

    
697

    
698
def _ExpandItemName(fn, name, kind):
699
  """Expand an item name.
700

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

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

    
714

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

    
719

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

    
724

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

730
  This builds the hook environment from individual variables.
731

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

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

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

    
794
  env["INSTANCE_NIC_COUNT"] = nic_count
795

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

    
804
  env["INSTANCE_DISK_COUNT"] = disk_count
805

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

    
810
  return env
811

    
812

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

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

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

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

    
836

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

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

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

    
874

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

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

    
890

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

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

    
901

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

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

    
915

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

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

    
924

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

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

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

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

    
944

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

    
948

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

952
  """
953

    
954
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
955

    
956

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

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

    
964

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

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

    
972

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

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

    
982
  return []
983

    
984

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

    
988
  for dev in instance.disks:
989
    cfg.SetDiskID(dev, node_name)
990

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

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

    
999
  return faulty
1000

    
1001

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

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

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

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

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

    
1033

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

1037
  """
1038
  HPATH = "cluster-init"
1039
  HTYPE = constants.HTYPE_CLUSTER
1040

    
1041
  def BuildHooksEnv(self):
1042
    """Build hooks env.
1043

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

    
1049
  def Exec(self, feedback_fn):
1050
    """Nothing to do.
1051

1052
    """
1053
    return True
1054

    
1055

    
1056
class LUDestroyCluster(LogicalUnit):
1057
  """Logical unit for destroying the cluster.
1058

1059
  """
1060
  HPATH = "cluster-destroy"
1061
  HTYPE = constants.HTYPE_CLUSTER
1062

    
1063
  def BuildHooksEnv(self):
1064
    """Build hooks env.
1065

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

    
1070
  def CheckPrereq(self):
1071
    """Check prerequisites.
1072

1073
    This checks whether the cluster is empty.
1074

1075
    Any errors are signaled by raising errors.OpPrereqError.
1076

1077
    """
1078
    master = self.cfg.GetMasterNode()
1079

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

    
1091
  def Exec(self, feedback_fn):
1092
    """Destroys the cluster.
1093

1094
    """
1095
    master = self.cfg.GetMasterNode()
1096

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

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

    
1108
    return master
1109

    
1110

    
1111
def _VerifyCertificate(filename):
1112
  """Verifies a certificate for LUVerifyCluster.
1113

1114
  @type filename: string
1115
  @param filename: Path to PEM file
1116

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

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

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

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

    
1141
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1142

    
1143

    
1144
class LUVerifyCluster(LogicalUnit):
1145
  """Verifies the cluster status.
1146

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

    
1159
  TCLUSTER = "cluster"
1160
  TNODE = "node"
1161
  TINSTANCE = "instance"
1162

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

    
1188
  ETYPE_FIELD = "code"
1189
  ETYPE_ERROR = "ERROR"
1190
  ETYPE_WARNING = "WARNING"
1191

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

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

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

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

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

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

1252
    This must be called only from Exec and functions called from Exec.
1253

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

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

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

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

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

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

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

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

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

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

    
1326
    # node seems compatible, we can actually try to look into its results
1327

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

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

    
1342

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

    
1348
    return True
1349

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

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

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

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

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

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

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

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

1390
    """
1391
    if vg_name is None:
1392
      return
1393

    
1394
    node = ninfo.name
1395
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1396

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

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

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

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

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

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

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

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

    
1461

    
1462
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1463
    """Verify an instance.
1464

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

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

    
1472
    node_vol_should = {}
1473
    instanceconfig.MapLVsByNode(node_vol_should)
1474

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

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

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

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

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

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

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

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

1522
    This checks what instances are running but unknown to the cluster.
1523

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1685
    nimg.os_fail = test
1686

    
1687
    if test:
1688
      return
1689

    
1690
    os_dict = {}
1691

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

    
1695
      if name not in os_dict:
1696
        os_dict[name] = []
1697

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

    
1704
    nimg.oslist = os_dict
1705

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

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

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

    
1718
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1719

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1848
  def BuildHooksEnv(self):
1849
    """Build hooks env.
1850

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

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

    
1862
    return env, [], all_nodes
1863

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

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

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

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

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

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

    
1908
    local_checksums = utils.FingerprintFiles(file_names)
1909

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

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

    
1934
    if drbd_helper:
1935
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
1936

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

    
1942
    for instance in instancelist:
1943
      inst_config = instanceinfo[instance]
1944

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

    
1952
      inst_config.MapLVsByNode(node_vol_should)
1953

    
1954
      pnode = inst_config.primary_node
1955
      node_image[pnode].pinst.append(instance)
1956

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

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

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

    
1976
    all_drbd_map = self.cfg.ComputeDRBDMap()
1977

    
1978
    feedback_fn("* Verifying node status")
1979

    
1980
    refos_img = None
1981

    
1982
    for node_i in nodeinfo:
1983
      node = node_i.name
1984
      nimg = node_image[node]
1985

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

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

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

    
2010
      nresult = all_nvinfo[node].payload
2011

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

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

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

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

    
2044
      if pnode_img.offline:
2045
        inst_nodes_offline.append(pnode)
2046

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

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

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

    
2067
        if s_img.offline:
2068
          inst_nodes_offline.append(snode)
2069

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

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

    
2083
    feedback_fn("* Verifying orphan instances")
2084
    self._VerifyOrphanInstances(instancelist, node_image)
2085

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

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

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

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

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

    
2105
    return not self.bad
2106

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

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

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

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

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

    
2151
      return lu_result
2152

    
2153

    
2154
class LUVerifyDisks(NoHooksLU):
2155
  """Verifies the cluster disks status.
2156

2157
  """
2158
  REQ_BGL = False
2159

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

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

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

2175
    """
2176
    result = res_nodes, res_instances, res_missing = {}, [], {}
2177

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

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

    
2195
    if not nv_dict:
2196
      return result
2197

    
2198
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2199

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

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

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

    
2225
    return result
2226

    
2227

    
2228
class LURepairDiskSizes(NoHooksLU):
2229
  """Verifies the cluster disks sizes.
2230

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

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

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

    
2258
  def CheckPrereq(self):
2259
    """Check prerequisites.
2260

2261
    This only checks the optional instance list against the existing names.
2262

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

    
2267
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2268
                             in self.wanted_names]
2269

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

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

2276
    @param disk: an L{ganeti.objects.Disk} object
2277

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

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

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

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

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

    
2343

    
2344
class LURenameCluster(LogicalUnit):
2345
  """Rename the cluster.
2346

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

    
2352
  def BuildHooksEnv(self):
2353
    """Build hooks env.
2354

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

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

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

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

    
2385
    self.op.name = new_name
2386

    
2387
  def Exec(self, feedback_fn):
2388
    """Rename the cluster.
2389

2390
    """
2391
    clustername = self.op.name
2392
    ip = self.ip
2393

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

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

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

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

    
2428
    return clustername
2429

    
2430

    
2431
class LUSetClusterParams(LogicalUnit):
2432
  """Change the parameters of the cluster.
2433

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

    
2472
  def CheckArguments(self):
2473
    """Check parameters
2474

2475
    """
2476
    if self.op.uid_pool:
2477
      uidpool.CheckUidPool(self.op.uid_pool)
2478

    
2479
    if self.op.add_uids:
2480
      uidpool.CheckUidPool(self.op.add_uids)
2481

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

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

    
2493
  def BuildHooksEnv(self):
2494
    """Build hooks env.
2495

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

    
2504
  def CheckPrereq(self):
2505
    """Check prerequisites.
2506

2507
    This checks whether the given params don't conflict and
2508
    if the given volume group is valid.
2509

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

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

    
2522
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2523

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

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

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

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

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

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

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

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

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

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

    
2622
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2623
                                                  use_none=True)
2624

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

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

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

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

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

    
2683
  def Exec(self, feedback_fn):
2684
    """Change the parameters of the cluster.
2685

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

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

    
2724
    if self.op.maintain_node_health is not None:
2725
      self.cluster.maintain_node_health = self.op.maintain_node_health
2726

    
2727
    if self.op.add_uids is not None:
2728
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2729

    
2730
    if self.op.remove_uids is not None:
2731
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2732

    
2733
    if self.op.uid_pool is not None:
2734
      self.cluster.uid_pool = self.op.uid_pool
2735

    
2736
    if self.op.default_iallocator is not None:
2737
      self.cluster.default_iallocator = self.op.default_iallocator
2738

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

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

    
2759
    if self.op.hidden_os:
2760
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2761

    
2762
    if self.op.blacklisted_os:
2763
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2764

    
2765
    self.cfg.Update(self.cluster, feedback_fn)
2766

    
2767

    
2768
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2769
  """Distribute additional files which are part of the cluster configuration.
2770

2771
  ConfigWriter takes care of distributing the config and ssconf files, but
2772
  there are more files which should be distributed to all nodes. This function
2773
  makes sure those are copied.
2774

2775
  @param lu: calling logical unit
2776
  @param additional_nodes: list of nodes not in the config to distribute to
2777

2778
  """
2779
  # 1. Gather target nodes
2780
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2781
  dist_nodes = lu.cfg.GetOnlineNodeList()
2782
  if additional_nodes is not None:
2783
    dist_nodes.extend(additional_nodes)
2784
  if myself.name in dist_nodes:
2785
    dist_nodes.remove(myself.name)
2786

    
2787
  # 2. Gather files to distribute
2788
  dist_files = set([constants.ETC_HOSTS,
2789
                    constants.SSH_KNOWN_HOSTS_FILE,
2790
                    constants.RAPI_CERT_FILE,
2791
                    constants.RAPI_USERS_FILE,
2792
                    constants.CONFD_HMAC_KEY,
2793
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2794
                   ])
2795

    
2796
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2797
  for hv_name in enabled_hypervisors:
2798
    hv_class = hypervisor.GetHypervisor(hv_name)
2799
    dist_files.update(hv_class.GetAncillaryFiles())
2800

    
2801
  # 3. Perform the files upload
2802
  for fname in dist_files:
2803
    if os.path.exists(fname):
2804
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2805
      for to_node, to_result in result.items():
2806
        msg = to_result.fail_msg
2807
        if msg:
2808
          msg = ("Copy of file %s to node %s failed: %s" %
2809
                 (fname, to_node, msg))
2810
          lu.proc.LogWarning(msg)
2811

    
2812

    
2813
class LURedistributeConfig(NoHooksLU):
2814
  """Force the redistribution of cluster configuration.
2815

2816
  This is a very simple LU.
2817

2818
  """
2819
  REQ_BGL = False
2820

    
2821
  def ExpandNames(self):
2822
    self.needed_locks = {
2823
      locking.LEVEL_NODE: locking.ALL_SET,
2824
    }
2825
    self.share_locks[locking.LEVEL_NODE] = 1
2826

    
2827
  def Exec(self, feedback_fn):
2828
    """Redistribute the configuration.
2829

2830
    """
2831
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2832
    _RedistributeAncillaryFiles(self)
2833

    
2834

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

2838
  """
2839
  if not instance.disks or disks is not None and not disks:
2840
    return True
2841

    
2842
  disks = _ExpandCheckDisks(instance, disks)
2843

    
2844
  if not oneshot:
2845
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2846

    
2847
  node = instance.primary_node
2848

    
2849
  for dev in disks:
2850
    lu.cfg.SetDiskID(dev, node)
2851

    
2852
  # TODO: Convert to utils.Retry
2853

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

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

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

    
2900
    if done or oneshot:
2901
      break
2902

    
2903
    time.sleep(min(60, max_time))
2904

    
2905
  if done:
2906
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2907
  return not cumul_degraded
2908

    
2909

    
2910
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2911
  """Check that mirrors are not degraded.
2912

2913
  The ldisk parameter, if True, will change the test from the
2914
  is_degraded attribute (which represents overall non-ok status for
2915
  the device(s)) to the ldisk (representing the local storage status).
2916

2917
  """
2918
  lu.cfg.SetDiskID(dev, node)
2919

    
2920
  result = True
2921

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

    
2937
  if dev.children:
2938
    for child in dev.children:
2939
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2940

    
2941
  return result
2942

    
2943

    
2944
class LUDiagnoseOS(NoHooksLU):
2945
  """Logical unit for OS diagnose/query.
2946

2947
  """
2948
  _OP_PARAMS = [
2949
    _POutputFields,
2950
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
2951
    ]
2952
  REQ_BGL = False
2953
  _HID = "hidden"
2954
  _BLK = "blacklisted"
2955
  _VLD = "valid"
2956
  _FIELDS_STATIC = utils.FieldSet()
2957
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
2958
                                   "parameters", "api_versions", _HID, _BLK)
2959

    
2960
  def CheckArguments(self):
2961
    if self.op.names:
2962
      raise errors.OpPrereqError("Selective OS query not supported",
2963
                                 errors.ECODE_INVAL)
2964

    
2965
    _CheckOutputFields(static=self._FIELDS_STATIC,
2966
                       dynamic=self._FIELDS_DYNAMIC,
2967
                       selected=self.op.output_fields)
2968

    
2969
  def ExpandNames(self):
2970
    # Lock all nodes, in shared mode
2971
    # Temporary removal of locks, should be reverted later
2972
    # TODO: reintroduce locks when they are lighter-weight
2973
    self.needed_locks = {}
2974
    #self.share_locks[locking.LEVEL_NODE] = 1
2975
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2976

    
2977
  @staticmethod
2978
  def _DiagnoseByOS(rlist):
2979
    """Remaps a per-node return list into an a per-os per-node dictionary
2980

2981
    @param rlist: a map with node names as keys and OS objects as values
2982

2983
    @rtype: dict
2984
    @return: a dictionary with osnames as keys and as value another
2985
        map, with nodes as keys and tuples of (path, status, diagnose,
2986
        variants, parameters, api_versions) as values, eg::
2987

2988
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
2989
                                     (/srv/..., False, "invalid api")],
2990
                           "node2": [(/srv/..., True, "", [], [])]}
2991
          }
2992

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

    
3017
  def Exec(self, feedback_fn):
3018
    """Compute the list of OSes.
3019

3020
    """
3021
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3022
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3023
    pol = self._DiagnoseByOS(node_data)
3024
    output = []
3025
    cluster = self.cfg.GetClusterInfo()
3026

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

    
3047
      is_hid = os_name in cluster.hidden_os
3048
      is_blk = os_name in cluster.blacklisted_os
3049
      if ((self._HID not in self.op.output_fields and is_hid) or
3050
          (self._BLK not in self.op.output_fields and is_blk) or
3051
          (self._VLD not in self.op.output_fields and not valid)):
3052
        continue
3053

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

    
3079
    return output
3080

    
3081

    
3082
class LURemoveNode(LogicalUnit):
3083
  """Logical unit for removing a node.
3084

3085
  """
3086
  HPATH = "node-remove"
3087
  HTYPE = constants.HTYPE_NODE
3088
  _OP_PARAMS = [
3089
    _PNodeName,
3090
    ]
3091

    
3092
  def BuildHooksEnv(self):
3093
    """Build hooks env.
3094

3095
    This doesn't run on the target node in the pre phase as a failed
3096
    node would then be impossible to remove.
3097

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

    
3111
  def CheckPrereq(self):
3112
    """Check prerequisites.
3113

3114
    This checks:
3115
     - the node exists in the configuration
3116
     - it does not have primary or secondary instances
3117
     - it's not the master
3118

3119
    Any errors are signaled by raising errors.OpPrereqError.
3120

3121
    """
3122
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3123
    node = self.cfg.GetNodeInfo(self.op.node_name)
3124
    assert node is not None
3125

    
3126
    instance_list = self.cfg.GetInstanceList()
3127

    
3128
    masternode = self.cfg.GetMasterNode()
3129
    if node.name == masternode:
3130
      raise errors.OpPrereqError("Node is the master node,"
3131
                                 " you need to failover first.",
3132
                                 errors.ECODE_INVAL)
3133

    
3134
    for instance_name in instance_list:
3135
      instance = self.cfg.GetInstanceInfo(instance_name)
3136
      if node.name in instance.all_nodes:
3137
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3138
                                   " please remove first." % instance_name,
3139
                                   errors.ECODE_INVAL)
3140
    self.op.node_name = node.name
3141
    self.node = node
3142

    
3143
  def Exec(self, feedback_fn):
3144
    """Removes the node from the cluster.
3145

3146
    """
3147
    node = self.node
3148
    logging.info("Stopping the node daemon and removing configs from node %s",
3149
                 node.name)
3150

    
3151
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3152

    
3153
    # Promote nodes to master candidate as needed
3154
    _AdjustCandidatePool(self, exceptions=[node.name])
3155
    self.context.RemoveNode(node.name)
3156

    
3157
    # Run post hooks on the node before it's removed
3158
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3159
    try:
3160
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3161
    except:
3162
      # pylint: disable-msg=W0702
3163
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3164

    
3165
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3166
    msg = result.fail_msg
3167
    if msg:
3168
      self.LogWarning("Errors encountered on the remote node while leaving"
3169
                      " the cluster: %s", msg)
3170

    
3171
    # Remove node from our /etc/hosts
3172
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3173
      master_node = self.cfg.GetMasterNode()
3174
      result = self.rpc.call_etc_hosts_modify(master_node,
3175
                                              constants.ETC_HOSTS_REMOVE,
3176
                                              node.name, None)
3177
      result.Raise("Can't update hosts file with new host data")
3178
      _RedistributeAncillaryFiles(self)
3179

    
3180

    
3181
class LUQueryNodes(NoHooksLU):
3182
  """Logical unit for querying nodes.
3183

3184
  """
3185
  # pylint: disable-msg=W0142
3186
  _OP_PARAMS = [
3187
    _POutputFields,
3188
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3189
    ("use_locking", False, ht.TBool),
3190
    ]
3191
  REQ_BGL = False
3192

    
3193
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3194
                    "master_candidate", "offline", "drained"]
3195

    
3196
  _FIELDS_DYNAMIC = utils.FieldSet(
3197
    "dtotal", "dfree",
3198
    "mtotal", "mnode", "mfree",
3199
    "bootid",
3200
    "ctotal", "cnodes", "csockets",
3201
    )
3202

    
3203
  _FIELDS_STATIC = utils.FieldSet(*[
3204
    "pinst_cnt", "sinst_cnt",
3205
    "pinst_list", "sinst_list",
3206
    "pip", "sip", "tags",
3207
    "master",
3208
    "role"] + _SIMPLE_FIELDS
3209
    )
3210

    
3211
  def CheckArguments(self):
3212
    _CheckOutputFields(static=self._FIELDS_STATIC,
3213
                       dynamic=self._FIELDS_DYNAMIC,
3214
                       selected=self.op.output_fields)
3215

    
3216
  def ExpandNames(self):
3217
    self.needed_locks = {}
3218
    self.share_locks[locking.LEVEL_NODE] = 1
3219

    
3220
    if self.op.names:
3221
      self.wanted = _GetWantedNodes(self, self.op.names)
3222
    else:
3223
      self.wanted = locking.ALL_SET
3224

    
3225
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3226
    self.do_locking = self.do_node_query and self.op.use_locking
3227
    if self.do_locking:
3228
      # if we don't request only static fields, we need to lock the nodes
3229
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3230

    
3231
  def Exec(self, feedback_fn):
3232
    """Computes the list of nodes and their attributes.
3233

3234
    """
3235
    all_info = self.cfg.GetAllNodesInfo()
3236
    if self.do_locking:
3237
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3238
    elif self.wanted != locking.ALL_SET:
3239
      nodenames = self.wanted
3240
      missing = set(nodenames).difference(all_info.keys())
3241
      if missing:
3242
        raise errors.OpExecError(
3243
          "Some nodes were removed before retrieving their data: %s" % missing)
3244
    else:
3245
      nodenames = all_info.keys()
3246

    
3247
    nodenames = utils.NiceSort(nodenames)
3248
    nodelist = [all_info[name] for name in nodenames]
3249

    
3250
    # begin data gathering
3251

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

    
3277
    node_to_primary = dict([(name, set()) for name in nodenames])
3278
    node_to_secondary = dict([(name, set()) for name in nodenames])
3279

    
3280
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3281
                             "sinst_cnt", "sinst_list"))
3282
    if inst_fields & frozenset(self.op.output_fields):
3283
      inst_data = self.cfg.GetAllInstancesInfo()
3284

    
3285
      for inst in inst_data.values():
3286
        if inst.primary_node in node_to_primary:
3287
          node_to_primary[inst.primary_node].add(inst.name)
3288
        for secnode in inst.secondary_nodes:
3289
          if secnode in node_to_secondary:
3290
            node_to_secondary[secnode].add(inst.name)
3291

    
3292
    master_node = self.cfg.GetMasterNode()
3293

    
3294
    # end data gathering
3295

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

    
3336
    return output
3337

    
3338

    
3339
class LUQueryNodeVolumes(NoHooksLU):
3340
  """Logical unit for getting volumes on node(s).
3341

3342
  """
3343
  _OP_PARAMS = [
3344
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3345
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3346
    ]
3347
  REQ_BGL = False
3348
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3349
  _FIELDS_STATIC = utils.FieldSet("node")
3350

    
3351
  def CheckArguments(self):
3352
    _CheckOutputFields(static=self._FIELDS_STATIC,
3353
                       dynamic=self._FIELDS_DYNAMIC,
3354
                       selected=self.op.output_fields)
3355

    
3356
  def ExpandNames(self):
3357
    self.needed_locks = {}
3358
    self.share_locks[locking.LEVEL_NODE] = 1
3359
    if not self.op.nodes:
3360
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3361
    else:
3362
      self.needed_locks[locking.LEVEL_NODE] = \
3363
        _GetWantedNodes(self, self.op.nodes)
3364

    
3365
  def Exec(self, feedback_fn):
3366
    """Computes the list of nodes and their attributes.
3367

3368
    """
3369
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3370
    volumes = self.rpc.call_node_volumes(nodenames)
3371

    
3372
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3373
             in self.cfg.GetInstanceList()]
3374

    
3375
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3376

    
3377
    output = []
3378
    for node in nodenames:
3379
      nresult = volumes[node]
3380
      if nresult.offline:
3381
        continue
3382
      msg = nresult.fail_msg
3383
      if msg:
3384
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3385
        continue
3386

    
3387
      node_vols = nresult.payload[:]
3388
      node_vols.sort(key=lambda vol: vol['dev'])
3389

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

    
3416
        output.append(node_output)
3417

    
3418
    return output
3419

    
3420

    
3421
class LUQueryNodeStorage(NoHooksLU):
3422
  """Logical unit for getting information on storage units on node(s).
3423

3424
  """
3425
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3426
  _OP_PARAMS = [
3427
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3428
    ("storage_type", ht.NoDefault, _CheckStorageType),
3429
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3430
    ("name", None, ht.TMaybeString),
3431
    ]
3432
  REQ_BGL = False
3433

    
3434
  def CheckArguments(self):
3435
    _CheckOutputFields(static=self._FIELDS_STATIC,
3436
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3437
                       selected=self.op.output_fields)
3438

    
3439
  def ExpandNames(self):
3440
    self.needed_locks = {}
3441
    self.share_locks[locking.LEVEL_NODE] = 1
3442

    
3443
    if self.op.nodes:
3444
      self.needed_locks[locking.LEVEL_NODE] = \
3445
        _GetWantedNodes(self, self.op.nodes)
3446
    else:
3447
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3448

    
3449
  def Exec(self, feedback_fn):
3450
    """Computes the list of nodes and their attributes.
3451

3452
    """
3453
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3454

    
3455
    # Always get name to sort by
3456
    if constants.SF_NAME in self.op.output_fields:
3457
      fields = self.op.output_fields[:]
3458
    else:
3459
      fields = [constants.SF_NAME] + self.op.output_fields
3460

    
3461
    # Never ask for node or type as it's only known to the LU
3462
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3463
      while extra in fields:
3464
        fields.remove(extra)
3465

    
3466
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3467
    name_idx = field_idx[constants.SF_NAME]
3468

    
3469
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3470
    data = self.rpc.call_storage_list(self.nodes,
3471
                                      self.op.storage_type, st_args,
3472
                                      self.op.name, fields)
3473

    
3474
    result = []
3475

    
3476
    for node in utils.NiceSort(self.nodes):
3477
      nresult = data[node]
3478
      if nresult.offline:
3479
        continue
3480

    
3481
      msg = nresult.fail_msg
3482
      if msg:
3483
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3484
        continue
3485

    
3486
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3487

    
3488
      for name in utils.NiceSort(rows.keys()):
3489
        row = rows[name]
3490

    
3491
        out = []
3492

    
3493
        for field in self.op.output_fields:
3494
          if field == constants.SF_NODE:
3495
            val = node
3496
          elif field == constants.SF_TYPE:
3497
            val = self.op.storage_type
3498
          elif field in field_idx:
3499
            val = row[field_idx[field]]
3500
          else:
3501
            raise errors.ParameterError(field)
3502

    
3503
          out.append(val)
3504

    
3505
        result.append(out)
3506

    
3507
    return result
3508

    
3509

    
3510
class LUModifyNodeStorage(NoHooksLU):
3511
  """Logical unit for modifying a storage volume on a node.
3512

3513
  """
3514
  _OP_PARAMS = [
3515
    _PNodeName,
3516
    ("storage_type", ht.NoDefault, _CheckStorageType),
3517
    ("name", ht.NoDefault, ht.TNonEmptyString),
3518
    ("changes", ht.NoDefault, ht.TDict),
3519
    ]
3520
  REQ_BGL = False
3521

    
3522
  def CheckArguments(self):
3523
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3524

    
3525
    storage_type = self.op.storage_type
3526

    
3527
    try:
3528
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3529
    except KeyError:
3530
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3531
                                 " modified" % storage_type,
3532
                                 errors.ECODE_INVAL)
3533

    
3534
    diff = set(self.op.changes.keys()) - modifiable
3535
    if diff:
3536
      raise errors.OpPrereqError("The following fields can not be modified for"
3537
                                 " storage units of type '%s': %r" %
3538
                                 (storage_type, list(diff)),
3539
                                 errors.ECODE_INVAL)
3540

    
3541
  def ExpandNames(self):
3542
    self.needed_locks = {
3543
      locking.LEVEL_NODE: self.op.node_name,
3544
      }
3545

    
3546
  def Exec(self, feedback_fn):
3547
    """Computes the list of nodes and their attributes.
3548

3549
    """
3550
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3551
    result = self.rpc.call_storage_modify(self.op.node_name,
3552
                                          self.op.storage_type, st_args,
3553
                                          self.op.name, self.op.changes)
3554
    result.Raise("Failed to modify storage unit '%s' on %s" %
3555
                 (self.op.name, self.op.node_name))
3556

    
3557

    
3558
class LUAddNode(LogicalUnit):
3559
  """Logical unit for adding node to the cluster.
3560

3561
  """
3562
  HPATH = "node-add"
3563
  HTYPE = constants.HTYPE_NODE
3564
  _OP_PARAMS = [
3565
    _PNodeName,
3566
    ("primary_ip", None, ht.NoType),
3567
    ("secondary_ip", None, ht.TMaybeString),
3568
    ("readd", False, ht.TBool),
3569
    ("nodegroup", None, ht.TMaybeString)
3570
    ]
3571

    
3572
  def CheckArguments(self):
3573
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3574
    # validate/normalize the node name
3575
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3576
                                         family=self.primary_ip_family)
3577
    self.op.node_name = self.hostname.name
3578
    if self.op.readd and self.op.nodegroup:
3579
      raise errors.OpPrereqError("Cannot pass a nodegroup when a node is"
3580
                                 " being readded", errors.ECODE_INVAL)
3581

    
3582
  def BuildHooksEnv(self):
3583
    """Build hooks env.
3584

3585
    This will run on all nodes before, and on all nodes + the new node after.
3586

3587
    """
3588
    env = {
3589
      "OP_TARGET": self.op.node_name,
3590
      "NODE_NAME": self.op.node_name,
3591
      "NODE_PIP": self.op.primary_ip,
3592
      "NODE_SIP": self.op.secondary_ip,
3593
      }
3594
    nodes_0 = self.cfg.GetNodeList()
3595
    nodes_1 = nodes_0 + [self.op.node_name, ]
3596
    return env, nodes_0, nodes_1
3597

    
3598
  def CheckPrereq(self):
3599
    """Check prerequisites.
3600

3601
    This checks:
3602
     - the new node is not already in the config
3603
     - it is resolvable
3604
     - its parameters (single/dual homed) matches the cluster
3605

3606
    Any errors are signaled by raising errors.OpPrereqError.
3607

3608
    """
3609
    cfg = self.cfg
3610
    hostname = self.hostname
3611
    node = hostname.name
3612
    primary_ip = self.op.primary_ip = hostname.ip
3613
    if self.op.secondary_ip is None:
3614
      if self.primary_ip_family == netutils.IP6Address.family:
3615
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3616
                                   " IPv4 address must be given as secondary",
3617
                                   errors.ECODE_INVAL)
3618
      self.op.secondary_ip = primary_ip
3619

    
3620
    secondary_ip = self.op.secondary_ip
3621
    if not netutils.IP4Address.IsValid(secondary_ip):
3622
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3623
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3624

    
3625
    node_list = cfg.GetNodeList()
3626
    if not self.op.readd and node in node_list:
3627
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3628
                                 node, errors.ECODE_EXISTS)
3629
    elif self.op.readd and node not in node_list:
3630
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3631
                                 errors.ECODE_NOENT)
3632

    
3633
    self.changed_primary_ip = False
3634

    
3635
    for existing_node_name in node_list:
3636
      existing_node = cfg.GetNodeInfo(existing_node_name)
3637

    
3638
      if self.op.readd and node == existing_node_name:
3639
        if existing_node.secondary_ip != secondary_ip:
3640
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3641
                                     " address configuration as before",
3642
                                     errors.ECODE_INVAL)
3643
        if existing_node.primary_ip != primary_ip:
3644
          self.changed_primary_ip = True
3645

    
3646
        continue
3647

    
3648
      if (existing_node.primary_ip == primary_ip or
3649
          existing_node.secondary_ip == primary_ip or
3650
          existing_node.primary_ip == secondary_ip or
3651
          existing_node.secondary_ip == secondary_ip):
3652
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3653
                                   " existing node %s" % existing_node.name,
3654
                                   errors.ECODE_NOTUNIQUE)
3655

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

    
3671
    # checks reachability
3672
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3673
      raise errors.OpPrereqError("Node not reachable by ping",
3674
                                 errors.ECODE_ENVIRON)
3675

    
3676
    if not newbie_singlehomed:
3677
      # check reachability from my secondary ip to newbie's secondary ip
3678
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3679
                           source=myself.secondary_ip):
3680
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3681
                                   " based ping to noded port",
3682
                                   errors.ECODE_ENVIRON)
3683

    
3684
    if self.op.readd:
3685
      exceptions = [node]
3686
    else:
3687
      exceptions = []
3688

    
3689
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3690

    
3691
    if self.op.readd:
3692
      self.new_node = self.cfg.GetNodeInfo(node)
3693
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3694
    else:
3695
      nodegroup = cfg.LookupNodeGroup(self.op.nodegroup)
3696
      self.new_node = objects.Node(name=node,
3697
                                   primary_ip=primary_ip,
3698
                                   secondary_ip=secondary_ip,
3699
                                   master_candidate=self.master_candidate,
3700
                                   offline=False, drained=False,
3701
                                   nodegroup=nodegroup)
3702

    
3703
  def Exec(self, feedback_fn):
3704
    """Adds the new node to the cluster.
3705

3706
    """
3707
    new_node = self.new_node
3708
    node = new_node.name
3709

    
3710
    # for re-adds, reset the offline/drained/master-candidate flags;
3711
    # we need to reset here, otherwise offline would prevent RPC calls
3712
    # later in the procedure; this also means that if the re-add
3713
    # fails, we are left with a non-offlined, broken node
3714
    if self.op.readd:
3715
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3716
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3717
      # if we demote the node, we do cleanup later in the procedure
3718
      new_node.master_candidate = self.master_candidate
3719
      if self.changed_primary_ip:
3720
        new_node.primary_ip = self.op.primary_ip
3721

    
3722
    # notify the user about any possible mc promotion
3723
    if new_node.master_candidate:
3724
      self.LogInfo("Node will be a master candidate")
3725

    
3726
    # check connectivity
3727
    result = self.rpc.call_version([node])[node]
3728
    result.Raise("Can't get version information from node %s" % node)
3729
    if constants.PROTOCOL_VERSION == result.payload:
3730
      logging.info("Communication to node %s fine, sw version %s match",
3731
                   node, result.payload)
3732
    else:
3733
      raise errors.OpExecError("Version mismatch master version %s,"
3734
                               " node version %s" %
3735
                               (constants.PROTOCOL_VERSION, result.payload))
3736

    
3737
    # Add node to our /etc/hosts, and add key to known_hosts
3738
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3739
      master_node = self.cfg.GetMasterNode()
3740
      result = self.rpc.call_etc_hosts_modify(master_node,
3741
                                              constants.ETC_HOSTS_ADD,
3742
                                              self.hostname.name,
3743
                                              self.hostname.ip)
3744
      result.Raise("Can't update hosts file with new host data")
3745

    
3746
    if new_node.secondary_ip != new_node.primary_ip:
3747
      result = self.rpc.call_node_has_ip_address(new_node.name,
3748
                                                 new_node.secondary_ip)
3749
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3750
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3751
      if not result.payload:
3752
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3753
                                 " you gave (%s). Please fix and re-run this"
3754
                                 " command." % new_node.secondary_ip)
3755

    
3756
    node_verify_list = [self.cfg.GetMasterNode()]
3757
    node_verify_param = {
3758
      constants.NV_NODELIST: [node],
3759
      # TODO: do a node-net-test as well?
3760
    }
3761

    
3762
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3763
                                       self.cfg.GetClusterName())
3764
    for verifier in node_verify_list:
3765
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3766
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3767
      if nl_payload:
3768
        for failed in nl_payload:
3769
          feedback_fn("ssh/hostname verification failed"
3770
                      " (checking from %s): %s" %
3771
                      (verifier, nl_payload[failed]))
3772
        raise errors.OpExecError("ssh/hostname verification failed.")
3773

    
3774
    if self.op.readd:
3775
      _RedistributeAncillaryFiles(self)
3776
      self.context.ReaddNode(new_node)
3777
      # make sure we redistribute the config
3778
      self.cfg.Update(new_node, feedback_fn)
3779
      # and make sure the new node will not have old files around
3780
      if not new_node.master_candidate:
3781
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3782
        msg = result.fail_msg
3783
        if msg:
3784
          self.LogWarning("Node failed to demote itself from master"
3785
                          " candidate status: %s" % msg)
3786
    else:
3787
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3788
      self.context.AddNode(new_node, self.proc.GetECId())
3789

    
3790

    
3791
class LUSetNodeParams(LogicalUnit):
3792
  """Modifies the parameters of a node.
3793

3794
  """
3795
  HPATH = "node-modify"
3796
  HTYPE = constants.HTYPE_NODE
3797
  _OP_PARAMS = [
3798
    _PNodeName,
3799
    ("master_candidate", None, ht.TMaybeBool),
3800
    ("offline", None, ht.TMaybeBool),
3801
    ("drained", None, ht.TMaybeBool),
3802
    ("auto_promote", False, ht.TBool),
3803
    _PForce,
3804
    ]
3805
  REQ_BGL = False
3806

    
3807
  def CheckArguments(self):
3808
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3809
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3810
    if all_mods.count(None) == 3:
3811
      raise errors.OpPrereqError("Please pass at least one modification",
3812
                                 errors.ECODE_INVAL)
3813
    if all_mods.count(True) > 1:
3814
      raise errors.OpPrereqError("Can't set the node into more than one"
3815
                                 " state at the same time",
3816
                                 errors.ECODE_INVAL)
3817

    
3818
    # Boolean value that tells us whether we're offlining or draining the node
3819
    self.offline_or_drain = (self.op.offline == True or
3820
                             self.op.drained == True)
3821
    self.deoffline_or_drain = (self.op.offline == False or
3822
                               self.op.drained == False)
3823
    self.might_demote = (self.op.master_candidate == False or
3824
                         self.offline_or_drain)
3825

    
3826
    self.lock_all = self.op.auto_promote and self.might_demote
3827

    
3828

    
3829
  def ExpandNames(self):
3830
    if self.lock_all:
3831
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3832
    else:
3833
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3834

    
3835
  def BuildHooksEnv(self):
3836
    """Build hooks env.
3837

3838
    This runs on the master node.
3839

3840
    """
3841
    env = {
3842
      "OP_TARGET": self.op.node_name,
3843
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3844
      "OFFLINE": str(self.op.offline),
3845
      "DRAINED": str(self.op.drained),
3846
      }
3847
    nl = [self.cfg.GetMasterNode(),
3848
          self.op.node_name]
3849
    return env, nl, nl
3850

    
3851
  def CheckPrereq(self):
3852
    """Check prerequisites.
3853

3854
    This only checks the instance list against the existing names.
3855

3856
    """
3857
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3858

    
3859
    if (self.op.master_candidate is not None or
3860
        self.op.drained is not None or
3861
        self.op.offline is not None):
3862
      # we can't change the master's node flags
3863
      if self.op.node_name == self.cfg.GetMasterNode():
3864
        raise errors.OpPrereqError("The master role can be changed"
3865
                                   " only via master-failover",
3866
                                   errors.ECODE_INVAL)
3867

    
3868

    
3869
    if node.master_candidate and self.might_demote and not self.lock_all:
3870
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3871
      # check if after removing the current node, we're missing master
3872
      # candidates
3873
      (mc_remaining, mc_should, _) = \
3874
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3875
      if mc_remaining < mc_should:
3876
        raise errors.OpPrereqError("Not enough master candidates, please"
3877
                                   " pass auto_promote to allow promotion",
3878
                                   errors.ECODE_INVAL)
3879

    
3880
    if (self.op.master_candidate == True and
3881
        ((node.offline and not self.op.offline == False) or
3882
         (node.drained and not self.op.drained == False))):
3883
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3884
                                 " to master_candidate" % node.name,
3885
                                 errors.ECODE_INVAL)
3886

    
3887
    # If we're being deofflined/drained, we'll MC ourself if needed
3888
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3889
        self.op.master_candidate == True and not node.master_candidate):
3890
      self.op.master_candidate = _DecideSelfPromotion(self)
3891
      if self.op.master_candidate:
3892
        self.LogInfo("Autopromoting node to master candidate")
3893

    
3894
    return
3895

    
3896
  def Exec(self, feedback_fn):
3897
    """Modifies a node.
3898

3899
    """
3900
    node = self.node
3901

    
3902
    result = []
3903
    changed_mc = False
3904

    
3905
    if self.op.offline is not None:
3906
      node.offline = self.op.offline
3907
      result.append(("offline", str(self.op.offline)))
3908
      if self.op.offline == True:
3909
        if node.master_candidate:
3910
          node.master_candidate = False
3911
          changed_mc = True
3912
          result.append(("master_candidate", "auto-demotion due to offline"))
3913
        if node.drained:
3914
          node.drained = False
3915
          result.append(("drained", "clear drained status due to offline"))
3916

    
3917
    if self.op.master_candidate is not None:
3918
      node.master_candidate = self.op.master_candidate
3919
      changed_mc = True
3920
      result.append(("master_candidate", str(self.op.master_candidate)))
3921
      if self.op.master_candidate == False:
3922
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3923
        msg = rrc.fail_msg
3924
        if msg:
3925
          self.LogWarning("Node failed to demote itself: %s" % msg)
3926

    
3927
    if self.op.drained is not None:
3928
      node.drained = self.op.drained
3929
      result.append(("drained", str(self.op.drained)))
3930
      if self.op.drained == True:
3931
        if node.master_candidate:
3932
          node.master_candidate = False
3933
          changed_mc = True
3934
          result.append(("master_candidate", "auto-demotion due to drain"))
3935
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3936
          msg = rrc.fail_msg
3937
          if msg:
3938
            self.LogWarning("Node failed to demote itself: %s" % msg)
3939
        if node.offline:
3940
          node.offline = False
3941
          result.append(("offline", "clear offline status due to drain"))
3942

    
3943
    # we locked all nodes, we adjust the CP before updating this node
3944
    if self.lock_all:
3945
      _AdjustCandidatePool(self, [node.name])
3946

    
3947
    # this will trigger configuration file update, if needed
3948
    self.cfg.Update(node, feedback_fn)
3949

    
3950
    # this will trigger job queue propagation or cleanup
3951
    if changed_mc:
3952
      self.context.ReaddNode(node)
3953

    
3954
    return result
3955

    
3956

    
3957
class LUPowercycleNode(NoHooksLU):
3958
  """Powercycles a node.
3959

3960
  """
3961
  _OP_PARAMS = [
3962
    _PNodeName,
3963
    _PForce,
3964
    ]
3965
  REQ_BGL = False
3966

    
3967
  def CheckArguments(self):
3968
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3969
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3970
      raise errors.OpPrereqError("The node is the master and the force"
3971
                                 " parameter was not set",
3972
                                 errors.ECODE_INVAL)
3973

    
3974
  def ExpandNames(self):
3975
    """Locking for PowercycleNode.
3976

3977
    This is a last-resort option and shouldn't block on other
3978
    jobs. Therefore, we grab no locks.
3979

3980
    """
3981
    self.needed_locks = {}
3982

    
3983
  def Exec(self, feedback_fn):
3984
    """Reboots a node.
3985

3986
    """
3987
    result = self.rpc.call_node_powercycle(self.op.node_name,
3988
                                           self.cfg.GetHypervisorType())
3989
    result.Raise("Failed to schedule the reboot")
3990
    return result.payload
3991

    
3992

    
3993
class LUQueryClusterInfo(NoHooksLU):
3994
  """Query cluster configuration.
3995

3996
  """
3997
  REQ_BGL = False
3998

    
3999
  def ExpandNames(self):
4000
    self.needed_locks = {}
4001

    
4002
  def Exec(self, feedback_fn):
4003
    """Return cluster config.
4004

4005
    """
4006
    cluster = self.cfg.GetClusterInfo()
4007
    os_hvp = {}
4008

    
4009
    # Filter just for enabled hypervisors
4010
    for os_name, hv_dict in cluster.os_hvp.items():
4011
      os_hvp[os_name] = {}
4012
      for hv_name, hv_params in hv_dict.items():
4013
        if hv_name in cluster.enabled_hypervisors:
4014
          os_hvp[os_name][hv_name] = hv_params
4015

    
4016
    # Convert ip_family to ip_version
4017
    primary_ip_version = constants.IP4_VERSION
4018
    if cluster.primary_ip_family == netutils.IP6Address.family:
4019
      primary_ip_version = constants.IP6_VERSION
4020

    
4021
    result = {
4022
      "software_version": constants.RELEASE_VERSION,
4023
      "protocol_version": constants.PROTOCOL_VERSION,
4024
      "config_version": constants.CONFIG_VERSION,
4025
      "os_api_version": max(constants.OS_API_VERSIONS),
4026
      "export_version": constants.EXPORT_VERSION,
4027
      "architecture": (platform.architecture()[0], platform.machine()),
4028
      "name": cluster.cluster_name,
4029
      "master": cluster.master_node,
4030
      "default_hypervisor": cluster.enabled_hypervisors[0],
4031
      "enabled_hypervisors": cluster.enabled_hypervisors,
4032
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4033
                        for hypervisor_name in cluster.enabled_hypervisors]),
4034
      "os_hvp": os_hvp,
4035
      "beparams": cluster.beparams,
4036
      "osparams": cluster.osparams,
4037
      "nicparams": cluster.nicparams,
4038
      "candidate_pool_size": cluster.candidate_pool_size,
4039
      "master_netdev": cluster.master_netdev,
4040
      "volume_group_name": cluster.volume_group_name,
4041
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4042
      "file_storage_dir": cluster.file_storage_dir,
4043
      "maintain_node_health": cluster.maintain_node_health,
4044
      "ctime": cluster.ctime,
4045
      "mtime": cluster.mtime,
4046
      "uuid": cluster.uuid,
4047
      "tags": list(cluster.GetTags()),
4048
      "uid_pool": cluster.uid_pool,
4049
      "default_iallocator": cluster.default_iallocator,
4050
      "reserved_lvs": cluster.reserved_lvs,
4051
      "primary_ip_version": primary_ip_version,
4052
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4053
      }
4054

    
4055
    return result
4056

    
4057

    
4058
class LUQueryConfigValues(NoHooksLU):
4059
  """Return configuration values.
4060

4061
  """
4062
  _OP_PARAMS = [_POutputFields]
4063
  REQ_BGL = False
4064
  _FIELDS_DYNAMIC = utils.FieldSet()
4065
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4066
                                  "watcher_pause", "volume_group_name")
4067

    
4068
  def CheckArguments(self):
4069
    _CheckOutputFields(static=self._FIELDS_STATIC,
4070
                       dynamic=self._FIELDS_DYNAMIC,
4071
                       selected=self.op.output_fields)
4072

    
4073
  def ExpandNames(self):
4074
    self.needed_locks = {}
4075

    
4076
  def Exec(self, feedback_fn):
4077
    """Dump a representation of the cluster config to the standard output.
4078

4079
    """
4080
    values = []
4081
    for field in self.op.output_fields:
4082
      if field == "cluster_name":
4083
        entry = self.cfg.GetClusterName()
4084
      elif field == "master_node":
4085
        entry = self.cfg.GetMasterNode()
4086
      elif field == "drain_flag":
4087
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4088
      elif field == "watcher_pause":
4089
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4090
      elif field == "volume_group_name":
4091
        entry = self.cfg.GetVGName()
4092
      else:
4093
        raise errors.ParameterError(field)
4094
      values.append(entry)
4095
    return values
4096

    
4097

    
4098
class LUActivateInstanceDisks(NoHooksLU):
4099
  """Bring up an instance's disks.
4100

4101
  """
4102
  _OP_PARAMS = [
4103
    _PInstanceName,
4104
    ("ignore_size", False, ht.TBool),
4105
    ]
4106
  REQ_BGL = False
4107

    
4108
  def ExpandNames(self):
4109
    self._ExpandAndLockInstance()
4110
    self.needed_locks[locking.LEVEL_NODE] = []
4111
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4112

    
4113
  def DeclareLocks(self, level):
4114
    if level == locking.LEVEL_NODE:
4115
      self._LockInstancesNodes()
4116

    
4117
  def CheckPrereq(self):
4118
    """Check prerequisites.
4119

4120
    This checks that the instance is in the cluster.
4121

4122
    """
4123
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4124
    assert self.instance is not None, \
4125
      "Cannot retrieve locked instance %s" % self.op.instance_name
4126
    _CheckNodeOnline(self, self.instance.primary_node)
4127

    
4128
  def Exec(self, feedback_fn):
4129
    """Activate the disks.
4130

4131
    """
4132
    disks_ok, disks_info = \
4133
              _AssembleInstanceDisks(self, self.instance,
4134
                                     ignore_size=self.op.ignore_size)
4135
    if not disks_ok:
4136
      raise errors.OpExecError("Cannot activate block devices")
4137

    
4138
    return disks_info
4139

    
4140

    
4141
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4142
                           ignore_size=False):
4143
  """Prepare the block devices for an instance.
4144

4145
  This sets up the block devices on all nodes.
4146

4147
  @type lu: L{LogicalUnit}
4148
  @param lu: the logical unit on whose behalf we execute
4149
  @type instance: L{objects.Instance}
4150
  @param instance: the instance for whose disks we assemble
4151
  @type disks: list of L{objects.Disk} or None
4152
  @param disks: which disks to assemble (or all, if None)
4153
  @type ignore_secondaries: boolean
4154
  @param ignore_secondaries: if true, errors on secondary nodes
4155
      won't result in an error return from the function
4156
  @type ignore_size: boolean
4157
  @param ignore_size: if true, the current known size of the disk
4158
      will not be used during the disk activation, useful for cases
4159
      when the size is wrong
4160
  @return: False if the operation failed, otherwise a list of
4161
      (host, instance_visible_name, node_visible_name)
4162
      with the mapping from node devices to instance devices
4163

4164
  """
4165
  device_info = []
4166
  disks_ok = True
4167
  iname = instance.name
4168
  disks = _ExpandCheckDisks(instance, disks)
4169

    
4170
  # With the two passes mechanism we try to reduce the window of
4171
  # opportunity for the race condition of switching DRBD to primary
4172
  # before handshaking occured, but we do not eliminate it
4173

    
4174
  # The proper fix would be to wait (with some limits) until the
4175
  # connection has been made and drbd transitions from WFConnection
4176
  # into any other network-connected state (Connected, SyncTarget,
4177
  # SyncSource, etc.)
4178

    
4179
  # 1st pass, assemble on all nodes in secondary mode
4180
  for inst_disk in disks:
4181
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4182
      if ignore_size:
4183
        node_disk = node_disk.Copy()
4184
        node_disk.UnsetSize()
4185
      lu.cfg.SetDiskID(node_disk, node)
4186
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4187
      msg = result.fail_msg
4188
      if msg:
4189
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4190
                           " (is_primary=False, pass=1): %s",
4191
                           inst_disk.iv_name, node, msg)
4192
        if not ignore_secondaries:
4193
          disks_ok = False
4194

    
4195
  # FIXME: race condition on drbd migration to primary
4196

    
4197
  # 2nd pass, do only the primary node
4198
  for inst_disk in disks:
4199
    dev_path = None
4200

    
4201
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4202
      if node != instance.primary_node:
4203
        continue
4204
      if ignore_size:
4205
        node_disk = node_disk.Copy()
4206
        node_disk.UnsetSize()
4207
      lu.cfg.SetDiskID(node_disk, node)
4208
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4209
      msg = result.fail_msg
4210
      if msg:
4211
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4212
                           " (is_primary=True, pass=2): %s",
4213
                           inst_disk.iv_name, node, msg)
4214
        disks_ok = False
4215
      else:
4216
        dev_path = result.payload
4217

    
4218
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4219

    
4220
  # leave the disks configured for the primary node
4221
  # this is a workaround that would be fixed better by
4222
  # improving the logical/physical id handling
4223
  for disk in disks:
4224
    lu.cfg.SetDiskID(disk, instance.primary_node)
4225

    
4226
  return disks_ok, device_info
4227

    
4228

    
4229
def _StartInstanceDisks(lu, instance, force):
4230
  """Start the disks of an instance.
4231

4232
  """
4233
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4234
                                           ignore_secondaries=force)
4235
  if not disks_ok:
4236
    _ShutdownInstanceDisks(lu, instance)
4237
    if force is not None and not force:
4238
      lu.proc.LogWarning("", hint="If the message above refers to a"
4239
                         " secondary node,"
4240
                         " you can retry the operation using '--force'.")
4241
    raise errors.OpExecError("Disk consistency error")
4242

    
4243

    
4244
class LUDeactivateInstanceDisks(NoHooksLU):
4245
  """Shutdown an instance's disks.
4246

4247
  """
4248
  _OP_PARAMS = [
4249
    _PInstanceName,
4250
    ]
4251
  REQ_BGL = False
4252

    
4253
  def ExpandNames(self):
4254
    self._ExpandAndLockInstance()
4255
    self.needed_locks[locking.LEVEL_NODE] = []
4256
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4257

    
4258
  def DeclareLocks(self, level):
4259
    if level == locking.LEVEL_NODE:
4260
      self._LockInstancesNodes()
4261

    
4262
  def CheckPrereq(self):
4263
    """Check prerequisites.
4264

4265
    This checks that the instance is in the cluster.
4266

4267
    """
4268
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4269
    assert self.instance is not None, \
4270
      "Cannot retrieve locked instance %s" % self.op.instance_name
4271

    
4272
  def Exec(self, feedback_fn):
4273
    """Deactivate the disks
4274

4275
    """
4276
    instance = self.instance
4277
    _SafeShutdownInstanceDisks(self, instance)
4278

    
4279

    
4280
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4281
  """Shutdown block devices of an instance.
4282

4283
  This function checks if an instance is running, before calling
4284
  _ShutdownInstanceDisks.
4285

4286
  """
4287
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4288
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4289

    
4290

    
4291
def _ExpandCheckDisks(instance, disks):
4292
  """Return the instance disks selected by the disks list
4293

4294
  @type disks: list of L{objects.Disk} or None
4295
  @param disks: selected disks
4296
  @rtype: list of L{objects.Disk}
4297
  @return: selected instance disks to act on
4298

4299
  """
4300
  if disks is None:
4301
    return instance.disks
4302
  else:
4303
    if not set(disks).issubset(instance.disks):
4304
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4305
                                   " target instance")
4306
    return disks
4307

    
4308

    
4309
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4310
  """Shutdown block devices of an instance.
4311

4312
  This does the shutdown on all nodes of the instance.
4313

4314
  If the ignore_primary is false, errors on the primary node are
4315
  ignored.
4316

4317
  """
4318
  all_result = True
4319
  disks = _ExpandCheckDisks(instance, disks)
4320

    
4321
  for disk in disks:
4322
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4323
      lu.cfg.SetDiskID(top_disk, node)
4324
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4325
      msg = result.fail_msg
4326
      if msg:
4327
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4328
                      disk.iv_name, node, msg)
4329
        if not ignore_primary or node != instance.primary_node:
4330
          all_result = False
4331
  return all_result
4332

    
4333

    
4334
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4335
  """Checks if a node has enough free memory.
4336

4337
  This function check if a given node has the needed amount of free
4338
  memory. In case the node has less memory or we cannot get the
4339
  information from the node, this function raise an OpPrereqError
4340
  exception.
4341

4342
  @type lu: C{LogicalUnit}
4343
  @param lu: a logical unit from which we get configuration data
4344
  @type node: C{str}
4345
  @param node: the node to check
4346
  @type reason: C{str}
4347
  @param reason: string to use in the error message
4348
  @type requested: C{int}
4349
  @param requested: the amount of memory in MiB to check for
4350
  @type hypervisor_name: C{str}
4351
  @param hypervisor_name: the hypervisor to ask for memory stats
4352
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4353
      we cannot check the node
4354

4355
  """
4356
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4357
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4358
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4359
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4360
  if not isinstance(free_mem, int):
4361
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4362
                               " was '%s'" % (node, free_mem),
4363
                               errors.ECODE_ENVIRON)
4364
  if requested > free_mem:
4365
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4366
                               " needed %s MiB, available %s MiB" %
4367
                               (node, reason, requested, free_mem),
4368
                               errors.ECODE_NORES)
4369

    
4370

    
4371
def _CheckNodesFreeDisk(lu, nodenames, requested):
4372
  """Checks if nodes have enough free disk space in the default VG.
4373

4374
  This function check if all given nodes have the needed amount of
4375
  free disk. In case any node has less disk or we cannot get the
4376
  information from the node, this function raise an OpPrereqError
4377
  exception.
4378

4379
  @type lu: C{LogicalUnit}
4380
  @param lu: a logical unit from which we get configuration data
4381
  @type nodenames: C{list}
4382
  @param nodenames: the list of node names to check
4383
  @type requested: C{int}
4384
  @param requested: the amount of disk in MiB to check for
4385
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4386
      we cannot check the node
4387

4388
  """
4389
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4390
                                   lu.cfg.GetHypervisorType())
4391
  for node in nodenames:
4392
    info = nodeinfo[node]
4393
    info.Raise("Cannot get current information from node %s" % node,
4394
               prereq=True, ecode=errors.ECODE_ENVIRON)
4395
    vg_free = info.payload.get("vg_free", None)
4396
    if not isinstance(vg_free, int):
4397
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4398
                                 " result was '%s'" % (node, vg_free),
4399
                                 errors.ECODE_ENVIRON)
4400
    if requested > vg_free:
4401
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4402
                                 " required %d MiB, available %d MiB" %
4403
                                 (node, requested, vg_free),
4404
                                 errors.ECODE_NORES)
4405

    
4406

    
4407
class LUStartupInstance(LogicalUnit):
4408
  """Starts an instance.
4409

4410
  """
4411
  HPATH = "instance-start"
4412
  HTYPE = constants.HTYPE_INSTANCE
4413
  _OP_PARAMS = [
4414
    _PInstanceName,
4415
    _PForce,
4416
    ("hvparams", ht.EmptyDict, ht.TDict),
4417
    ("beparams", ht.EmptyDict, ht.TDict),
4418
    ]
4419
  REQ_BGL = False
4420

    
4421
  def CheckArguments(self):
4422
    # extra beparams
4423
    if self.op.beparams:
4424
      # fill the beparams dict
4425
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4426

    
4427
  def ExpandNames(self):
4428
    self._ExpandAndLockInstance()
4429

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

4433
    This runs on master, primary and secondary nodes of the instance.
4434

4435
    """
4436
    env = {
4437
      "FORCE": self.op.force,
4438
      }
4439
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4440
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4441
    return env, nl, nl
4442

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

4446
    This checks that the instance is in the cluster.
4447

4448
    """
4449
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4450
    assert self.instance is not None, \
4451
      "Cannot retrieve locked instance %s" % self.op.instance_name
4452

    
4453
    # extra hvparams
4454
    if self.op.hvparams:
4455
      # check hypervisor parameter syntax (locally)
4456
      cluster = self.cfg.GetClusterInfo()
4457
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4458
      filled_hvp = cluster.FillHV(instance)
4459
      filled_hvp.update(self.op.hvparams)
4460
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4461
      hv_type.CheckParameterSyntax(filled_hvp)
4462
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4463

    
4464
    _CheckNodeOnline(self, instance.primary_node)
4465

    
4466
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4467
    # check bridges existence
4468
    _CheckInstanceBridgesExist(self, instance)
4469

    
4470
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4471
                                              instance.name,
4472
                                              instance.hypervisor)
4473
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4474
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4475
    if not remote_info.payload: # not running already
4476
      _CheckNodeFreeMemory(self, instance.primary_node,
4477
                           "starting instance %s" % instance.name,
4478
                           bep[constants.BE_MEMORY], instance.hypervisor)
4479

    
4480
  def Exec(self, feedback_fn):
4481
    """Start the instance.
4482

4483
    """
4484
    instance = self.instance
4485
    force = self.op.force
4486

    
4487
    self.cfg.MarkInstanceUp(instance.name)
4488

    
4489
    node_current = instance.primary_node
4490

    
4491
    _StartInstanceDisks(self, instance, force)
4492

    
4493
    result = self.rpc.call_instance_start(node_current, instance,
4494
                                          self.op.hvparams, self.op.beparams)
4495
    msg = result.fail_msg
4496
    if msg:
4497
      _ShutdownInstanceDisks(self, instance)
4498
      raise errors.OpExecError("Could not start instance: %s" % msg)
4499

    
4500

    
4501
class LURebootInstance(LogicalUnit):
4502
  """Reboot an instance.
4503

4504
  """
4505
  HPATH = "instance-reboot"
4506
  HTYPE = constants.HTYPE_INSTANCE
4507
  _OP_PARAMS = [
4508
    _PInstanceName,
4509
    ("ignore_secondaries", False, ht.TBool),
4510
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4511
    _PShutdownTimeout,
4512
    ]
4513
  REQ_BGL = False
4514

    
4515
  def ExpandNames(self):
4516
    self._ExpandAndLockInstance()
4517

    
4518
  def BuildHooksEnv(self):
4519
    """Build hooks env.
4520

4521
    This runs on master, primary and secondary nodes of the instance.
4522

4523
    """
4524
    env = {
4525
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4526
      "REBOOT_TYPE": self.op.reboot_type,
4527
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4528
      }
4529
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4530
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4531
    return env, nl, nl
4532

    
4533
  def CheckPrereq(self):
4534
    """Check prerequisites.
4535

4536
    This checks that the instance is in the cluster.
4537

4538
    """
4539
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4540
    assert self.instance is not None, \
4541
      "Cannot retrieve locked instance %s" % self.op.instance_name
4542

    
4543
    _CheckNodeOnline(self, instance.primary_node)
4544

    
4545
    # check bridges existence
4546
    _CheckInstanceBridgesExist(self, instance)
4547

    
4548
  def Exec(self, feedback_fn):
4549
    """Reboot the instance.
4550

4551
    """
4552
    instance = self.instance
4553
    ignore_secondaries = self.op.ignore_secondaries
4554
    reboot_type = self.op.reboot_type
4555

    
4556
    node_current = instance.primary_node
4557

    
4558
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4559
                       constants.INSTANCE_REBOOT_HARD]:
4560
      for disk in instance.disks:
4561
        self.cfg.SetDiskID(disk, node_current)
4562
      result = self.rpc.call_instance_reboot(node_current, instance,
4563
                                             reboot_type,
4564
                                             self.op.shutdown_timeout)
4565
      result.Raise("Could not reboot instance")
4566
    else:
4567
      result = self.rpc.call_instance_shutdown(node_current, instance,
4568
                                               self.op.shutdown_timeout)
4569
      result.Raise("Could not shutdown instance for full reboot")
4570
      _ShutdownInstanceDisks(self, instance)
4571
      _StartInstanceDisks(self, instance, ignore_secondaries)
4572
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4573
      msg = result.fail_msg
4574
      if msg:
4575
        _ShutdownInstanceDisks(self, instance)
4576
        raise errors.OpExecError("Could not start instance for"
4577
                                 " full reboot: %s" % msg)
4578

    
4579
    self.cfg.MarkInstanceUp(instance.name)
4580

    
4581

    
4582
class LUShutdownInstance(LogicalUnit):
4583
  """Shutdown an instance.
4584

4585
  """
4586
  HPATH = "instance-stop"
4587
  HTYPE = constants.HTYPE_INSTANCE
4588
  _OP_PARAMS = [
4589
    _PInstanceName,
4590
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
4591
    ]
4592
  REQ_BGL = False
4593

    
4594
  def ExpandNames(self):
4595
    self._ExpandAndLockInstance()
4596

    
4597
  def BuildHooksEnv(self):
4598
    """Build hooks env.
4599

4600
    This runs on master, primary and secondary nodes of the instance.
4601

4602
    """
4603
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4604
    env["TIMEOUT"] = self.op.timeout
4605
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4606
    return env, nl, nl
4607

    
4608
  def CheckPrereq(self):
4609
    """Check prerequisites.
4610

4611
    This checks that the instance is in the cluster.
4612

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

    
4619
  def Exec(self, feedback_fn):
4620
    """Shutdown the instance.
4621

4622
    """
4623
    instance = self.instance
4624
    node_current = instance.primary_node
4625
    timeout = self.op.timeout
4626
    self.cfg.MarkInstanceDown(instance.name)
4627
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4628
    msg = result.fail_msg
4629
    if msg:
4630
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4631

    
4632
    _ShutdownInstanceDisks(self, instance)
4633

    
4634

    
4635
class LUReinstallInstance(LogicalUnit):
4636
  """Reinstall an instance.
4637

4638
  """
4639
  HPATH = "instance-reinstall"
4640
  HTYPE = constants.HTYPE_INSTANCE
4641
  _OP_PARAMS = [
4642
    _PInstanceName,
4643
    ("os_type", None, ht.TMaybeString),
4644
    ("force_variant", False, ht.TBool),
4645
    ]
4646
  REQ_BGL = False
4647

    
4648
  def ExpandNames(self):
4649
    self._ExpandAndLockInstance()
4650

    
4651
  def BuildHooksEnv(self):
4652
    """Build hooks env.
4653

4654
    This runs on master, primary and secondary nodes of the instance.
4655

4656
    """
4657
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4658
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4659
    return env, nl, nl
4660

    
4661
  def CheckPrereq(self):
4662
    """Check prerequisites.
4663

4664
    This checks that the instance is in the cluster and is not running.
4665

4666
    """
4667
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4668
    assert instance is not None, \
4669
      "Cannot retrieve locked instance %s" % self.op.instance_name
4670
    _CheckNodeOnline(self, instance.primary_node)
4671

    
4672
    if instance.disk_template == constants.DT_DISKLESS:
4673
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4674
                                 self.op.instance_name,
4675
                                 errors.ECODE_INVAL)
4676
    _CheckInstanceDown(self, instance, "cannot reinstall")
4677

    
4678
    if self.op.os_type is not None:
4679
      # OS verification
4680
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4681
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4682

    
4683
    self.instance = instance
4684

    
4685
  def Exec(self, feedback_fn):
4686
    """Reinstall the instance.
4687

4688
    """
4689
    inst = self.instance
4690

    
4691
    if self.op.os_type is not None:
4692
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4693
      inst.os = self.op.os_type
4694
      self.cfg.Update(inst, feedback_fn)
4695

    
4696
    _StartInstanceDisks(self, inst, None)
4697
    try:
4698
      feedback_fn("Running the instance OS create scripts...")
4699
      # FIXME: pass debug option from opcode to backend
4700
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4701
                                             self.op.debug_level)
4702
      result.Raise("Could not install OS for instance %s on node %s" %
4703
                   (inst.name, inst.primary_node))
4704
    finally:
4705
      _ShutdownInstanceDisks(self, inst)
4706

    
4707

    
4708
class LURecreateInstanceDisks(LogicalUnit):
4709
  """Recreate an instance's missing disks.
4710

4711
  """
4712
  HPATH = "instance-recreate-disks"
4713
  HTYPE = constants.HTYPE_INSTANCE
4714
  _OP_PARAMS = [
4715
    _PInstanceName,
4716
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
4717
    ]
4718
  REQ_BGL = False
4719

    
4720
  def ExpandNames(self):
4721
    self._ExpandAndLockInstance()
4722

    
4723
  def BuildHooksEnv(self):
4724
    """Build hooks env.
4725

4726
    This runs on master, primary and secondary nodes of the instance.
4727

4728
    """
4729
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4730
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4731
    return env, nl, nl
4732

    
4733
  def CheckPrereq(self):
4734
    """Check prerequisites.
4735

4736
    This checks that the instance is in the cluster and is not running.
4737

4738
    """
4739
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4740
    assert instance is not None, \
4741
      "Cannot retrieve locked instance %s" % self.op.instance_name
4742
    _CheckNodeOnline(self, instance.primary_node)
4743

    
4744
    if instance.disk_template == constants.DT_DISKLESS:
4745
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4746
                                 self.op.instance_name, errors.ECODE_INVAL)
4747
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4748

    
4749
    if not self.op.disks:
4750
      self.op.disks = range(len(instance.disks))
4751
    else:
4752
      for idx in self.op.disks:
4753
        if idx >= len(instance.disks):
4754
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4755
                                     errors.ECODE_INVAL)
4756

    
4757
    self.instance = instance
4758

    
4759
  def Exec(self, feedback_fn):
4760
    """Recreate the disks.
4761

4762
    """
4763
    to_skip = []
4764
    for idx, _ in enumerate(self.instance.disks):
4765
      if idx not in self.op.disks: # disk idx has not been passed in
4766
        to_skip.append(idx)
4767
        continue
4768

    
4769
    _CreateDisks(self, self.instance, to_skip=to_skip)
4770

    
4771

    
4772
class LURenameInstance(LogicalUnit):
4773
  """Rename an instance.
4774

4775
  """
4776
  HPATH = "instance-rename"
4777
  HTYPE = constants.HTYPE_INSTANCE
4778
  _OP_PARAMS = [
4779
    _PInstanceName,
4780
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
4781
    ("ip_check", False, ht.TBool),
4782
    ("name_check", True, ht.TBool),
4783
    ]
4784

    
4785
  def CheckArguments(self):
4786
    """Check arguments.
4787

4788
    """
4789
    if self.op.ip_check and not self.op.name_check:
4790
      # TODO: make the ip check more flexible and not depend on the name check
4791
      raise errors.OpPrereqError("Cannot do ip check without a name check",
4792
                                 errors.ECODE_INVAL)
4793

    
4794
  def BuildHooksEnv(self):
4795
    """Build hooks env.
4796

4797
    This runs on master, primary and secondary nodes of the instance.
4798

4799
    """
4800
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4801
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4802
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4803
    return env, nl, nl
4804

    
4805
  def CheckPrereq(self):
4806
    """Check prerequisites.
4807

4808
    This checks that the instance is in the cluster and is not running.
4809

4810
    """
4811
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4812
                                                self.op.instance_name)
4813
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4814
    assert instance is not None
4815
    _CheckNodeOnline(self, instance.primary_node)
4816
    _CheckInstanceDown(self, instance, "cannot rename")
4817
    self.instance = instance
4818

    
4819
    new_name = self.op.new_name
4820
    if self.op.name_check:
4821
      hostname = netutils.GetHostname(name=new_name)
4822
      new_name = self.op.new_name = hostname.name
4823
      if (self.op.ip_check and
4824
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
4825
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4826
                                   (hostname.ip, new_name),
4827
                                   errors.ECODE_NOTUNIQUE)
4828

    
4829
    instance_list = self.cfg.GetInstanceList()
4830
    if new_name in instance_list:
4831
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4832
                                 new_name, errors.ECODE_EXISTS)
4833

    
4834
  def Exec(self, feedback_fn):
4835
    """Reinstall the instance.
4836

4837
    """
4838
    inst = self.instance
4839
    old_name = inst.name
4840

    
4841
    if inst.disk_template == constants.DT_FILE:
4842
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4843

    
4844
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4845
    # Change the instance lock. This is definitely safe while we hold the BGL
4846
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4847
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4848

    
4849
    # re-read the instance from the configuration after rename
4850
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4851

    
4852
    if inst.disk_template == constants.DT_FILE:
4853
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4854
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4855
                                                     old_file_storage_dir,
4856
                                                     new_file_storage_dir)
4857
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4858
                   " (but the instance has been renamed in Ganeti)" %
4859
                   (inst.primary_node, old_file_storage_dir,
4860
                    new_file_storage_dir))
4861

    
4862
    _StartInstanceDisks(self, inst, None)
4863
    try:
4864
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4865
                                                 old_name, self.op.debug_level)
4866
      msg = result.fail_msg
4867
      if msg:
4868
        msg = ("Could not run OS rename script for instance %s on node %s"
4869
               " (but the instance has been renamed in Ganeti): %s" %
4870
               (inst.name, inst.primary_node, msg))
4871
        self.proc.LogWarning(msg)
4872
    finally:
4873
      _ShutdownInstanceDisks(self, inst)
4874

    
4875
    return inst.name
4876

    
4877

    
4878
class LURemoveInstance(LogicalUnit):
4879
  """Remove an instance.
4880

4881
  """
4882
  HPATH = "instance-remove"
4883
  HTYPE = constants.HTYPE_INSTANCE
4884
  _OP_PARAMS = [
4885
    _PInstanceName,
4886
    ("ignore_failures", False, ht.TBool),
4887
    _PShutdownTimeout,
4888
    ]
4889
  REQ_BGL = False
4890

    
4891
  def ExpandNames(self):
4892
    self._ExpandAndLockInstance()
4893
    self.needed_locks[locking.LEVEL_NODE] = []
4894
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4895

    
4896
  def DeclareLocks(self, level):
4897
    if level == locking.LEVEL_NODE:
4898
      self._LockInstancesNodes()
4899

    
4900
  def BuildHooksEnv(self):
4901
    """Build hooks env.
4902

4903
    This runs on master, primary and secondary nodes of the instance.
4904

4905
    """
4906
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4907
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4908
    nl = [self.cfg.GetMasterNode()]
4909
    nl_post = list(self.instance.all_nodes) + nl
4910
    return env, nl, nl_post
4911

    
4912
  def CheckPrereq(self):
4913
    """Check prerequisites.
4914

4915
    This checks that the instance is in the cluster.
4916

4917
    """
4918
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4919
    assert self.instance is not None, \
4920
      "Cannot retrieve locked instance %s" % self.op.instance_name
4921

    
4922
  def Exec(self, feedback_fn):
4923
    """Remove the instance.
4924

4925
    """
4926
    instance = self.instance
4927
    logging.info("Shutting down instance %s on node %s",
4928
                 instance.name, instance.primary_node)
4929

    
4930
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4931
                                             self.op.shutdown_timeout)
4932
    msg = result.fail_msg
4933
    if msg:
4934
      if self.op.ignore_failures:
4935
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4936
      else:
4937
        raise errors.OpExecError("Could not shutdown instance %s on"
4938
                                 " node %s: %s" %
4939
                                 (instance.name, instance.primary_node, msg))
4940

    
4941
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
4942

    
4943

    
4944
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
4945
  """Utility function to remove an instance.
4946

4947
  """
4948
  logging.info("Removing block devices for instance %s", instance.name)
4949

    
4950
  if not _RemoveDisks(lu, instance):
4951
    if not ignore_failures:
4952
      raise errors.OpExecError("Can't remove instance's disks")
4953
    feedback_fn("Warning: can't remove instance's disks")
4954

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

    
4957
  lu.cfg.RemoveInstance(instance.name)
4958

    
4959
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
4960
    "Instance lock removal conflict"
4961

    
4962
  # Remove lock for the instance
4963
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4964

    
4965

    
4966
class LUQueryInstances(NoHooksLU):
4967
  """Logical unit for querying instances.
4968

4969
  """
4970
  # pylint: disable-msg=W0142
4971
  _OP_PARAMS = [
4972
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
4973
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
4974
    ("use_locking", False, ht.TBool),
4975
    ]
4976
  REQ_BGL = False
4977
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4978
                    "serial_no", "ctime", "mtime", "uuid"]
4979
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4980
                                    "admin_state",
4981
                                    "disk_template", "ip", "mac", "bridge",
4982
                                    "nic_mode", "nic_link",
4983
                                    "sda_size", "sdb_size", "vcpus", "tags",
4984
                                    "network_port", "beparams",
4985
                                    r"(disk)\.(size)/([0-9]+)",
4986
                                    r"(disk)\.(sizes)", "disk_usage",
4987
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4988
                                    r"(nic)\.(bridge)/([0-9]+)",
4989
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4990
                                    r"(disk|nic)\.(count)",
4991
                                    "hvparams", "custom_hvparams",
4992
                                    "custom_beparams", "custom_nicparams",
4993
                                    ] + _SIMPLE_FIELDS +
4994
                                  ["hv/%s" % name
4995
                                   for name in constants.HVS_PARAMETERS
4996
                                   if name not in constants.HVC_GLOBALS] +
4997
                                  ["be/%s" % name
4998
                                   for name in constants.BES_PARAMETERS])
4999
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5000
                                   "oper_ram",
5001
                                   "oper_vcpus",
5002
                                   "status")
5003

    
5004

    
5005
  def CheckArguments(self):
5006
    _CheckOutputFields(static=self._FIELDS_STATIC,
5007
                       dynamic=self._FIELDS_DYNAMIC,
5008
                       selected=self.op.output_fields)
5009

    
5010
  def ExpandNames(self):
5011
    self.needed_locks = {}
5012
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5013
    self.share_locks[locking.LEVEL_NODE] = 1
5014

    
5015
    if self.op.names:
5016
      self.wanted = _GetWantedInstances(self, self.op.names)
5017
    else:
5018
      self.wanted = locking.ALL_SET
5019

    
5020
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5021
    self.do_locking = self.do_node_query and self.op.use_locking
5022
    if self.do_locking:
5023
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5024
      self.needed_locks[locking.LEVEL_NODE] = []
5025
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5026

    
5027
  def DeclareLocks(self, level):
5028
    if level == locking.LEVEL_NODE and self.do_locking:
5029
      self._LockInstancesNodes()
5030

    
5031
  def Exec(self, feedback_fn):
5032
    """Computes the list of nodes and their attributes.
5033

5034
    """
5035
    # pylint: disable-msg=R0912
5036
    # way too many branches here
5037
    all_info = self.cfg.GetAllInstancesInfo()
5038
    if self.wanted == locking.ALL_SET:
5039
      # caller didn't specify instance names, so ordering is not important
5040
      if self.do_locking:
5041
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5042
      else:
5043
        instance_names = all_info.keys()
5044
      instance_names = utils.NiceSort(instance_names)
5045
    else:
5046
      # caller did specify names, so we must keep the ordering
5047
      if self.do_locking:
5048
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5049
      else:
5050
        tgt_set = all_info.keys()
5051
      missing = set(self.wanted).difference(tgt_set)
5052
      if missing:
5053
        raise errors.OpExecError("Some instances were removed before"
5054
                                 " retrieving their data: %s" % missing)
5055
      instance_names = self.wanted
5056

    
5057
    instance_list = [all_info[iname] for iname in instance_names]
5058

    
5059
    # begin data gathering
5060

    
5061
    nodes = frozenset([inst.primary_node for inst in instance_list])
5062
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5063

    
5064
    bad_nodes = []
5065
    off_nodes = []
5066
    if self.do_node_query:
5067
      live_data = {}
5068
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5069
      for name in nodes:
5070
        result = node_data[name]
5071
        if result.offline:
5072
          # offline nodes will be in both lists
5073
          off_nodes.append(name)
5074
        if result.fail_msg:
5075
          bad_nodes.append(name)
5076
        else:
5077
          if result.payload:
5078
            live_data.update(result.payload)
5079
          # else no instance is alive
5080
    else:
5081
      live_data = dict([(name, {}) for name in instance_names])
5082

    
5083
    # end data gathering
5084

    
5085
    HVPREFIX = "hv/"
5086
    BEPREFIX = "be/"
5087
    output = []
5088
    cluster = self.cfg.GetClusterInfo()
5089
    for instance in instance_list:
5090
      iout = []
5091
      i_hv = cluster.FillHV(instance, skip_globals=True)
5092
      i_be = cluster.FillBE(instance)
5093
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5094
      for field in self.op.output_fields:
5095
        st_match = self._FIELDS_STATIC.Matches(field)
5096
        if field in self._SIMPLE_FIELDS:
5097
          val = getattr(instance, field)
5098
        elif field == "pnode":
5099
          val = instance.primary_node
5100
        elif field == "snodes":
5101
          val = list(instance.secondary_nodes)
5102
        elif field == "admin_state":
5103
          val = instance.admin_up
5104
        elif field == "oper_state":
5105
          if instance.primary_node in bad_nodes:
5106
            val = None
5107
          else:
5108
            val = bool(live_data.get(instance.name))
5109
        elif field == "status":
5110
          if instance.primary_node in off_nodes:
5111
            val = "ERROR_nodeoffline"
5112
          elif instance.primary_node in bad_nodes:
5113
            val = "ERROR_nodedown"
5114
          else:
5115
            running = bool(live_data.get(instance.name))
5116
            if running:
5117
              if instance.admin_up:
5118
                val = "running"
5119
              else:
5120
                val = "ERROR_up"
5121
            else:
5122
              if instance.admin_up:
5123
                val = "ERROR_down"
5124
              else:
5125
                val = "ADMIN_down"
5126
        elif field == "oper_ram":
5127
          if instance.primary_node in bad_nodes:
5128
            val = None
5129
          elif instance.name in live_data:
5130
            val = live_data[instance.name].get("memory", "?")
5131
          else:
5132
            val = "-"
5133
        elif field == "oper_vcpus":
5134
          if instance.primary_node in bad_nodes:
5135
            val = None
5136
          elif instance.name in live_data:
5137
            val = live_data[instance.name].get("vcpus", "?")
5138
          else:
5139
            val = "-"
5140
        elif field == "vcpus":
5141
          val = i_be[constants.BE_VCPUS]
5142
        elif field == "disk_template":
5143
          val = instance.disk_template
5144
        elif field == "ip":
5145
          if instance.nics:
5146
            val = instance.nics[0].ip
5147
          else:
5148
            val = None
5149
        elif field == "nic_mode":
5150
          if instance.nics:
5151
            val = i_nicp[0][constants.NIC_MODE]
5152
          else:
5153
            val = None
5154
        elif field == "nic_link":
5155
          if instance.nics:
5156
            val = i_nicp[0][constants.NIC_LINK]
5157
          else:
5158
            val = None
5159
        elif field == "bridge":
5160
          if (instance.nics and
5161
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5162
            val = i_nicp[0][constants.NIC_LINK]
5163
          else:
5164
            val = None
5165
        elif field == "mac":
5166
          if instance.nics:
5167
            val = instance.nics[0].mac
5168
          else:
5169
            val = None
5170
        elif field == "custom_nicparams":
5171
          val = [nic.nicparams for nic in instance.nics]
5172
        elif field == "sda_size" or field == "sdb_size":
5173
          idx = ord(field[2]) - ord('a')
5174
          try:
5175
            val = instance.FindDisk(idx).size
5176
          except errors.OpPrereqError:
5177
            val = None
5178
        elif field == "disk_usage": # total disk usage per node
5179
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5180
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5181
        elif field == "tags":
5182
          val = list(instance.GetTags())
5183
        elif field == "custom_hvparams":
5184
          val = instance.hvparams # not filled!
5185
        elif field == "hvparams":
5186
          val = i_hv
5187
        elif (field.startswith(HVPREFIX) and
5188
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5189
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5190
          val = i_hv.get(field[len(HVPREFIX):], None)
5191
        elif field == "custom_beparams":
5192
          val = instance.beparams
5193
        elif field == "beparams":
5194
          val = i_be
5195
        elif (field.startswith(BEPREFIX) and
5196
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5197
          val = i_be.get(field[len(BEPREFIX):], None)
5198
        elif st_match and st_match.groups():
5199
          # matches a variable list
5200
          st_groups = st_match.groups()
5201
          if st_groups and st_groups[0] == "disk":
5202
            if st_groups[1] == "count":
5203
              val = len(instance.disks)
5204
            elif st_groups[1] == "sizes":
5205
              val = [disk.size for disk in instance.disks]
5206
            elif st_groups[1] == "size":
5207
              try:
5208
                val = instance.FindDisk(st_groups[2]).size
5209
              except errors.OpPrereqError:
5210
                val = None
5211
            else:
5212
              assert False, "Unhandled disk parameter"
5213
          elif st_groups[0] == "nic":
5214
            if st_groups[1] == "count":
5215
              val = len(instance.nics)
5216
            elif st_groups[1] == "macs":
5217
              val = [nic.mac for nic in instance.nics]
5218
            elif st_groups[1] == "ips":
5219
              val = [nic.ip for nic in instance.nics]
5220
            elif st_groups[1] == "modes":
5221
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5222
            elif st_groups[1] == "links":
5223
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5224
            elif st_groups[1] == "bridges":
5225
              val = []
5226
              for nicp in i_nicp:
5227
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5228
                  val.append(nicp[constants.NIC_LINK])
5229
                else:
5230
                  val.append(None)
5231
            else:
5232
              # index-based item
5233
              nic_idx = int(st_groups[2])
5234
              if nic_idx >= len(instance.nics):
5235
                val = None
5236
              else:
5237
                if st_groups[1] == "mac":
5238
                  val = instance.nics[nic_idx].mac
5239
                elif st_groups[1] == "ip":
5240
                  val = instance.nics[nic_idx].ip
5241
                elif st_groups[1] == "mode":
5242
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5243
                elif st_groups[1] == "link":
5244
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5245
                elif st_groups[1] == "bridge":
5246
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5247
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5248
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5249
                  else:
5250
                    val = None
5251
                else:
5252
                  assert False, "Unhandled NIC parameter"
5253
          else:
5254
            assert False, ("Declared but unhandled variable parameter '%s'" %
5255
                           field)
5256
        else:
5257
          assert False, "Declared but unhandled parameter '%s'" % field
5258
        iout.append(val)
5259
      output.append(iout)
5260

    
5261
    return output
5262

    
5263

    
5264
class LUFailoverInstance(LogicalUnit):
5265
  """Failover an instance.
5266

5267
  """
5268
  HPATH = "instance-failover"
5269
  HTYPE = constants.HTYPE_INSTANCE
5270
  _OP_PARAMS = [
5271
    _PInstanceName,
5272
    ("ignore_consistency", False, ht.TBool),
5273
    _PShutdownTimeout,
5274
    ]
5275
  REQ_BGL = False
5276

    
5277
  def ExpandNames(self):
5278
    self._ExpandAndLockInstance()
5279
    self.needed_locks[locking.LEVEL_NODE] = []
5280
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5281

    
5282
  def DeclareLocks(self, level):
5283
    if level == locking.LEVEL_NODE:
5284
      self._LockInstancesNodes()
5285

    
5286
  def BuildHooksEnv(self):
5287
    """Build hooks env.
5288

5289
    This runs on master, primary and secondary nodes of the instance.
5290

5291
    """
5292
    instance = self.instance
5293
    source_node = instance.primary_node
5294
    target_node = instance.secondary_nodes[0]
5295
    env = {
5296
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5297
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5298
      "OLD_PRIMARY": source_node,
5299
      "OLD_SECONDARY": target_node,
5300
      "NEW_PRIMARY": target_node,
5301
      "NEW_SECONDARY": source_node,
5302
      }
5303
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5304
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5305
    nl_post = list(nl)
5306
    nl_post.append(source_node)
5307
    return env, nl, nl_post
5308

    
5309
  def CheckPrereq(self):
5310
    """Check prerequisites.
5311

5312
    This checks that the instance is in the cluster.
5313

5314
    """
5315
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5316
    assert self.instance is not None, \
5317
      "Cannot retrieve locked instance %s" % self.op.instance_name
5318

    
5319
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5320
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5321
      raise errors.OpPrereqError("Instance's disk layout is not"
5322
                                 " network mirrored, cannot failover.",
5323
                                 errors.ECODE_STATE)
5324

    
5325
    secondary_nodes = instance.secondary_nodes
5326
    if not secondary_nodes:
5327
      raise errors.ProgrammerError("no secondary node but using "
5328
                                   "a mirrored disk template")
5329

    
5330
    target_node = secondary_nodes[0]
5331
    _CheckNodeOnline(self, target_node)
5332
    _CheckNodeNotDrained(self, target_node)
5333
    if instance.admin_up:
5334
      # check memory requirements on the secondary node
5335
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5336
                           instance.name, bep[constants.BE_MEMORY],
5337
                           instance.hypervisor)
5338
    else:
5339
      self.LogInfo("Not checking memory on the secondary node as"
5340
                   " instance will not be started")
5341

    
5342
    # check bridge existance
5343
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5344

    
5345
  def Exec(self, feedback_fn):
5346
    """Failover an instance.
5347

5348
    The failover is done by shutting it down on its present node and
5349
    starting it on the secondary.
5350

5351
    """
5352
    instance = self.instance
5353
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5354

    
5355
    source_node = instance.primary_node
5356
    target_node = instance.secondary_nodes[0]
5357

    
5358
    if instance.admin_up:
5359
      feedback_fn("* checking disk consistency between source and target")
5360
      for dev in instance.disks:
5361
        # for drbd, these are drbd over lvm
5362
        if not _CheckDiskConsistency(self, dev, target_node, False):
5363
          if not self.op.ignore_consistency:
5364
            raise errors.OpExecError("Disk %s is degraded on target node,"
5365
                                     " aborting failover." % dev.iv_name)
5366
    else:
5367
      feedback_fn("* not checking disk consistency as instance is not running")
5368

    
5369
    feedback_fn("* shutting down instance on source node")
5370
    logging.info("Shutting down instance %s on node %s",
5371
                 instance.name, source_node)
5372

    
5373
    result = self.rpc.call_instance_shutdown(source_node, instance,
5374
                                             self.op.shutdown_timeout)
5375
    msg = result.fail_msg
5376
    if msg:
5377
      if self.op.ignore_consistency or primary_node.offline:
5378
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5379
                             " Proceeding anyway. Please make sure node"
5380
                             " %s is down. Error details: %s",
5381
                             instance.name, source_node, source_node, msg)
5382
      else:
5383
        raise errors.OpExecError("Could not shutdown instance %s on"
5384
                                 " node %s: %s" %
5385
                                 (instance.name, source_node, msg))
5386

    
5387
    feedback_fn("* deactivating the instance's disks on source node")
5388
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5389
      raise errors.OpExecError("Can't shut down the instance's disks.")
5390

    
5391
    instance.primary_node = target_node
5392
    # distribute new instance config to the other nodes
5393
    self.cfg.Update(instance, feedback_fn)
5394

    
5395
    # Only start the instance if it's marked as up
5396
    if instance.admin_up:
5397
      feedback_fn("* activating the instance's disks on target node")
5398
      logging.info("Starting instance %s on node %s",
5399
                   instance.name, target_node)
5400

    
5401
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5402
                                           ignore_secondaries=True)
5403
      if not disks_ok:
5404
        _ShutdownInstanceDisks(self, instance)
5405
        raise errors.OpExecError("Can't activate the instance's disks")
5406

    
5407
      feedback_fn("* starting the instance on the target node")
5408
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5409
      msg = result.fail_msg
5410
      if msg:
5411
        _ShutdownInstanceDisks(self, instance)
5412
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5413
                                 (instance.name, target_node, msg))
5414

    
5415

    
5416
class LUMigrateInstance(LogicalUnit):
5417
  """Migrate an instance.
5418

5419
  This is migration without shutting down, compared to the failover,
5420
  which is done with shutdown.
5421

5422
  """
5423
  HPATH = "instance-migrate"
5424
  HTYPE = constants.HTYPE_INSTANCE
5425
  _OP_PARAMS = [
5426
    _PInstanceName,
5427
    _PMigrationMode,
5428
    _PMigrationLive,
5429
    ("cleanup", False, ht.TBool),
5430
    ]
5431

    
5432
  REQ_BGL = False
5433

    
5434
  def ExpandNames(self):
5435
    self._ExpandAndLockInstance()
5436

    
5437
    self.needed_locks[locking.LEVEL_NODE] = []
5438
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5439

    
5440
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5441
                                       self.op.cleanup)
5442
    self.tasklets = [self._migrater]
5443

    
5444
  def DeclareLocks(self, level):
5445
    if level == locking.LEVEL_NODE:
5446
      self._LockInstancesNodes()
5447

    
5448
  def BuildHooksEnv(self):
5449
    """Build hooks env.
5450

5451
    This runs on master, primary and secondary nodes of the instance.
5452

5453
    """
5454
    instance = self._migrater.instance
5455
    source_node = instance.primary_node
5456
    target_node = instance.secondary_nodes[0]
5457
    env = _BuildInstanceHookEnvByObject(self, instance)
5458
    env["MIGRATE_LIVE"] = self._migrater.live
5459
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5460
    env.update({
5461
        "OLD_PRIMARY": source_node,
5462
        "OLD_SECONDARY": target_node,
5463
        "NEW_PRIMARY": target_node,
5464
        "NEW_SECONDARY": source_node,
5465
        })
5466
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5467
    nl_post = list(nl)
5468
    nl_post.append(source_node)
5469
    return env, nl, nl_post
5470

    
5471

    
5472
class LUMoveInstance(LogicalUnit):
5473
  """Move an instance by data-copying.
5474

5475
  """
5476
  HPATH = "instance-move"
5477
  HTYPE = constants.HTYPE_INSTANCE
5478
  _OP_PARAMS = [
5479
    _PInstanceName,
5480
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5481
    _PShutdownTimeout,
5482
    ]
5483
  REQ_BGL = False
5484

    
5485
  def ExpandNames(self):
5486
    self._ExpandAndLockInstance()
5487
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5488
    self.op.target_node = target_node
5489
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5490
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5491

    
5492
  def DeclareLocks(self, level):
5493
    if level == locking.LEVEL_NODE:
5494
      self._LockInstancesNodes(primary_only=True)
5495

    
5496
  def BuildHooksEnv(self):
5497
    """Build hooks env.
5498

5499
    This runs on master, primary and secondary nodes of the instance.
5500

5501
    """
5502
    env = {
5503
      "TARGET_NODE": self.op.target_node,
5504
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5505
      }
5506
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5507
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5508
                                       self.op.target_node]
5509
    return env, nl, nl
5510

    
5511
  def CheckPrereq(self):
5512
    """Check prerequisites.
5513

5514
    This checks that the instance is in the cluster.
5515

5516
    """
5517
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5518
    assert self.instance is not None, \
5519
      "Cannot retrieve locked instance %s" % self.op.instance_name
5520

    
5521
    node = self.cfg.GetNodeInfo(self.op.target_node)
5522
    assert node is not None, \
5523
      "Cannot retrieve locked node %s" % self.op.target_node
5524

    
5525
    self.target_node = target_node = node.name
5526

    
5527
    if target_node == instance.primary_node:
5528
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5529
                                 (instance.name, target_node),
5530
                                 errors.ECODE_STATE)
5531

    
5532
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5533

    
5534
    for idx, dsk in enumerate(instance.disks):
5535
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5536
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5537
                                   " cannot copy" % idx, errors.ECODE_STATE)
5538

    
5539
    _CheckNodeOnline(self, target_node)
5540
    _CheckNodeNotDrained(self, target_node)
5541

    
5542
    if instance.admin_up:
5543
      # check memory requirements on the secondary node
5544
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5545
                           instance.name, bep[constants.BE_MEMORY],
5546
                           instance.hypervisor)
5547
    else:
5548
      self.LogInfo("Not checking memory on the secondary node as"
5549
                   " instance will not be started")
5550

    
5551
    # check bridge existance
5552
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5553

    
5554
  def Exec(self, feedback_fn):
5555
    """Move an instance.
5556

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

5560
    """
5561
    instance = self.instance
5562

    
5563
    source_node = instance.primary_node
5564
    target_node = self.target_node
5565

    
5566
    self.LogInfo("Shutting down instance %s on source node %s",
5567
                 instance.name, source_node)
5568

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

    
5583
    # create the target disks
5584
    try:
5585
      _CreateDisks(self, instance, target_node=target_node)
5586
    except errors.OpExecError:
5587
      self.LogWarning("Device creation failed, reverting...")
5588
      try:
5589
        _RemoveDisks(self, instance, target_node=target_node)
5590
      finally:
5591
        self.cfg.ReleaseDRBDMinors(instance.name)
5592
        raise
5593

    
5594
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5595

    
5596
    errs = []
5597
    # activate, get path, copy the data over
5598
    for idx, disk in enumerate(instance.disks):
5599
      self.LogInfo("Copying data for disk %d", idx)
5600
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5601
                                               instance.name, True)
5602
      if result.fail_msg:
5603
        self.LogWarning("Can't assemble newly created disk %d: %s",
5604
                        idx, result.fail_msg)
5605
        errs.append(result.fail_msg)
5606
        break
5607
      dev_path = result.payload
5608
      result = self.rpc.call_blockdev_export(source_node, disk,
5609
                                             target_node, dev_path,
5610
                                             cluster_name)
5611
      if result.fail_msg:
5612
        self.LogWarning("Can't copy data over for disk %d: %s",
5613
                        idx, result.fail_msg)
5614
        errs.append(result.fail_msg)
5615
        break
5616

    
5617
    if errs:
5618
      self.LogWarning("Some disks failed to copy, aborting")
5619
      try:
5620
        _RemoveDisks(self, instance, target_node=target_node)
5621
      finally:
5622
        self.cfg.ReleaseDRBDMinors(instance.name)
5623
        raise errors.OpExecError("Errors during disk copy: %s" %
5624
                                 (",".join(errs),))
5625

    
5626
    instance.primary_node = target_node
5627
    self.cfg.Update(instance, feedback_fn)
5628

    
5629
    self.LogInfo("Removing the disks on the original node")
5630
    _RemoveDisks(self, instance, target_node=source_node)
5631

    
5632
    # Only start the instance if it's marked as up
5633
    if instance.admin_up:
5634
      self.LogInfo("Starting instance %s on node %s",
5635
                   instance.name, target_node)
5636

    
5637
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5638
                                           ignore_secondaries=True)
5639
      if not disks_ok:
5640
        _ShutdownInstanceDisks(self, instance)
5641
        raise errors.OpExecError("Can't activate the instance's disks")
5642

    
5643
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5644
      msg = result.fail_msg
5645
      if msg:
5646
        _ShutdownInstanceDisks(self, instance)
5647
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5648
                                 (instance.name, target_node, msg))
5649

    
5650

    
5651
class LUMigrateNode(LogicalUnit):
5652
  """Migrate all instances from a node.
5653

5654
  """
5655
  HPATH = "node-migrate"
5656
  HTYPE = constants.HTYPE_NODE
5657
  _OP_PARAMS = [
5658
    _PNodeName,
5659
    _PMigrationMode,
5660
    _PMigrationLive,
5661
    ]
5662
  REQ_BGL = False
5663

    
5664
  def ExpandNames(self):
5665
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5666

    
5667
    self.needed_locks = {
5668
      locking.LEVEL_NODE: [self.op.node_name],
5669
      }
5670

    
5671
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5672

    
5673
    # Create tasklets for migrating instances for all instances on this node
5674
    names = []
5675
    tasklets = []
5676

    
5677
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5678
      logging.debug("Migrating instance %s", inst.name)
5679
      names.append(inst.name)
5680

    
5681
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5682

    
5683
    self.tasklets = tasklets
5684

    
5685
    # Declare instance locks
5686
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5687

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

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

5695
    This runs on the master, the primary and all the secondaries.
5696

5697
    """
5698
    env = {
5699
      "NODE_NAME": self.op.node_name,
5700
      }
5701

    
5702
    nl = [self.cfg.GetMasterNode()]
5703

    
5704
    return (env, nl, nl)
5705

    
5706

    
5707
class TLMigrateInstance(Tasklet):
5708
  """Tasklet class for instance migration.
5709

5710
  @type live: boolean
5711
  @ivar live: whether the migration will be done live or non-live;
5712
      this variable is initalized only after CheckPrereq has run
5713

5714
  """
5715
  def __init__(self, lu, instance_name, cleanup):
5716
    """Initializes this class.
5717

5718
    """
5719
    Tasklet.__init__(self, lu)
5720

    
5721
    # Parameters
5722
    self.instance_name = instance_name
5723
    self.cleanup = cleanup
5724
    self.live = False # will be overridden later
5725

    
5726
  def CheckPrereq(self):
5727
    """Check prerequisites.
5728

5729
    This checks that the instance is in the cluster.
5730

5731
    """
5732
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5733
    instance = self.cfg.GetInstanceInfo(instance_name)
5734
    assert instance is not None
5735

    
5736
    if instance.disk_template != constants.DT_DRBD8:
5737
      raise errors.OpPrereqError("Instance's disk layout is not"
5738
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5739

    
5740
    secondary_nodes = instance.secondary_nodes
5741
    if not secondary_nodes:
5742
      raise errors.ConfigurationError("No secondary node but using"
5743
                                      " drbd8 disk template")
5744

    
5745
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5746

    
5747
    target_node = secondary_nodes[0]
5748
    # check memory requirements on the secondary node
5749
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5750
                         instance.name, i_be[constants.BE_MEMORY],
5751
                         instance.hypervisor)
5752

    
5753
    # check bridge existance
5754
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5755

    
5756
    if not self.cleanup:
5757
      _CheckNodeNotDrained(self.lu, target_node)
5758
      result = self.rpc.call_instance_migratable(instance.primary_node,
5759
                                                 instance)
5760
      result.Raise("Can't migrate, please use failover",
5761
                   prereq=True, ecode=errors.ECODE_STATE)
5762

    
5763
    self.instance = instance
5764

    
5765
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5766
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5767
                                 " parameters are accepted",
5768
                                 errors.ECODE_INVAL)
5769
    if self.lu.op.live is not None:
5770
      if self.lu.op.live:
5771
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5772
      else:
5773
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
5774
      # reset the 'live' parameter to None so that repeated
5775
      # invocations of CheckPrereq do not raise an exception
5776
      self.lu.op.live = None
5777
    elif self.lu.op.mode is None:
5778
      # read the default value from the hypervisor
5779
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5780
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5781

    
5782
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5783

    
5784
  def _WaitUntilSync(self):
5785
    """Poll with custom rpc for disk sync.
5786

5787
    This uses our own step-based rpc call.
5788

5789
    """
5790
    self.feedback_fn("* wait until resync is done")
5791
    all_done = False
5792
    while not all_done:
5793
      all_done = True
5794
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5795
                                            self.nodes_ip,
5796
                                            self.instance.disks)
5797
      min_percent = 100
5798
      for node, nres in result.items():
5799
        nres.Raise("Cannot resync disks on node %s" % node)
5800
        node_done, node_percent = nres.payload
5801
        all_done = all_done and node_done
5802
        if node_percent is not None:
5803
          min_percent = min(min_percent, node_percent)
5804
      if not all_done:
5805
        if min_percent < 100:
5806
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5807
        time.sleep(2)
5808

    
5809
  def _EnsureSecondary(self, node):
5810
    """Demote a node to secondary.
5811

5812
    """
5813
    self.feedback_fn("* switching node %s to secondary mode" % node)
5814

    
5815
    for dev in self.instance.disks:
5816
      self.cfg.SetDiskID(dev, node)
5817

    
5818
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5819
                                          self.instance.disks)
5820
    result.Raise("Cannot change disk to secondary on node %s" % node)
5821

    
5822
  def _GoStandalone(self):
5823
    """Disconnect from the network.
5824

5825
    """
5826
    self.feedback_fn("* changing into standalone mode")
5827
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5828
                                               self.instance.disks)
5829
    for node, nres in result.items():
5830
      nres.Raise("Cannot disconnect disks node %s" % node)
5831

    
5832
  def _GoReconnect(self, multimaster):
5833
    """Reconnect to the network.
5834

5835
    """
5836
    if multimaster:
5837
      msg = "dual-master"
5838
    else:
5839
      msg = "single-master"
5840
    self.feedback_fn("* changing disks into %s mode" % msg)
5841
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5842
                                           self.instance.disks,
5843
                                           self.instance.name, multimaster)
5844
    for node, nres in result.items():
5845
      nres.Raise("Cannot change disks config on node %s" % node)
5846

    
5847
  def _ExecCleanup(self):
5848
    """Try to cleanup after a failed migration.
5849

5850
    The cleanup is done by:
5851
      - check that the instance is running only on one node
5852
        (and update the config if needed)
5853
      - change disks on its secondary node to secondary
5854
      - wait until disks are fully synchronized
5855
      - disconnect from the network
5856
      - change disks into single-master mode
5857
      - wait again until disks are fully synchronized
5858

5859
    """
5860
    instance = self.instance
5861
    target_node = self.target_node
5862
    source_node = self.source_node
5863

    
5864
    # check running on only one node
5865
    self.feedback_fn("* checking where the instance actually runs"
5866
                     " (if this hangs, the hypervisor might be in"
5867
                     " a bad state)")
5868
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5869
    for node, result in ins_l.items():
5870
      result.Raise("Can't contact node %s" % node)
5871

    
5872
    runningon_source = instance.name in ins_l[source_node].payload
5873
    runningon_target = instance.name in ins_l[target_node].payload
5874

    
5875
    if runningon_source and runningon_target:
5876
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5877
                               " or the hypervisor is confused. You will have"
5878
                               " to ensure manually that it runs only on one"
5879
                               " and restart this operation.")
5880

    
5881
    if not (runningon_source or runningon_target):
5882
      raise errors.OpExecError("Instance does not seem to be running at all."
5883
                               " In this case, it's safer to repair by"
5884
                               " running 'gnt-instance stop' to ensure disk"
5885
                               " shutdown, and then restarting it.")
5886

    
5887
    if runningon_target:
5888
      # the migration has actually succeeded, we need to update the config
5889
      self.feedback_fn("* instance running on secondary node (%s),"
5890
                       " updating config" % target_node)
5891
      instance.primary_node = target_node
5892
      self.cfg.Update(instance, self.feedback_fn)
5893
      demoted_node = source_node
5894
    else:
5895
      self.feedback_fn("* instance confirmed to be running on its"
5896
                       " primary node (%s)" % source_node)
5897
      demoted_node = target_node
5898

    
5899
    self._EnsureSecondary(demoted_node)
5900
    try:
5901
      self._WaitUntilSync()
5902
    except errors.OpExecError:
5903
      # we ignore here errors, since if the device is standalone, it
5904
      # won't be able to sync
5905
      pass
5906
    self._GoStandalone()
5907
    self._GoReconnect(False)
5908
    self._WaitUntilSync()
5909

    
5910
    self.feedback_fn("* done")
5911

    
5912
  def _RevertDiskStatus(self):
5913
    """Try to revert the disk status after a failed migration.
5914

5915
    """
5916
    target_node = self.target_node
5917
    try:
5918
      self._EnsureSecondary(target_node)
5919
      self._GoStandalone()
5920
      self._GoReconnect(False)
5921
      self._WaitUntilSync()
5922
    except errors.OpExecError, err:
5923
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5924
                         " drives: error '%s'\n"
5925
                         "Please look and recover the instance status" %
5926
                         str(err))
5927

    
5928
  def _AbortMigration(self):
5929
    """Call the hypervisor code to abort a started migration.
5930

5931
    """
5932
    instance = self.instance
5933
    target_node = self.target_node
5934
    migration_info = self.migration_info
5935

    
5936
    abort_result = self.rpc.call_finalize_migration(target_node,
5937
                                                    instance,
5938
                                                    migration_info,
5939
                                                    False)
5940
    abort_msg = abort_result.fail_msg
5941
    if abort_msg:
5942
      logging.error("Aborting migration failed on target node %s: %s",
5943
                    target_node, abort_msg)
5944
      # Don't raise an exception here, as we stil have to try to revert the
5945
      # disk status, even if this step failed.
5946

    
5947
  def _ExecMigration(self):
5948
    """Migrate an instance.
5949

5950
    The migrate is done by:
5951
      - change the disks into dual-master mode
5952
      - wait until disks are fully synchronized again
5953
      - migrate the instance
5954
      - change disks on the new secondary node (the old primary) to secondary
5955
      - wait until disks are fully synchronized
5956
      - change disks into single-master mode
5957

5958
    """
5959
    instance = self.instance
5960
    target_node = self.target_node
5961
    source_node = self.source_node
5962

    
5963
    self.feedback_fn("* checking disk consistency between source and target")
5964
    for dev in instance.disks:
5965
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
5966
        raise errors.OpExecError("Disk %s is degraded or not fully"
5967
                                 " synchronized on target node,"
5968
                                 " aborting migrate." % dev.iv_name)
5969

    
5970
    # First get the migration information from the remote node
5971
    result = self.rpc.call_migration_info(source_node, instance)
5972
    msg = result.fail_msg
5973
    if msg:
5974
      log_err = ("Failed fetching source migration information from %s: %s" %
5975
                 (source_node, msg))
5976
      logging.error(log_err)
5977
      raise errors.OpExecError(log_err)
5978

    
5979
    self.migration_info = migration_info = result.payload
5980

    
5981
    # Then switch the disks to master/master mode
5982
    self._EnsureSecondary(target_node)
5983
    self._GoStandalone()
5984
    self._GoReconnect(True)
5985
    self._WaitUntilSync()
5986

    
5987
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5988
    result = self.rpc.call_accept_instance(target_node,
5989
                                           instance,
5990
                                           migration_info,
5991
                                           self.nodes_ip[target_node])
5992

    
5993
    msg = result.fail_msg
5994
    if msg:
5995
      logging.error("Instance pre-migration failed, trying to revert"
5996
                    " disk status: %s", msg)
5997
      self.feedback_fn("Pre-migration failed, aborting")
5998
      self._AbortMigration()
5999
      self._RevertDiskStatus()
6000
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6001
                               (instance.name, msg))
6002

    
6003
    self.feedback_fn("* migrating instance to %s" % target_node)
6004
    time.sleep(10)
6005
    result = self.rpc.call_instance_migrate(source_node, instance,
6006
                                            self.nodes_ip[target_node],
6007
                                            self.live)
6008
    msg = result.fail_msg
6009
    if msg:
6010
      logging.error("Instance migration failed, trying to revert"
6011
                    " disk status: %s", msg)
6012
      self.feedback_fn("Migration failed, aborting")
6013
      self._AbortMigration()
6014
      self._RevertDiskStatus()
6015
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6016
                               (instance.name, msg))
6017
    time.sleep(10)
6018

    
6019
    instance.primary_node = target_node
6020
    # distribute new instance config to the other nodes
6021
    self.cfg.Update(instance, self.feedback_fn)
6022

    
6023
    result = self.rpc.call_finalize_migration(target_node,
6024
                                              instance,
6025
                                              migration_info,
6026
                                              True)
6027
    msg = result.fail_msg
6028
    if msg:
6029
      logging.error("Instance migration succeeded, but finalization failed:"
6030
                    " %s", msg)
6031
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6032
                               msg)
6033

    
6034
    self._EnsureSecondary(source_node)
6035
    self._WaitUntilSync()
6036
    self._GoStandalone()
6037
    self._GoReconnect(False)
6038
    self._WaitUntilSync()
6039

    
6040
    self.feedback_fn("* done")
6041

    
6042
  def Exec(self, feedback_fn):
6043
    """Perform the migration.
6044

6045
    """
6046
    feedback_fn("Migrating instance %s" % self.instance.name)
6047

    
6048
    self.feedback_fn = feedback_fn
6049

    
6050
    self.source_node = self.instance.primary_node
6051
    self.target_node = self.instance.secondary_nodes[0]
6052
    self.all_nodes = [self.source_node, self.target_node]
6053
    self.nodes_ip = {
6054
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6055
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6056
      }
6057

    
6058
    if self.cleanup:
6059
      return self._ExecCleanup()
6060
    else:
6061
      return self._ExecMigration()
6062

    
6063

    
6064
def _CreateBlockDev(lu, node, instance, device, force_create,
6065
                    info, force_open):
6066
  """Create a tree of block devices on a given node.
6067

6068
  If this device type has to be created on secondaries, create it and
6069
  all its children.
6070

6071
  If not, just recurse to children keeping the same 'force' value.
6072

6073
  @param lu: the lu on whose behalf we execute
6074
  @param node: the node on which to create the device
6075
  @type instance: L{objects.Instance}
6076
  @param instance: the instance which owns the device
6077
  @type device: L{objects.Disk}
6078
  @param device: the device to create
6079
  @type force_create: boolean
6080
  @param force_create: whether to force creation of this device; this
6081
      will be change to True whenever we find a device which has
6082
      CreateOnSecondary() attribute
6083
  @param info: the extra 'metadata' we should attach to the device
6084
      (this will be represented as a LVM tag)
6085
  @type force_open: boolean
6086
  @param force_open: this parameter will be passes to the
6087
      L{backend.BlockdevCreate} function where it specifies
6088
      whether we run on primary or not, and it affects both
6089
      the child assembly and the device own Open() execution
6090

6091
  """
6092
  if device.CreateOnSecondary():
6093
    force_create = True
6094

    
6095
  if device.children:
6096
    for child in device.children:
6097
      _CreateBlockDev(lu, node, instance, child, force_create,
6098
                      info, force_open)
6099

    
6100
  if not force_create:
6101
    return
6102

    
6103
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6104

    
6105

    
6106
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6107
  """Create a single block device on a given node.
6108

6109
  This will not recurse over children of the device, so they must be
6110
  created in advance.
6111

6112
  @param lu: the lu on whose behalf we execute
6113
  @param node: the node on which to create the device
6114
  @type instance: L{objects.Instance}
6115
  @param instance: the instance which owns the device
6116
  @type device: L{objects.Disk}
6117
  @param device: the device to create
6118
  @param info: the extra 'metadata' we should attach to the device
6119
      (this will be represented as a LVM tag)
6120
  @type force_open: boolean
6121
  @param force_open: this parameter will be passes to the
6122
      L{backend.BlockdevCreate} function where it specifies
6123
      whether we run on primary or not, and it affects both
6124
      the child assembly and the device own Open() execution
6125

6126
  """
6127
  lu.cfg.SetDiskID(device, node)
6128
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6129
                                       instance.name, force_open, info)
6130
  result.Raise("Can't create block device %s on"
6131
               " node %s for instance %s" % (device, node, instance.name))
6132
  if device.physical_id is None:
6133
    device.physical_id = result.payload
6134

    
6135

    
6136
def _GenerateUniqueNames(lu, exts):
6137
  """Generate a suitable LV name.
6138

6139
  This will generate a logical volume name for the given instance.
6140

6141
  """
6142
  results = []
6143
  for val in exts:
6144
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6145
    results.append("%s%s" % (new_id, val))
6146
  return results
6147

    
6148

    
6149
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6150
                         p_minor, s_minor):
6151
  """Generate a drbd8 device complete with its children.
6152

6153
  """
6154
  port = lu.cfg.AllocatePort()
6155
  vgname = lu.cfg.GetVGName()
6156
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6157
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6158
                          logical_id=(vgname, names[0]))
6159
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6160
                          logical_id=(vgname, names[1]))
6161
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6162
                          logical_id=(primary, secondary, port,
6163
                                      p_minor, s_minor,
6164
                                      shared_secret),
6165
                          children=[dev_data, dev_meta],
6166
                          iv_name=iv_name)
6167
  return drbd_dev
6168

    
6169

    
6170
def _GenerateDiskTemplate(lu, template_name,
6171
                          instance_name, primary_node,
6172
                          secondary_nodes, disk_info,
6173
                          file_storage_dir, file_driver,
6174
                          base_index):
6175
  """Generate the entire disk layout for a given template type.
6176

6177
  """
6178
  #TODO: compute space requirements
6179

    
6180
  vgname = lu.cfg.GetVGName()
6181
  disk_count = len(disk_info)
6182
  disks = []
6183
  if template_name == constants.DT_DISKLESS:
6184
    pass
6185
  elif template_name == constants.DT_PLAIN:
6186
    if len(secondary_nodes) != 0:
6187
      raise errors.ProgrammerError("Wrong template configuration")
6188

    
6189
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6190
                                      for i in range(disk_count)])
6191
    for idx, disk in enumerate(disk_info):
6192
      disk_index = idx + base_index
6193
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6194
                              logical_id=(vgname, names[idx]),
6195
                              iv_name="disk/%d" % disk_index,
6196
                              mode=disk["mode"])
6197
      disks.append(disk_dev)
6198
  elif template_name == constants.DT_DRBD8:
6199
    if len(secondary_nodes) != 1:
6200
      raise errors.ProgrammerError("Wrong template configuration")
6201
    remote_node = secondary_nodes[0]
6202
    minors = lu.cfg.AllocateDRBDMinor(
6203
      [primary_node, remote_node] * len(disk_info), instance_name)
6204

    
6205
    names = []
6206
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6207
                                               for i in range(disk_count)]):
6208
      names.append(lv_prefix + "_data")
6209
      names.append(lv_prefix + "_meta")
6210
    for idx, disk in enumerate(disk_info):
6211
      disk_index = idx + base_index
6212
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6213
                                      disk["size"], names[idx*2:idx*2+2],
6214
                                      "disk/%d" % disk_index,
6215
                                      minors[idx*2], minors[idx*2+1])
6216
      disk_dev.mode = disk["mode"]
6217
      disks.append(disk_dev)
6218
  elif template_name == constants.DT_FILE:
6219
    if len(secondary_nodes) != 0:
6220
      raise errors.ProgrammerError("Wrong template configuration")
6221

    
6222
    _RequireFileStorage()
6223

    
6224
    for idx, disk in enumerate(disk_info):
6225
      disk_index = idx + base_index
6226
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6227
                              iv_name="disk/%d" % disk_index,
6228
                              logical_id=(file_driver,
6229
                                          "%s/disk%d" % (file_storage_dir,
6230
                                                         disk_index)),
6231
                              mode=disk["mode"])
6232
      disks.append(disk_dev)
6233
  else:
6234
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6235
  return disks
6236

    
6237

    
6238
def _GetInstanceInfoText(instance):
6239
  """Compute that text that should be added to the disk's metadata.
6240

6241
  """
6242
  return "originstname+%s" % instance.name
6243

    
6244

    
6245
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6246
  """Create all disks for an instance.
6247

6248
  This abstracts away some work from AddInstance.
6249

6250
  @type lu: L{LogicalUnit}
6251
  @param lu: the logical unit on whose behalf we execute
6252
  @type instance: L{objects.Instance}
6253
  @param instance: the instance whose disks we should create
6254
  @type to_skip: list
6255
  @param to_skip: list of indices to skip
6256
  @type target_node: string
6257
  @param target_node: if passed, overrides the target node for creation
6258
  @rtype: boolean
6259
  @return: the success of the creation
6260

6261
  """
6262
  info = _GetInstanceInfoText(instance)
6263
  if target_node is None:
6264
    pnode = instance.primary_node
6265
    all_nodes = instance.all_nodes
6266
  else:
6267
    pnode = target_node
6268
    all_nodes = [pnode]
6269

    
6270
  if instance.disk_template == constants.DT_FILE:
6271
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6272
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6273

    
6274
    result.Raise("Failed to create directory '%s' on"
6275
                 " node %s" % (file_storage_dir, pnode))
6276

    
6277
  # Note: this needs to be kept in sync with adding of disks in
6278
  # LUSetInstanceParams
6279
  for idx, device in enumerate(instance.disks):
6280
    if to_skip and idx in to_skip:
6281
      continue
6282
    logging.info("Creating volume %s for instance %s",
6283
                 device.iv_name, instance.name)
6284
    #HARDCODE
6285
    for node in all_nodes:
6286
      f_create = node == pnode
6287
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6288

    
6289

    
6290
def _RemoveDisks(lu, instance, target_node=None):
6291
  """Remove all disks for an instance.
6292

6293
  This abstracts away some work from `AddInstance()` and
6294
  `RemoveInstance()`. Note that in case some of the devices couldn't
6295
  be removed, the removal will continue with the other ones (compare
6296
  with `_CreateDisks()`).
6297

6298
  @type lu: L{LogicalUnit}
6299
  @param lu: the logical unit on whose behalf we execute
6300
  @type instance: L{objects.Instance}
6301
  @param instance: the instance whose disks we should remove
6302
  @type target_node: string
6303
  @param target_node: used to override the node on which to remove the disks
6304
  @rtype: boolean
6305
  @return: the success of the removal
6306

6307
  """
6308
  logging.info("Removing block devices for instance %s", instance.name)
6309

    
6310
  all_result = True
6311
  for device in instance.disks:
6312
    if target_node:
6313
      edata = [(target_node, device)]
6314
    else:
6315
      edata = device.ComputeNodeTree(instance.primary_node)
6316
    for node, disk in edata:
6317
      lu.cfg.SetDiskID(disk, node)
6318
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6319
      if msg:
6320
        lu.LogWarning("Could not remove block device %s on node %s,"
6321
                      " continuing anyway: %s", device.iv_name, node, msg)
6322
        all_result = False
6323

    
6324
  if instance.disk_template == constants.DT_FILE:
6325
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6326
    if target_node:
6327
      tgt = target_node
6328
    else:
6329
      tgt = instance.primary_node
6330
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6331
    if result.fail_msg:
6332
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6333
                    file_storage_dir, instance.primary_node, result.fail_msg)
6334
      all_result = False
6335

    
6336
  return all_result
6337

    
6338

    
6339
def _ComputeDiskSize(disk_template, disks):
6340
  """Compute disk size requirements in the volume group
6341

6342
  """
6343
  # Required free disk space as a function of disk and swap space
6344
  req_size_dict = {
6345
    constants.DT_DISKLESS: None,
6346
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6347
    # 128 MB are added for drbd metadata for each disk
6348
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6349
    constants.DT_FILE: None,
6350
  }
6351

    
6352
  if disk_template not in req_size_dict:
6353
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6354
                                 " is unknown" %  disk_template)
6355

    
6356
  return req_size_dict[disk_template]
6357

    
6358

    
6359
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6360
  """Hypervisor parameter validation.
6361

6362
  This function abstract the hypervisor parameter validation to be
6363
  used in both instance create and instance modify.
6364

6365
  @type lu: L{LogicalUnit}
6366
  @param lu: the logical unit for which we check
6367
  @type nodenames: list
6368
  @param nodenames: the list of nodes on which we should check
6369
  @type hvname: string
6370
  @param hvname: the name of the hypervisor we should use
6371
  @type hvparams: dict
6372
  @param hvparams: the parameters which we need to check
6373
  @raise errors.OpPrereqError: if the parameters are not valid
6374

6375
  """
6376
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6377
                                                  hvname,
6378
                                                  hvparams)
6379
  for node in nodenames:
6380
    info = hvinfo[node]
6381
    if info.offline:
6382
      continue
6383
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6384

    
6385

    
6386
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6387
  """OS parameters validation.
6388

6389
  @type lu: L{LogicalUnit}
6390
  @param lu: the logical unit for which we check
6391
  @type required: boolean
6392
  @param required: whether the validation should fail if the OS is not
6393
      found
6394
  @type nodenames: list
6395
  @param nodenames: the list of nodes on which we should check
6396
  @type osname: string
6397
  @param osname: the name of the hypervisor we should use
6398
  @type osparams: dict
6399
  @param osparams: the parameters which we need to check
6400
  @raise errors.OpPrereqError: if the parameters are not valid
6401

6402
  """
6403
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6404
                                   [constants.OS_VALIDATE_PARAMETERS],
6405
                                   osparams)
6406
  for node, nres in result.items():
6407
    # we don't check for offline cases since this should be run only
6408
    # against the master node and/or an instance's nodes
6409
    nres.Raise("OS Parameters validation failed on node %s" % node)
6410
    if not nres.payload:
6411
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6412
                 osname, node)
6413

    
6414

    
6415
class LUCreateInstance(LogicalUnit):
6416
  """Create an instance.
6417

6418
  """
6419
  HPATH = "instance-add"
6420
  HTYPE = constants.HTYPE_INSTANCE
6421
  _OP_PARAMS = [
6422
    _PInstanceName,
6423
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
6424
    ("start", True, ht.TBool),
6425
    ("wait_for_sync", True, ht.TBool),
6426
    ("ip_check", True, ht.TBool),
6427
    ("name_check", True, ht.TBool),
6428
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
6429
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
6430
    ("hvparams", ht.EmptyDict, ht.TDict),
6431
    ("beparams", ht.EmptyDict, ht.TDict),
6432
    ("osparams", ht.EmptyDict, ht.TDict),
6433
    ("no_install", None, ht.TMaybeBool),
6434
    ("os_type", None, ht.TMaybeString),
6435
    ("force_variant", False, ht.TBool),
6436
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
6437
    ("source_x509_ca", None, ht.TMaybeString),
6438
    ("source_instance_name", None, ht.TMaybeString),
6439
    ("src_node", None, ht.TMaybeString),
6440
    ("src_path", None, ht.TMaybeString),
6441
    ("pnode", None, ht.TMaybeString),
6442
    ("snode", None, ht.TMaybeString),
6443
    ("iallocator", None, ht.TMaybeString),
6444
    ("hypervisor", None, ht.TMaybeString),
6445
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
6446
    ("identify_defaults", False, ht.TBool),
6447
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
6448
    ("file_storage_dir", None, ht.TMaybeString),
6449
    ]
6450
  REQ_BGL = False
6451

    
6452
  def CheckArguments(self):
6453
    """Check arguments.
6454

6455
    """
6456
    # do not require name_check to ease forward/backward compatibility
6457
    # for tools
6458
    if self.op.no_install and self.op.start:
6459
      self.LogInfo("No-installation mode selected, disabling startup")
6460
      self.op.start = False
6461
    # validate/normalize the instance name
6462
    self.op.instance_name = \
6463
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6464

    
6465
    if self.op.ip_check and not self.op.name_check:
6466
      # TODO: make the ip check more flexible and not depend on the name check
6467
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6468
                                 errors.ECODE_INVAL)
6469

    
6470
    # check nics' parameter names
6471
    for nic in self.op.nics:
6472
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6473

    
6474
    # check disks. parameter names and consistent adopt/no-adopt strategy
6475
    has_adopt = has_no_adopt = False
6476
    for disk in self.op.disks:
6477
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6478
      if "adopt" in disk:
6479
        has_adopt = True
6480
      else:
6481
        has_no_adopt = True
6482
    if has_adopt and has_no_adopt:
6483
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6484
                                 errors.ECODE_INVAL)
6485
    if has_adopt:
6486
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6487
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6488
                                   " '%s' disk template" %
6489
                                   self.op.disk_template,
6490
                                   errors.ECODE_INVAL)
6491
      if self.op.iallocator is not None:
6492
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6493
                                   " iallocator script", errors.ECODE_INVAL)
6494
      if self.op.mode == constants.INSTANCE_IMPORT:
6495
        raise errors.OpPrereqError("Disk adoption not allowed for"
6496
                                   " instance import", errors.ECODE_INVAL)
6497

    
6498
    self.adopt_disks = has_adopt
6499

    
6500
    # instance name verification
6501
    if self.op.name_check:
6502
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6503
      self.op.instance_name = self.hostname1.name
6504
      # used in CheckPrereq for ip ping check
6505
      self.check_ip = self.hostname1.ip
6506
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6507
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6508
                                 errors.ECODE_INVAL)
6509
    else:
6510
      self.check_ip = None
6511

    
6512
    # file storage checks
6513
    if (self.op.file_driver and
6514
        not self.op.file_driver in constants.FILE_DRIVER):
6515
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6516
                                 self.op.file_driver, errors.ECODE_INVAL)
6517

    
6518
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6519
      raise errors.OpPrereqError("File storage directory path not absolute",
6520
                                 errors.ECODE_INVAL)
6521

    
6522
    ### Node/iallocator related checks
6523
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6524

    
6525
    if self.op.pnode is not None:
6526
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6527
        if self.op.snode is None:
6528
          raise errors.OpPrereqError("The networked disk templates need"
6529
                                     " a mirror node", errors.ECODE_INVAL)
6530
      elif self.op.snode:
6531
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6532
                        " template")
6533
        self.op.snode = None
6534

    
6535
    self._cds = _GetClusterDomainSecret()
6536

    
6537
    if self.op.mode == constants.INSTANCE_IMPORT:
6538
      # On import force_variant must be True, because if we forced it at
6539
      # initial install, our only chance when importing it back is that it
6540
      # works again!
6541
      self.op.force_variant = True
6542

    
6543
      if self.op.no_install:
6544
        self.LogInfo("No-installation mode has no effect during import")
6545

    
6546
    elif self.op.mode == constants.INSTANCE_CREATE:
6547
      if self.op.os_type is None:
6548
        raise errors.OpPrereqError("No guest OS specified",
6549
                                   errors.ECODE_INVAL)
6550
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6551
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6552
                                   " installation" % self.op.os_type,
6553
                                   errors.ECODE_STATE)
6554
      if self.op.disk_template is None:
6555
        raise errors.OpPrereqError("No disk template specified",
6556
                                   errors.ECODE_INVAL)
6557

    
6558
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6559
      # Check handshake to ensure both clusters have the same domain secret
6560
      src_handshake = self.op.source_handshake
6561
      if not src_handshake:
6562
        raise errors.OpPrereqError("Missing source handshake",
6563
                                   errors.ECODE_INVAL)
6564

    
6565
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6566
                                                           src_handshake)
6567
      if errmsg:
6568
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6569
                                   errors.ECODE_INVAL)
6570

    
6571
      # Load and check source CA
6572
      self.source_x509_ca_pem = self.op.source_x509_ca
6573
      if not self.source_x509_ca_pem:
6574
        raise errors.OpPrereqError("Missing source X509 CA",
6575
                                   errors.ECODE_INVAL)
6576

    
6577
      try:
6578
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6579
                                                    self._cds)
6580
      except OpenSSL.crypto.Error, err:
6581
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6582
                                   (err, ), errors.ECODE_INVAL)
6583

    
6584
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6585
      if errcode is not None:
6586
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6587
                                   errors.ECODE_INVAL)
6588

    
6589
      self.source_x509_ca = cert
6590

    
6591
      src_instance_name = self.op.source_instance_name
6592
      if not src_instance_name:
6593
        raise errors.OpPrereqError("Missing source instance name",
6594
                                   errors.ECODE_INVAL)
6595

    
6596
      self.source_instance_name = \
6597
          netutils.GetHostname(name=src_instance_name).name
6598

    
6599
    else:
6600
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6601
                                 self.op.mode, errors.ECODE_INVAL)
6602

    
6603
  def ExpandNames(self):
6604
    """ExpandNames for CreateInstance.
6605

6606
    Figure out the right locks for instance creation.
6607

6608
    """
6609
    self.needed_locks = {}
6610

    
6611
    instance_name = self.op.instance_name
6612
    # this is just a preventive check, but someone might still add this
6613
    # instance in the meantime, and creation will fail at lock-add time
6614
    if instance_name in self.cfg.GetInstanceList():
6615
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6616
                                 instance_name, errors.ECODE_EXISTS)
6617

    
6618
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6619

    
6620
    if self.op.iallocator:
6621
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6622
    else:
6623
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6624
      nodelist = [self.op.pnode]
6625
      if self.op.snode is not None:
6626
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6627
        nodelist.append(self.op.snode)
6628
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6629

    
6630
    # in case of import lock the source node too
6631
    if self.op.mode == constants.INSTANCE_IMPORT:
6632
      src_node = self.op.src_node
6633
      src_path = self.op.src_path
6634

    
6635
      if src_path is None:
6636
        self.op.src_path = src_path = self.op.instance_name
6637

    
6638
      if src_node is None:
6639
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6640
        self.op.src_node = None
6641
        if os.path.isabs(src_path):
6642
          raise errors.OpPrereqError("Importing an instance from an absolute"
6643
                                     " path requires a source node option.",
6644
                                     errors.ECODE_INVAL)
6645
      else:
6646
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6647
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6648
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6649
        if not os.path.isabs(src_path):
6650
          self.op.src_path = src_path = \
6651
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6652

    
6653
  def _RunAllocator(self):
6654
    """Run the allocator based on input opcode.
6655

6656
    """
6657
    nics = [n.ToDict() for n in self.nics]
6658
    ial = IAllocator(self.cfg, self.rpc,
6659
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6660
                     name=self.op.instance_name,
6661
                     disk_template=self.op.disk_template,
6662
                     tags=[],
6663
                     os=self.op.os_type,
6664
                     vcpus=self.be_full[constants.BE_VCPUS],
6665
                     mem_size=self.be_full[constants.BE_MEMORY],
6666
                     disks=self.disks,
6667
                     nics=nics,
6668
                     hypervisor=self.op.hypervisor,
6669
                     )
6670

    
6671
    ial.Run(self.op.iallocator)
6672

    
6673
    if not ial.success:
6674
      raise errors.OpPrereqError("Can't compute nodes using"
6675
                                 " iallocator '%s': %s" %
6676
                                 (self.op.iallocator, ial.info),
6677
                                 errors.ECODE_NORES)
6678
    if len(ial.result) != ial.required_nodes:
6679
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6680
                                 " of nodes (%s), required %s" %
6681
                                 (self.op.iallocator, len(ial.result),
6682
                                  ial.required_nodes), errors.ECODE_FAULT)
6683
    self.op.pnode = ial.result[0]
6684
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6685
                 self.op.instance_name, self.op.iallocator,
6686
                 utils.CommaJoin(ial.result))
6687
    if ial.required_nodes == 2:
6688
      self.op.snode = ial.result[1]
6689

    
6690
  def BuildHooksEnv(self):
6691
    """Build hooks env.
6692

6693
    This runs on master, primary and secondary nodes of the instance.
6694

6695
    """
6696
    env = {
6697
      "ADD_MODE": self.op.mode,
6698
      }
6699
    if self.op.mode == constants.INSTANCE_IMPORT:
6700
      env["SRC_NODE"] = self.op.src_node
6701
      env["SRC_PATH"] = self.op.src_path
6702
      env["SRC_IMAGES"] = self.src_images
6703

    
6704
    env.update(_BuildInstanceHookEnv(
6705
      name=self.op.instance_name,
6706
      primary_node=self.op.pnode,
6707
      secondary_nodes=self.secondaries,
6708
      status=self.op.start,
6709
      os_type=self.op.os_type,
6710
      memory=self.be_full[constants.BE_MEMORY],
6711
      vcpus=self.be_full[constants.BE_VCPUS],
6712
      nics=_NICListToTuple(self, self.nics),
6713
      disk_template=self.op.disk_template,
6714
      disks=[(d["size"], d["mode"]) for d in self.disks],
6715
      bep=self.be_full,
6716
      hvp=self.hv_full,
6717
      hypervisor_name=self.op.hypervisor,
6718
    ))
6719

    
6720
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6721
          self.secondaries)
6722
    return env, nl, nl
6723

    
6724
  def _ReadExportInfo(self):
6725
    """Reads the export information from disk.
6726

6727
    It will override the opcode source node and path with the actual
6728
    information, if these two were not specified before.
6729

6730
    @return: the export information
6731

6732
    """
6733
    assert self.op.mode == constants.INSTANCE_IMPORT
6734

    
6735
    src_node = self.op.src_node
6736
    src_path = self.op.src_path
6737

    
6738
    if src_node is None:
6739
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6740
      exp_list = self.rpc.call_export_list(locked_nodes)
6741
      found = False
6742
      for node in exp_list:
6743
        if exp_list[node].fail_msg:
6744
          continue
6745
        if src_path in exp_list[node].payload:
6746
          found = True
6747
          self.op.src_node = src_node = node
6748
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6749
                                                       src_path)
6750
          break
6751
      if not found:
6752
        raise errors.OpPrereqError("No export found for relative path %s" %
6753
                                    src_path, errors.ECODE_INVAL)
6754

    
6755
    _CheckNodeOnline(self, src_node)
6756
    result = self.rpc.call_export_info(src_node, src_path)
6757
    result.Raise("No export or invalid export found in dir %s" % src_path)
6758

    
6759
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6760
    if not export_info.has_section(constants.INISECT_EXP):
6761
      raise errors.ProgrammerError("Corrupted export config",
6762
                                   errors.ECODE_ENVIRON)
6763

    
6764
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6765
    if (int(ei_version) != constants.EXPORT_VERSION):
6766
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6767
                                 (ei_version, constants.EXPORT_VERSION),
6768
                                 errors.ECODE_ENVIRON)
6769
    return export_info
6770

    
6771
  def _ReadExportParams(self, einfo):
6772
    """Use export parameters as defaults.
6773

6774
    In case the opcode doesn't specify (as in override) some instance
6775
    parameters, then try to use them from the export information, if
6776
    that declares them.
6777

6778
    """
6779
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6780

    
6781
    if self.op.disk_template is None:
6782
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6783
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6784
                                          "disk_template")
6785
      else:
6786
        raise errors.OpPrereqError("No disk template specified and the export"
6787
                                   " is missing the disk_template information",
6788
                                   errors.ECODE_INVAL)
6789

    
6790
    if not self.op.disks:
6791
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6792
        disks = []
6793
        # TODO: import the disk iv_name too
6794
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6795
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6796
          disks.append({"size": disk_sz})
6797
        self.op.disks = disks
6798
      else:
6799
        raise errors.OpPrereqError("No disk info specified and the export"
6800
                                   " is missing the disk information",
6801
                                   errors.ECODE_INVAL)
6802

    
6803
    if (not self.op.nics and
6804
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6805
      nics = []
6806
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6807
        ndict = {}
6808
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6809
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6810
          ndict[name] = v
6811
        nics.append(ndict)
6812
      self.op.nics = nics
6813

    
6814
    if (self.op.hypervisor is None and
6815
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6816
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6817
    if einfo.has_section(constants.INISECT_HYP):
6818
      # use the export parameters but do not override the ones
6819
      # specified by the user
6820
      for name, value in einfo.items(constants.INISECT_HYP):
6821
        if name not in self.op.hvparams:
6822
          self.op.hvparams[name] = value
6823

    
6824
    if einfo.has_section(constants.INISECT_BEP):
6825
      # use the parameters, without overriding
6826
      for name, value in einfo.items(constants.INISECT_BEP):
6827
        if name not in self.op.beparams:
6828
          self.op.beparams[name] = value
6829
    else:
6830
      # try to read the parameters old style, from the main section
6831
      for name in constants.BES_PARAMETERS:
6832
        if (name not in self.op.beparams and
6833
            einfo.has_option(constants.INISECT_INS, name)):
6834
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6835

    
6836
    if einfo.has_section(constants.INISECT_OSP):
6837
      # use the parameters, without overriding
6838
      for name, value in einfo.items(constants.INISECT_OSP):
6839
        if name not in self.op.osparams:
6840
          self.op.osparams[name] = value
6841

    
6842
  def _RevertToDefaults(self, cluster):
6843
    """Revert the instance parameters to the default values.
6844

6845
    """
6846
    # hvparams
6847
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6848
    for name in self.op.hvparams.keys():
6849
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6850
        del self.op.hvparams[name]
6851
    # beparams
6852
    be_defs = cluster.SimpleFillBE({})
6853
    for name in self.op.beparams.keys():
6854
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6855
        del self.op.beparams[name]
6856
    # nic params
6857
    nic_defs = cluster.SimpleFillNIC({})
6858
    for nic in self.op.nics:
6859
      for name in constants.NICS_PARAMETERS:
6860
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6861
          del nic[name]
6862
    # osparams
6863
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6864
    for name in self.op.osparams.keys():
6865
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6866
        del self.op.osparams[name]
6867

    
6868
  def CheckPrereq(self):
6869
    """Check prerequisites.
6870

6871
    """
6872
    if self.op.mode == constants.INSTANCE_IMPORT:
6873
      export_info = self._ReadExportInfo()
6874
      self._ReadExportParams(export_info)
6875

    
6876
    _CheckDiskTemplate(self.op.disk_template)
6877

    
6878
    if (not self.cfg.GetVGName() and
6879
        self.op.disk_template not in constants.DTS_NOT_LVM):
6880
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6881
                                 " instances", errors.ECODE_STATE)
6882

    
6883
    if self.op.hypervisor is None:
6884
      self.op.hypervisor = self.cfg.GetHypervisorType()
6885

    
6886
    cluster = self.cfg.GetClusterInfo()
6887
    enabled_hvs = cluster.enabled_hypervisors
6888
    if self.op.hypervisor not in enabled_hvs:
6889
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6890
                                 " cluster (%s)" % (self.op.hypervisor,
6891
                                  ",".join(enabled_hvs)),
6892
                                 errors.ECODE_STATE)
6893

    
6894
    # check hypervisor parameter syntax (locally)
6895
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6896
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6897
                                      self.op.hvparams)
6898
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6899
    hv_type.CheckParameterSyntax(filled_hvp)
6900
    self.hv_full = filled_hvp
6901
    # check that we don't specify global parameters on an instance
6902
    _CheckGlobalHvParams(self.op.hvparams)
6903

    
6904
    # fill and remember the beparams dict
6905
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6906
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6907

    
6908
    # build os parameters
6909
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6910

    
6911
    # now that hvp/bep are in final format, let's reset to defaults,
6912
    # if told to do so
6913
    if self.op.identify_defaults:
6914
      self._RevertToDefaults(cluster)
6915

    
6916
    # NIC buildup
6917
    self.nics = []
6918
    for idx, nic in enumerate(self.op.nics):
6919
      nic_mode_req = nic.get("mode", None)
6920
      nic_mode = nic_mode_req
6921
      if nic_mode is None:
6922
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6923

    
6924
      # in routed mode, for the first nic, the default ip is 'auto'
6925
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6926
        default_ip_mode = constants.VALUE_AUTO
6927
      else:
6928
        default_ip_mode = constants.VALUE_NONE
6929

    
6930
      # ip validity checks
6931
      ip = nic.get("ip", default_ip_mode)
6932
      if ip is None or ip.lower() == constants.VALUE_NONE:
6933
        nic_ip = None
6934
      elif ip.lower() == constants.VALUE_AUTO:
6935
        if not self.op.name_check:
6936
          raise errors.OpPrereqError("IP address set to auto but name checks"
6937
                                     " have been skipped",
6938
                                     errors.ECODE_INVAL)
6939
        nic_ip = self.hostname1.ip
6940
      else:
6941
        if not netutils.IPAddress.IsValid(ip):
6942
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
6943
                                     errors.ECODE_INVAL)
6944
        nic_ip = ip
6945

    
6946
      # TODO: check the ip address for uniqueness
6947
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6948
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6949
                                   errors.ECODE_INVAL)
6950

    
6951
      # MAC address verification
6952
      mac = nic.get("mac", constants.VALUE_AUTO)
6953
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6954
        mac = utils.NormalizeAndValidateMac(mac)
6955

    
6956
        try:
6957
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6958
        except errors.ReservationError:
6959
          raise errors.OpPrereqError("MAC address %s already in use"
6960
                                     " in cluster" % mac,
6961
                                     errors.ECODE_NOTUNIQUE)
6962

    
6963
      # bridge verification
6964
      bridge = nic.get("bridge", None)
6965
      link = nic.get("link", None)
6966
      if bridge and link:
6967
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6968
                                   " at the same time", errors.ECODE_INVAL)
6969
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6970
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6971
                                   errors.ECODE_INVAL)
6972
      elif bridge:
6973
        link = bridge
6974

    
6975
      nicparams = {}
6976
      if nic_mode_req:
6977
        nicparams[constants.NIC_MODE] = nic_mode_req
6978
      if link:
6979
        nicparams[constants.NIC_LINK] = link
6980

    
6981
      check_params = cluster.SimpleFillNIC(nicparams)
6982
      objects.NIC.CheckParameterSyntax(check_params)
6983
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6984

    
6985
    # disk checks/pre-build
6986
    self.disks = []
6987
    for disk in self.op.disks:
6988
      mode = disk.get("mode", constants.DISK_RDWR)
6989
      if mode not in constants.DISK_ACCESS_SET:
6990
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6991
                                   mode, errors.ECODE_INVAL)
6992
      size = disk.get("size", None)
6993
      if size is None:
6994
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6995
      try:
6996
        size = int(size)
6997
      except (TypeError, ValueError):
6998
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6999
                                   errors.ECODE_INVAL)
7000
      new_disk = {"size": size, "mode": mode}
7001
      if "adopt" in disk:
7002
        new_disk["adopt"] = disk["adopt"]
7003
      self.disks.append(new_disk)
7004

    
7005
    if self.op.mode == constants.INSTANCE_IMPORT:
7006

    
7007
      # Check that the new instance doesn't have less disks than the export
7008
      instance_disks = len(self.disks)
7009
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7010
      if instance_disks < export_disks:
7011
        raise errors.OpPrereqError("Not enough disks to import."
7012
                                   " (instance: %d, export: %d)" %
7013
                                   (instance_disks, export_disks),
7014
                                   errors.ECODE_INVAL)
7015

    
7016
      disk_images = []
7017
      for idx in range(export_disks):
7018
        option = 'disk%d_dump' % idx
7019
        if export_info.has_option(constants.INISECT_INS, option):
7020
          # FIXME: are the old os-es, disk sizes, etc. useful?
7021
          export_name = export_info.get(constants.INISECT_INS, option)
7022
          image = utils.PathJoin(self.op.src_path, export_name)
7023
          disk_images.append(image)
7024
        else:
7025
          disk_images.append(False)
7026

    
7027
      self.src_images = disk_images
7028

    
7029
      old_name = export_info.get(constants.INISECT_INS, 'name')
7030
      try:
7031
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7032
      except (TypeError, ValueError), err:
7033
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7034
                                   " an integer: %s" % str(err),
7035
                                   errors.ECODE_STATE)
7036
      if self.op.instance_name == old_name:
7037
        for idx, nic in enumerate(self.nics):
7038
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7039
            nic_mac_ini = 'nic%d_mac' % idx
7040
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7041

    
7042
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7043

    
7044
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7045
    if self.op.ip_check:
7046
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7047
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7048
                                   (self.check_ip, self.op.instance_name),
7049
                                   errors.ECODE_NOTUNIQUE)
7050

    
7051
    #### mac address generation
7052
    # By generating here the mac address both the allocator and the hooks get
7053
    # the real final mac address rather than the 'auto' or 'generate' value.
7054
    # There is a race condition between the generation and the instance object
7055
    # creation, which means that we know the mac is valid now, but we're not
7056
    # sure it will be when we actually add the instance. If things go bad
7057
    # adding the instance will abort because of a duplicate mac, and the
7058
    # creation job will fail.
7059
    for nic in self.nics:
7060
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7061
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7062

    
7063
    #### allocator run
7064

    
7065
    if self.op.iallocator is not None:
7066
      self._RunAllocator()
7067

    
7068
    #### node related checks
7069

    
7070
    # check primary node
7071
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7072
    assert self.pnode is not None, \
7073
      "Cannot retrieve locked node %s" % self.op.pnode
7074
    if pnode.offline:
7075
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7076
                                 pnode.name, errors.ECODE_STATE)
7077
    if pnode.drained:
7078
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7079
                                 pnode.name, errors.ECODE_STATE)
7080

    
7081
    self.secondaries = []
7082

    
7083
    # mirror node verification
7084
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7085
      if self.op.snode == pnode.name:
7086
        raise errors.OpPrereqError("The secondary node cannot be the"
7087
                                   " primary node.", errors.ECODE_INVAL)
7088
      _CheckNodeOnline(self, self.op.snode)
7089
      _CheckNodeNotDrained(self, self.op.snode)
7090
      self.secondaries.append(self.op.snode)
7091

    
7092
    nodenames = [pnode.name] + self.secondaries
7093

    
7094
    req_size = _ComputeDiskSize(self.op.disk_template,
7095
                                self.disks)
7096

    
7097
    # Check lv size requirements, if not adopting
7098
    if req_size is not None and not self.adopt_disks:
7099
      _CheckNodesFreeDisk(self, nodenames, req_size)
7100

    
7101
    if self.adopt_disks: # instead, we must check the adoption data
7102
      all_lvs = set([i["adopt"] for i in self.disks])
7103
      if len(all_lvs) != len(self.disks):
7104
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7105
                                   errors.ECODE_INVAL)
7106
      for lv_name in all_lvs:
7107
        try:
7108
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7109
        except errors.ReservationError:
7110
          raise errors.OpPrereqError("LV named %s used by another instance" %
7111
                                     lv_name, errors.ECODE_NOTUNIQUE)
7112

    
7113
      node_lvs = self.rpc.call_lv_list([pnode.name],
7114
                                       self.cfg.GetVGName())[pnode.name]
7115
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7116
      node_lvs = node_lvs.payload
7117
      delta = all_lvs.difference(node_lvs.keys())
7118
      if delta:
7119
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7120
                                   utils.CommaJoin(delta),
7121
                                   errors.ECODE_INVAL)
7122
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7123
      if online_lvs:
7124
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7125
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7126
                                   errors.ECODE_STATE)
7127
      # update the size of disk based on what is found
7128
      for dsk in self.disks:
7129
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7130

    
7131
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7132

    
7133
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7134
    # check OS parameters (remotely)
7135
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7136

    
7137
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7138

    
7139
    # memory check on primary node
7140
    if self.op.start:
7141
      _CheckNodeFreeMemory(self, self.pnode.name,
7142
                           "creating instance %s" % self.op.instance_name,
7143
                           self.be_full[constants.BE_MEMORY],
7144
                           self.op.hypervisor)
7145

    
7146
    self.dry_run_result = list(nodenames)
7147

    
7148
  def Exec(self, feedback_fn):
7149
    """Create and add the instance to the cluster.
7150

7151
    """
7152
    instance = self.op.instance_name
7153
    pnode_name = self.pnode.name
7154

    
7155
    ht_kind = self.op.hypervisor
7156
    if ht_kind in constants.HTS_REQ_PORT:
7157
      network_port = self.cfg.AllocatePort()
7158
    else:
7159
      network_port = None
7160

    
7161
    if constants.ENABLE_FILE_STORAGE:
7162
      # this is needed because os.path.join does not accept None arguments
7163
      if self.op.file_storage_dir is None:
7164
        string_file_storage_dir = ""
7165
      else:
7166
        string_file_storage_dir = self.op.file_storage_dir
7167

    
7168
      # build the full file storage dir path
7169
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7170
                                        string_file_storage_dir, instance)
7171
    else:
7172
      file_storage_dir = ""
7173

    
7174
    disks = _GenerateDiskTemplate(self,
7175
                                  self.op.disk_template,
7176
                                  instance, pnode_name,
7177
                                  self.secondaries,
7178
                                  self.disks,
7179
                                  file_storage_dir,
7180
                                  self.op.file_driver,
7181
                                  0)
7182

    
7183
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7184
                            primary_node=pnode_name,
7185
                            nics=self.nics, disks=disks,
7186
                            disk_template=self.op.disk_template,
7187
                            admin_up=False,
7188
                            network_port=network_port,
7189
                            beparams=self.op.beparams,
7190
                            hvparams=self.op.hvparams,
7191
                            hypervisor=self.op.hypervisor,
7192
                            osparams=self.op.osparams,
7193
                            )
7194

    
7195
    if self.adopt_disks:
7196
      # rename LVs to the newly-generated names; we need to construct
7197
      # 'fake' LV disks with the old data, plus the new unique_id
7198
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7199
      rename_to = []
7200
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7201
        rename_to.append(t_dsk.logical_id)
7202
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7203
        self.cfg.SetDiskID(t_dsk, pnode_name)
7204
      result = self.rpc.call_blockdev_rename(pnode_name,
7205
                                             zip(tmp_disks, rename_to))
7206
      result.Raise("Failed to rename adoped LVs")
7207
    else:
7208
      feedback_fn("* creating instance disks...")
7209
      try:
7210
        _CreateDisks(self, iobj)
7211
      except errors.OpExecError:
7212
        self.LogWarning("Device creation failed, reverting...")
7213
        try:
7214
          _RemoveDisks(self, iobj)
7215
        finally:
7216
          self.cfg.ReleaseDRBDMinors(instance)
7217
          raise
7218

    
7219
    feedback_fn("adding instance %s to cluster config" % instance)
7220

    
7221
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7222

    
7223
    # Declare that we don't want to remove the instance lock anymore, as we've
7224
    # added the instance to the config
7225
    del self.remove_locks[locking.LEVEL_INSTANCE]
7226
    # Unlock all the nodes
7227
    if self.op.mode == constants.INSTANCE_IMPORT:
7228
      nodes_keep = [self.op.src_node]
7229
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7230
                       if node != self.op.src_node]
7231
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7232
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7233
    else:
7234
      self.context.glm.release(locking.LEVEL_NODE)
7235
      del self.acquired_locks[locking.LEVEL_NODE]
7236

    
7237
    if self.op.wait_for_sync:
7238
      disk_abort = not _WaitForSync(self, iobj)
7239
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7240
      # make sure the disks are not degraded (still sync-ing is ok)
7241
      time.sleep(15)
7242
      feedback_fn("* checking mirrors status")
7243
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7244
    else:
7245
      disk_abort = False
7246

    
7247
    if disk_abort:
7248
      _RemoveDisks(self, iobj)
7249
      self.cfg.RemoveInstance(iobj.name)
7250
      # Make sure the instance lock gets removed
7251
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7252
      raise errors.OpExecError("There are some degraded disks for"
7253
                               " this instance")
7254

    
7255
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7256
      if self.op.mode == constants.INSTANCE_CREATE:
7257
        if not self.op.no_install:
7258
          feedback_fn("* running the instance OS create scripts...")
7259
          # FIXME: pass debug option from opcode to backend
7260
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7261
                                                 self.op.debug_level)
7262
          result.Raise("Could not add os for instance %s"
7263
                       " on node %s" % (instance, pnode_name))
7264

    
7265
      elif self.op.mode == constants.INSTANCE_IMPORT:
7266
        feedback_fn("* running the instance OS import scripts...")
7267

    
7268
        transfers = []
7269

    
7270
        for idx, image in enumerate(self.src_images):
7271
          if not image:
7272
            continue
7273

    
7274
          # FIXME: pass debug option from opcode to backend
7275
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7276
                                             constants.IEIO_FILE, (image, ),
7277
                                             constants.IEIO_SCRIPT,
7278
                                             (iobj.disks[idx], idx),
7279
                                             None)
7280
          transfers.append(dt)
7281

    
7282
        import_result = \
7283
          masterd.instance.TransferInstanceData(self, feedback_fn,
7284
                                                self.op.src_node, pnode_name,
7285
                                                self.pnode.secondary_ip,
7286
                                                iobj, transfers)
7287
        if not compat.all(import_result):
7288
          self.LogWarning("Some disks for instance %s on node %s were not"
7289
                          " imported successfully" % (instance, pnode_name))
7290

    
7291
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7292
        feedback_fn("* preparing remote import...")
7293
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7294
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7295

    
7296
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7297
                                                     self.source_x509_ca,
7298
                                                     self._cds, timeouts)
7299
        if not compat.all(disk_results):
7300
          # TODO: Should the instance still be started, even if some disks
7301
          # failed to import (valid for local imports, too)?
7302
          self.LogWarning("Some disks for instance %s on node %s were not"
7303
                          " imported successfully" % (instance, pnode_name))
7304

    
7305
        # Run rename script on newly imported instance
7306
        assert iobj.name == instance
7307
        feedback_fn("Running rename script for %s" % instance)
7308
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7309
                                                   self.source_instance_name,
7310
                                                   self.op.debug_level)
7311
        if result.fail_msg:
7312
          self.LogWarning("Failed to run rename script for %s on node"
7313
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7314

    
7315
      else:
7316
        # also checked in the prereq part
7317
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7318
                                     % self.op.mode)
7319

    
7320
    if self.op.start:
7321
      iobj.admin_up = True
7322
      self.cfg.Update(iobj, feedback_fn)
7323
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7324
      feedback_fn("* starting instance...")
7325
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7326
      result.Raise("Could not start instance")
7327

    
7328
    return list(iobj.all_nodes)
7329

    
7330

    
7331
class LUConnectConsole(NoHooksLU):
7332
  """Connect to an instance's console.
7333

7334
  This is somewhat special in that it returns the command line that
7335
  you need to run on the master node in order to connect to the
7336
  console.
7337

7338
  """
7339
  _OP_PARAMS = [
7340
    _PInstanceName
7341
    ]
7342
  REQ_BGL = False
7343

    
7344
  def ExpandNames(self):
7345
    self._ExpandAndLockInstance()
7346

    
7347
  def CheckPrereq(self):
7348
    """Check prerequisites.
7349

7350
    This checks that the instance is in the cluster.
7351

7352
    """
7353
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7354
    assert self.instance is not None, \
7355
      "Cannot retrieve locked instance %s" % self.op.instance_name
7356
    _CheckNodeOnline(self, self.instance.primary_node)
7357

    
7358
  def Exec(self, feedback_fn):
7359
    """Connect to the console of an instance
7360

7361
    """
7362
    instance = self.instance
7363
    node = instance.primary_node
7364

    
7365
    node_insts = self.rpc.call_instance_list([node],
7366
                                             [instance.hypervisor])[node]
7367
    node_insts.Raise("Can't get node information from %s" % node)
7368

    
7369
    if instance.name not in node_insts.payload:
7370
      if instance.admin_up:
7371
        state = "ERROR_down"
7372
      else:
7373
        state = "ADMIN_down"
7374
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7375
                               (instance.name, state))
7376

    
7377
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7378

    
7379
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7380
    cluster = self.cfg.GetClusterInfo()
7381
    # beparams and hvparams are passed separately, to avoid editing the
7382
    # instance and then saving the defaults in the instance itself.
7383
    hvparams = cluster.FillHV(instance)
7384
    beparams = cluster.FillBE(instance)
7385
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7386

    
7387
    # build ssh cmdline
7388
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7389

    
7390

    
7391
class LUReplaceDisks(LogicalUnit):
7392
  """Replace the disks of an instance.
7393

7394
  """
7395
  HPATH = "mirrors-replace"
7396
  HTYPE = constants.HTYPE_INSTANCE
7397
  _OP_PARAMS = [
7398
    _PInstanceName,
7399
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
7400
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
7401
    ("remote_node", None, ht.TMaybeString),
7402
    ("iallocator", None, ht.TMaybeString),
7403
    ("early_release", False, ht.TBool),
7404
    ]
7405
  REQ_BGL = False
7406

    
7407
  def CheckArguments(self):
7408
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7409
                                  self.op.iallocator)
7410

    
7411
  def ExpandNames(self):
7412
    self._ExpandAndLockInstance()
7413

    
7414
    if self.op.iallocator is not None:
7415
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7416

    
7417
    elif self.op.remote_node is not None:
7418
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7419
      self.op.remote_node = remote_node
7420

    
7421
      # Warning: do not remove the locking of the new secondary here
7422
      # unless DRBD8.AddChildren is changed to work in parallel;
7423
      # currently it doesn't since parallel invocations of
7424
      # FindUnusedMinor will conflict
7425
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7426
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7427

    
7428
    else:
7429
      self.needed_locks[locking.LEVEL_NODE] = []
7430
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7431

    
7432
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7433
                                   self.op.iallocator, self.op.remote_node,
7434
                                   self.op.disks, False, self.op.early_release)
7435

    
7436
    self.tasklets = [self.replacer]
7437

    
7438
  def DeclareLocks(self, level):
7439
    # If we're not already locking all nodes in the set we have to declare the
7440
    # instance's primary/secondary nodes.
7441
    if (level == locking.LEVEL_NODE and
7442
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7443
      self._LockInstancesNodes()
7444

    
7445
  def BuildHooksEnv(self):
7446
    """Build hooks env.
7447

7448
    This runs on the master, the primary and all the secondaries.
7449

7450
    """
7451
    instance = self.replacer.instance
7452
    env = {
7453
      "MODE": self.op.mode,
7454
      "NEW_SECONDARY": self.op.remote_node,
7455
      "OLD_SECONDARY": instance.secondary_nodes[0],
7456
      }
7457
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7458
    nl = [
7459
      self.cfg.GetMasterNode(),
7460
      instance.primary_node,
7461
      ]
7462
    if self.op.remote_node is not None:
7463
      nl.append(self.op.remote_node)
7464
    return env, nl, nl
7465

    
7466

    
7467
class TLReplaceDisks(Tasklet):
7468
  """Replaces disks for an instance.
7469

7470
  Note: Locking is not within the scope of this class.
7471

7472
  """
7473
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7474
               disks, delay_iallocator, early_release):
7475
    """Initializes this class.
7476

7477
    """
7478
    Tasklet.__init__(self, lu)
7479

    
7480
    # Parameters
7481
    self.instance_name = instance_name
7482
    self.mode = mode
7483
    self.iallocator_name = iallocator_name
7484
    self.remote_node = remote_node
7485
    self.disks = disks
7486
    self.delay_iallocator = delay_iallocator
7487
    self.early_release = early_release
7488

    
7489
    # Runtime data
7490
    self.instance = None
7491
    self.new_node = None
7492
    self.target_node = None
7493
    self.other_node = None
7494
    self.remote_node_info = None
7495
    self.node_secondary_ip = None
7496

    
7497
  @staticmethod
7498
  def CheckArguments(mode, remote_node, iallocator):
7499
    """Helper function for users of this class.
7500

7501
    """
7502
    # check for valid parameter combination
7503
    if mode == constants.REPLACE_DISK_CHG:
7504
      if remote_node is None and iallocator is None:
7505
        raise errors.OpPrereqError("When changing the secondary either an"
7506
                                   " iallocator script must be used or the"
7507
                                   " new node given", errors.ECODE_INVAL)
7508

    
7509
      if remote_node is not None and iallocator is not None:
7510
        raise errors.OpPrereqError("Give either the iallocator or the new"
7511
                                   " secondary, not both", errors.ECODE_INVAL)
7512

    
7513
    elif remote_node is not None or iallocator is not None:
7514
      # Not replacing the secondary
7515
      raise errors.OpPrereqError("The iallocator and new node options can"
7516
                                 " only be used when changing the"
7517
                                 " secondary node", errors.ECODE_INVAL)
7518

    
7519
  @staticmethod
7520
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7521
    """Compute a new secondary node using an IAllocator.
7522

7523
    """
7524
    ial = IAllocator(lu.cfg, lu.rpc,
7525
                     mode=constants.IALLOCATOR_MODE_RELOC,
7526
                     name=instance_name,
7527
                     relocate_from=relocate_from)
7528

    
7529
    ial.Run(iallocator_name)
7530

    
7531
    if not ial.success:
7532
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7533
                                 " %s" % (iallocator_name, ial.info),
7534
                                 errors.ECODE_NORES)
7535

    
7536
    if len(ial.result) != ial.required_nodes:
7537
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7538
                                 " of nodes (%s), required %s" %
7539
                                 (iallocator_name,
7540
                                  len(ial.result), ial.required_nodes),
7541
                                 errors.ECODE_FAULT)
7542

    
7543
    remote_node_name = ial.result[0]
7544

    
7545
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7546
               instance_name, remote_node_name)
7547

    
7548
    return remote_node_name
7549

    
7550
  def _FindFaultyDisks(self, node_name):
7551
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7552
                                    node_name, True)
7553

    
7554
  def CheckPrereq(self):
7555
    """Check prerequisites.
7556

7557
    This checks that the instance is in the cluster.
7558

7559
    """
7560
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7561
    assert instance is not None, \
7562
      "Cannot retrieve locked instance %s" % self.instance_name
7563

    
7564
    if instance.disk_template != constants.DT_DRBD8:
7565
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7566
                                 " instances", errors.ECODE_INVAL)
7567

    
7568
    if len(instance.secondary_nodes) != 1:
7569
      raise errors.OpPrereqError("The instance has a strange layout,"
7570
                                 " expected one secondary but found %d" %
7571
                                 len(instance.secondary_nodes),
7572
                                 errors.ECODE_FAULT)
7573

    
7574
    if not self.delay_iallocator:
7575
      self._CheckPrereq2()
7576

    
7577
  def _CheckPrereq2(self):
7578
    """Check prerequisites, second part.
7579

7580
    This function should always be part of CheckPrereq. It was separated and is
7581
    now called from Exec because during node evacuation iallocator was only
7582
    called with an unmodified cluster model, not taking planned changes into
7583
    account.
7584

7585
    """
7586
    instance = self.instance
7587
    secondary_node = instance.secondary_nodes[0]
7588

    
7589
    if self.iallocator_name is None:
7590
      remote_node = self.remote_node
7591
    else:
7592
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7593
                                       instance.name, instance.secondary_nodes)
7594

    
7595
    if remote_node is not None:
7596
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7597
      assert self.remote_node_info is not None, \
7598
        "Cannot retrieve locked node %s" % remote_node
7599
    else:
7600
      self.remote_node_info = None
7601

    
7602
    if remote_node == self.instance.primary_node:
7603
      raise errors.OpPrereqError("The specified node is the primary node of"
7604
                                 " the instance.", errors.ECODE_INVAL)
7605

    
7606
    if remote_node == secondary_node:
7607
      raise errors.OpPrereqError("The specified node is already the"
7608
                                 " secondary node of the instance.",
7609
                                 errors.ECODE_INVAL)
7610

    
7611
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7612
                                    constants.REPLACE_DISK_CHG):
7613
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7614
                                 errors.ECODE_INVAL)
7615

    
7616
    if self.mode == constants.REPLACE_DISK_AUTO:
7617
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7618
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7619

    
7620
      if faulty_primary and faulty_secondary:
7621
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7622
                                   " one node and can not be repaired"
7623
                                   " automatically" % self.instance_name,
7624
                                   errors.ECODE_STATE)
7625

    
7626
      if faulty_primary:
7627
        self.disks = faulty_primary
7628
        self.target_node = instance.primary_node
7629
        self.other_node = secondary_node
7630
        check_nodes = [self.target_node, self.other_node]
7631
      elif faulty_secondary:
7632
        self.disks = faulty_secondary
7633
        self.target_node = secondary_node
7634
        self.other_node = instance.primary_node
7635
        check_nodes = [self.target_node, self.other_node]
7636
      else:
7637
        self.disks = []
7638
        check_nodes = []
7639

    
7640
    else:
7641
      # Non-automatic modes
7642
      if self.mode == constants.REPLACE_DISK_PRI:
7643
        self.target_node = instance.primary_node
7644
        self.other_node = secondary_node
7645
        check_nodes = [self.target_node, self.other_node]
7646

    
7647
      elif self.mode == constants.REPLACE_DISK_SEC:
7648
        self.target_node = secondary_node
7649
        self.other_node = instance.primary_node
7650
        check_nodes = [self.target_node, self.other_node]
7651

    
7652
      elif self.mode == constants.REPLACE_DISK_CHG:
7653
        self.new_node = remote_node
7654
        self.other_node = instance.primary_node
7655
        self.target_node = secondary_node
7656
        check_nodes = [self.new_node, self.other_node]
7657

    
7658
        _CheckNodeNotDrained(self.lu, remote_node)
7659

    
7660
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7661
        assert old_node_info is not None
7662
        if old_node_info.offline and not self.early_release:
7663
          # doesn't make sense to delay the release
7664
          self.early_release = True
7665
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7666
                          " early-release mode", secondary_node)
7667

    
7668
      else:
7669
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7670
                                     self.mode)
7671

    
7672
      # If not specified all disks should be replaced
7673
      if not self.disks:
7674
        self.disks = range(len(self.instance.disks))
7675

    
7676
    for node in check_nodes:
7677
      _CheckNodeOnline(self.lu, node)
7678

    
7679
    # Check whether disks are valid
7680
    for disk_idx in self.disks:
7681
      instance.FindDisk(disk_idx)
7682

    
7683
    # Get secondary node IP addresses
7684
    node_2nd_ip = {}
7685

    
7686
    for node_name in [self.target_node, self.other_node, self.new_node]:
7687
      if node_name is not None:
7688
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7689

    
7690
    self.node_secondary_ip = node_2nd_ip
7691

    
7692
  def Exec(self, feedback_fn):
7693
    """Execute disk replacement.
7694

7695
    This dispatches the disk replacement to the appropriate handler.
7696

7697
    """
7698
    if self.delay_iallocator:
7699
      self._CheckPrereq2()
7700

    
7701
    if not self.disks:
7702
      feedback_fn("No disks need replacement")
7703
      return
7704

    
7705
    feedback_fn("Replacing disk(s) %s for %s" %
7706
                (utils.CommaJoin(self.disks), self.instance.name))
7707

    
7708
    activate_disks = (not self.instance.admin_up)
7709

    
7710
    # Activate the instance disks if we're replacing them on a down instance
7711
    if activate_disks:
7712
      _StartInstanceDisks(self.lu, self.instance, True)
7713

    
7714
    try:
7715
      # Should we replace the secondary node?
7716
      if self.new_node is not None:
7717
        fn = self._ExecDrbd8Secondary
7718
      else:
7719
        fn = self._ExecDrbd8DiskOnly
7720

    
7721
      return fn(feedback_fn)
7722

    
7723
    finally:
7724
      # Deactivate the instance disks if we're replacing them on a
7725
      # down instance
7726
      if activate_disks:
7727
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7728

    
7729
  def _CheckVolumeGroup(self, nodes):
7730
    self.lu.LogInfo("Checking volume groups")
7731

    
7732
    vgname = self.cfg.GetVGName()
7733

    
7734
    # Make sure volume group exists on all involved nodes
7735
    results = self.rpc.call_vg_list(nodes)
7736
    if not results:
7737
      raise errors.OpExecError("Can't list volume groups on the nodes")
7738

    
7739
    for node in nodes:
7740
      res = results[node]
7741
      res.Raise("Error checking node %s" % node)
7742
      if vgname not in res.payload:
7743
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7744
                                 (vgname, node))
7745

    
7746
  def _CheckDisksExistence(self, nodes):
7747
    # Check disk existence
7748
    for idx, dev in enumerate(self.instance.disks):
7749
      if idx not in self.disks:
7750
        continue
7751

    
7752
      for node in nodes:
7753
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7754
        self.cfg.SetDiskID(dev, node)
7755

    
7756
        result = self.rpc.call_blockdev_find(node, dev)
7757

    
7758
        msg = result.fail_msg
7759
        if msg or not result.payload:
7760
          if not msg:
7761
            msg = "disk not found"
7762
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7763
                                   (idx, node, msg))
7764

    
7765
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7766
    for idx, dev in enumerate(self.instance.disks):
7767
      if idx not in self.disks:
7768
        continue
7769

    
7770
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7771
                      (idx, node_name))
7772

    
7773
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7774
                                   ldisk=ldisk):
7775
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7776
                                 " replace disks for instance %s" %
7777
                                 (node_name, self.instance.name))
7778

    
7779
  def _CreateNewStorage(self, node_name):
7780
    vgname = self.cfg.GetVGName()
7781
    iv_names = {}
7782

    
7783
    for idx, dev in enumerate(self.instance.disks):
7784
      if idx not in self.disks:
7785
        continue
7786

    
7787
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7788

    
7789
      self.cfg.SetDiskID(dev, node_name)
7790

    
7791
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7792
      names = _GenerateUniqueNames(self.lu, lv_names)
7793

    
7794
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7795
                             logical_id=(vgname, names[0]))
7796
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7797
                             logical_id=(vgname, names[1]))
7798

    
7799
      new_lvs = [lv_data, lv_meta]
7800
      old_lvs = dev.children
7801
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7802

    
7803
      # we pass force_create=True to force the LVM creation
7804
      for new_lv in new_lvs:
7805
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7806
                        _GetInstanceInfoText(self.instance), False)
7807

    
7808
    return iv_names
7809

    
7810
  def _CheckDevices(self, node_name, iv_names):
7811
    for name, (dev, _, _) in iv_names.iteritems():
7812
      self.cfg.SetDiskID(dev, node_name)
7813

    
7814
      result = self.rpc.call_blockdev_find(node_name, dev)
7815

    
7816
      msg = result.fail_msg
7817
      if msg or not result.payload:
7818
        if not msg:
7819
          msg = "disk not found"
7820
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7821
                                 (name, msg))
7822

    
7823
      if result.payload.is_degraded:
7824
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7825

    
7826
  def _RemoveOldStorage(self, node_name, iv_names):
7827
    for name, (_, old_lvs, _) in iv_names.iteritems():
7828
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7829

    
7830
      for lv in old_lvs:
7831
        self.cfg.SetDiskID(lv, node_name)
7832

    
7833
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7834
        if msg:
7835
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7836
                             hint="remove unused LVs manually")
7837

    
7838
  def _ReleaseNodeLock(self, node_name):
7839
    """Releases the lock for a given node."""
7840
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7841

    
7842
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7843
    """Replace a disk on the primary or secondary for DRBD 8.
7844

7845
    The algorithm for replace is quite complicated:
7846

7847
      1. for each disk to be replaced:
7848

7849
        1. create new LVs on the target node with unique names
7850
        1. detach old LVs from the drbd device
7851
        1. rename old LVs to name_replaced.<time_t>
7852
        1. rename new LVs to old LVs
7853
        1. attach the new LVs (with the old names now) to the drbd device
7854

7855
      1. wait for sync across all devices
7856

7857
      1. for each modified disk:
7858

7859
        1. remove old LVs (which have the name name_replaces.<time_t>)
7860

7861
    Failures are not very well handled.
7862

7863
    """
7864
    steps_total = 6
7865

    
7866
    # Step: check device activation
7867
    self.lu.LogStep(1, steps_total, "Check device existence")
7868
    self._CheckDisksExistence([self.other_node, self.target_node])
7869
    self._CheckVolumeGroup([self.target_node, self.other_node])
7870

    
7871
    # Step: check other node consistency
7872
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7873
    self._CheckDisksConsistency(self.other_node,
7874
                                self.other_node == self.instance.primary_node,
7875
                                False)
7876

    
7877
    # Step: create new storage
7878
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7879
    iv_names = self._CreateNewStorage(self.target_node)
7880

    
7881
    # Step: for each lv, detach+rename*2+attach
7882
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7883
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7884
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7885

    
7886
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7887
                                                     old_lvs)
7888
      result.Raise("Can't detach drbd from local storage on node"
7889
                   " %s for device %s" % (self.target_node, dev.iv_name))
7890
      #dev.children = []
7891
      #cfg.Update(instance)
7892

    
7893
      # ok, we created the new LVs, so now we know we have the needed
7894
      # storage; as such, we proceed on the target node to rename
7895
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7896
      # using the assumption that logical_id == physical_id (which in
7897
      # turn is the unique_id on that node)
7898

    
7899
      # FIXME(iustin): use a better name for the replaced LVs
7900
      temp_suffix = int(time.time())
7901
      ren_fn = lambda d, suff: (d.physical_id[0],
7902
                                d.physical_id[1] + "_replaced-%s" % suff)
7903

    
7904
      # Build the rename list based on what LVs exist on the node
7905
      rename_old_to_new = []
7906
      for to_ren in old_lvs:
7907
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7908
        if not result.fail_msg and result.payload:
7909
          # device exists
7910
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7911

    
7912
      self.lu.LogInfo("Renaming the old LVs on the target node")
7913
      result = self.rpc.call_blockdev_rename(self.target_node,
7914
                                             rename_old_to_new)
7915
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7916

    
7917
      # Now we rename the new LVs to the old LVs
7918
      self.lu.LogInfo("Renaming the new LVs on the target node")
7919
      rename_new_to_old = [(new, old.physical_id)
7920
                           for old, new in zip(old_lvs, new_lvs)]
7921
      result = self.rpc.call_blockdev_rename(self.target_node,
7922
                                             rename_new_to_old)
7923
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7924

    
7925
      for old, new in zip(old_lvs, new_lvs):
7926
        new.logical_id = old.logical_id
7927
        self.cfg.SetDiskID(new, self.target_node)
7928

    
7929
      for disk in old_lvs:
7930
        disk.logical_id = ren_fn(disk, temp_suffix)
7931
        self.cfg.SetDiskID(disk, self.target_node)
7932

    
7933
      # Now that the new lvs have the old name, we can add them to the device
7934
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7935
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7936
                                                  new_lvs)
7937
      msg = result.fail_msg
7938
      if msg:
7939
        for new_lv in new_lvs:
7940
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7941
                                               new_lv).fail_msg
7942
          if msg2:
7943
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7944
                               hint=("cleanup manually the unused logical"
7945
                                     "volumes"))
7946
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7947

    
7948
      dev.children = new_lvs
7949

    
7950
      self.cfg.Update(self.instance, feedback_fn)
7951

    
7952
    cstep = 5
7953
    if self.early_release:
7954
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7955
      cstep += 1
7956
      self._RemoveOldStorage(self.target_node, iv_names)
7957
      # WARNING: we release both node locks here, do not do other RPCs
7958
      # than WaitForSync to the primary node
7959
      self._ReleaseNodeLock([self.target_node, self.other_node])
7960

    
7961
    # Wait for sync
7962
    # This can fail as the old devices are degraded and _WaitForSync
7963
    # does a combined result over all disks, so we don't check its return value
7964
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7965
    cstep += 1
7966
    _WaitForSync(self.lu, self.instance)
7967

    
7968
    # Check all devices manually
7969
    self._CheckDevices(self.instance.primary_node, iv_names)
7970

    
7971
    # Step: remove old storage
7972
    if not self.early_release:
7973
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7974
      cstep += 1
7975
      self._RemoveOldStorage(self.target_node, iv_names)
7976

    
7977
  def _ExecDrbd8Secondary(self, feedback_fn):
7978
    """Replace the secondary node for DRBD 8.
7979

7980
    The algorithm for replace is quite complicated:
7981
      - for all disks of the instance:
7982
        - create new LVs on the new node with same names
7983
        - shutdown the drbd device on the old secondary
7984
        - disconnect the drbd network on the primary
7985
        - create the drbd device on the new secondary
7986
        - network attach the drbd on the primary, using an artifice:
7987
          the drbd code for Attach() will connect to the network if it
7988
          finds a device which is connected to the good local disks but
7989
          not network enabled
7990
      - wait for sync across all devices
7991
      - remove all disks from the old secondary
7992

7993
    Failures are not very well handled.
7994

7995
    """
7996
    steps_total = 6
7997

    
7998
    # Step: check device activation
7999
    self.lu.LogStep(1, steps_total, "Check device existence")
8000
    self._CheckDisksExistence([self.instance.primary_node])
8001
    self._CheckVolumeGroup([self.instance.primary_node])
8002

    
8003
    # Step: check other node consistency
8004
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8005
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8006

    
8007
    # Step: create new storage
8008
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8009
    for idx, dev in enumerate(self.instance.disks):
8010
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8011
                      (self.new_node, idx))
8012
      # we pass force_create=True to force LVM creation
8013
      for new_lv in dev.children:
8014
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8015
                        _GetInstanceInfoText(self.instance), False)
8016

    
8017
    # Step 4: dbrd minors and drbd setups changes
8018
    # after this, we must manually remove the drbd minors on both the
8019
    # error and the success paths
8020
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8021
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8022
                                         for dev in self.instance.disks],
8023
                                        self.instance.name)
8024
    logging.debug("Allocated minors %r", minors)
8025

    
8026
    iv_names = {}
8027
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8028
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8029
                      (self.new_node, idx))
8030
      # create new devices on new_node; note that we create two IDs:
8031
      # one without port, so the drbd will be activated without
8032
      # networking information on the new node at this stage, and one
8033
      # with network, for the latter activation in step 4
8034
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8035
      if self.instance.primary_node == o_node1:
8036
        p_minor = o_minor1
8037
      else:
8038
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8039
        p_minor = o_minor2
8040

    
8041
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8042
                      p_minor, new_minor, o_secret)
8043
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8044
                    p_minor, new_minor, o_secret)
8045

    
8046
      iv_names[idx] = (dev, dev.children, new_net_id)
8047
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8048
                    new_net_id)
8049
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8050
                              logical_id=new_alone_id,
8051
                              children=dev.children,
8052
                              size=dev.size)
8053
      try:
8054
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8055
                              _GetInstanceInfoText(self.instance), False)
8056
      except errors.GenericError:
8057
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8058
        raise
8059

    
8060
    # We have new devices, shutdown the drbd on the old secondary
8061
    for idx, dev in enumerate(self.instance.disks):
8062
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8063
      self.cfg.SetDiskID(dev, self.target_node)
8064
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8065
      if msg:
8066
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8067
                           "node: %s" % (idx, msg),
8068
                           hint=("Please cleanup this device manually as"
8069
                                 " soon as possible"))
8070

    
8071
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8072
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8073
                                               self.node_secondary_ip,
8074
                                               self.instance.disks)\
8075
                                              [self.instance.primary_node]
8076

    
8077
    msg = result.fail_msg
8078
    if msg:
8079
      # detaches didn't succeed (unlikely)
8080
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8081
      raise errors.OpExecError("Can't detach the disks from the network on"
8082
                               " old node: %s" % (msg,))
8083

    
8084
    # if we managed to detach at least one, we update all the disks of
8085
    # the instance to point to the new secondary
8086
    self.lu.LogInfo("Updating instance configuration")
8087
    for dev, _, new_logical_id in iv_names.itervalues():
8088
      dev.logical_id = new_logical_id
8089
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8090

    
8091
    self.cfg.Update(self.instance, feedback_fn)
8092

    
8093
    # and now perform the drbd attach
8094
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8095
                    " (standalone => connected)")
8096
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8097
                                            self.new_node],
8098
                                           self.node_secondary_ip,
8099
                                           self.instance.disks,
8100
                                           self.instance.name,
8101
                                           False)
8102
    for to_node, to_result in result.items():
8103
      msg = to_result.fail_msg
8104
      if msg:
8105
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8106
                           to_node, msg,
8107
                           hint=("please do a gnt-instance info to see the"
8108
                                 " status of disks"))
8109
    cstep = 5
8110
    if self.early_release:
8111
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8112
      cstep += 1
8113
      self._RemoveOldStorage(self.target_node, iv_names)
8114
      # WARNING: we release all node locks here, do not do other RPCs
8115
      # than WaitForSync to the primary node
8116
      self._ReleaseNodeLock([self.instance.primary_node,
8117
                             self.target_node,
8118
                             self.new_node])
8119

    
8120
    # Wait for sync
8121
    # This can fail as the old devices are degraded and _WaitForSync
8122
    # does a combined result over all disks, so we don't check its return value
8123
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8124
    cstep += 1
8125
    _WaitForSync(self.lu, self.instance)
8126

    
8127
    # Check all devices manually
8128
    self._CheckDevices(self.instance.primary_node, iv_names)
8129

    
8130
    # Step: remove old storage
8131
    if not self.early_release:
8132
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8133
      self._RemoveOldStorage(self.target_node, iv_names)
8134

    
8135

    
8136
class LURepairNodeStorage(NoHooksLU):
8137
  """Repairs the volume group on a node.
8138

8139
  """
8140
  _OP_PARAMS = [
8141
    _PNodeName,
8142
    ("storage_type", ht.NoDefault, _CheckStorageType),
8143
    ("name", ht.NoDefault, ht.TNonEmptyString),
8144
    ("ignore_consistency", False, ht.TBool),
8145
    ]
8146
  REQ_BGL = False
8147

    
8148
  def CheckArguments(self):
8149
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8150

    
8151
    storage_type = self.op.storage_type
8152

    
8153
    if (constants.SO_FIX_CONSISTENCY not in
8154
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8155
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8156
                                 " repaired" % storage_type,
8157
                                 errors.ECODE_INVAL)
8158

    
8159
  def ExpandNames(self):
8160
    self.needed_locks = {
8161
      locking.LEVEL_NODE: [self.op.node_name],
8162
      }
8163

    
8164
  def _CheckFaultyDisks(self, instance, node_name):
8165
    """Ensure faulty disks abort the opcode or at least warn."""
8166
    try:
8167
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8168
                                  node_name, True):
8169
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8170
                                   " node '%s'" % (instance.name, node_name),
8171
                                   errors.ECODE_STATE)
8172
    except errors.OpPrereqError, err:
8173
      if self.op.ignore_consistency:
8174
        self.proc.LogWarning(str(err.args[0]))
8175
      else:
8176
        raise
8177

    
8178
  def CheckPrereq(self):
8179
    """Check prerequisites.
8180

8181
    """
8182
    # Check whether any instance on this node has faulty disks
8183
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8184
      if not inst.admin_up:
8185
        continue
8186
      check_nodes = set(inst.all_nodes)
8187
      check_nodes.discard(self.op.node_name)
8188
      for inst_node_name in check_nodes:
8189
        self._CheckFaultyDisks(inst, inst_node_name)
8190

    
8191
  def Exec(self, feedback_fn):
8192
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8193
                (self.op.name, self.op.node_name))
8194

    
8195
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8196
    result = self.rpc.call_storage_execute(self.op.node_name,
8197
                                           self.op.storage_type, st_args,
8198
                                           self.op.name,
8199
                                           constants.SO_FIX_CONSISTENCY)
8200
    result.Raise("Failed to repair storage unit '%s' on %s" %
8201
                 (self.op.name, self.op.node_name))
8202

    
8203

    
8204
class LUNodeEvacuationStrategy(NoHooksLU):
8205
  """Computes the node evacuation strategy.
8206

8207
  """
8208
  _OP_PARAMS = [
8209
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8210
    ("remote_node", None, ht.TMaybeString),
8211
    ("iallocator", None, ht.TMaybeString),
8212
    ]
8213
  REQ_BGL = False
8214

    
8215
  def CheckArguments(self):
8216
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8217

    
8218
  def ExpandNames(self):
8219
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8220
    self.needed_locks = locks = {}
8221
    if self.op.remote_node is None:
8222
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8223
    else:
8224
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8225
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8226

    
8227
  def Exec(self, feedback_fn):
8228
    if self.op.remote_node is not None:
8229
      instances = []
8230
      for node in self.op.nodes:
8231
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8232
      result = []
8233
      for i in instances:
8234
        if i.primary_node == self.op.remote_node:
8235
          raise errors.OpPrereqError("Node %s is the primary node of"
8236
                                     " instance %s, cannot use it as"
8237
                                     " secondary" %
8238
                                     (self.op.remote_node, i.name),
8239
                                     errors.ECODE_INVAL)
8240
        result.append([i.name, self.op.remote_node])
8241
    else:
8242
      ial = IAllocator(self.cfg, self.rpc,
8243
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8244
                       evac_nodes=self.op.nodes)
8245
      ial.Run(self.op.iallocator, validate=True)
8246
      if not ial.success:
8247
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8248
                                 errors.ECODE_NORES)
8249
      result = ial.result
8250
    return result
8251

    
8252

    
8253
class LUGrowDisk(LogicalUnit):
8254
  """Grow a disk of an instance.
8255

8256
  """
8257
  HPATH = "disk-grow"
8258
  HTYPE = constants.HTYPE_INSTANCE
8259
  _OP_PARAMS = [
8260
    _PInstanceName,
8261
    ("disk", ht.NoDefault, ht.TInt),
8262
    ("amount", ht.NoDefault, ht.TInt),
8263
    ("wait_for_sync", True, ht.TBool),
8264
    ]
8265
  REQ_BGL = False
8266

    
8267
  def ExpandNames(self):
8268
    self._ExpandAndLockInstance()
8269
    self.needed_locks[locking.LEVEL_NODE] = []
8270
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8271

    
8272
  def DeclareLocks(self, level):
8273
    if level == locking.LEVEL_NODE:
8274
      self._LockInstancesNodes()
8275

    
8276
  def BuildHooksEnv(self):
8277
    """Build hooks env.
8278

8279
    This runs on the master, the primary and all the secondaries.
8280

8281
    """
8282
    env = {
8283
      "DISK": self.op.disk,
8284
      "AMOUNT": self.op.amount,
8285
      }
8286
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8287
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8288
    return env, nl, nl
8289

    
8290
  def CheckPrereq(self):
8291
    """Check prerequisites.
8292

8293
    This checks that the instance is in the cluster.
8294

8295
    """
8296
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8297
    assert instance is not None, \
8298
      "Cannot retrieve locked instance %s" % self.op.instance_name
8299
    nodenames = list(instance.all_nodes)
8300
    for node in nodenames:
8301
      _CheckNodeOnline(self, node)
8302

    
8303
    self.instance = instance
8304

    
8305
    if instance.disk_template not in constants.DTS_GROWABLE:
8306
      raise errors.OpPrereqError("Instance's disk layout does not support"
8307
                                 " growing.", errors.ECODE_INVAL)
8308

    
8309
    self.disk = instance.FindDisk(self.op.disk)
8310

    
8311
    if instance.disk_template != constants.DT_FILE:
8312
      # TODO: check the free disk space for file, when that feature will be
8313
      # supported
8314
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8315

    
8316
  def Exec(self, feedback_fn):
8317
    """Execute disk grow.
8318

8319
    """
8320
    instance = self.instance
8321
    disk = self.disk
8322

    
8323
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8324
    if not disks_ok:
8325
      raise errors.OpExecError("Cannot activate block device to grow")
8326

    
8327
    for node in instance.all_nodes:
8328
      self.cfg.SetDiskID(disk, node)
8329
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8330
      result.Raise("Grow request failed to node %s" % node)
8331

    
8332
      # TODO: Rewrite code to work properly
8333
      # DRBD goes into sync mode for a short amount of time after executing the
8334
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8335
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8336
      # time is a work-around.
8337
      time.sleep(5)
8338

    
8339
    disk.RecordGrow(self.op.amount)
8340
    self.cfg.Update(instance, feedback_fn)
8341
    if self.op.wait_for_sync:
8342
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8343
      if disk_abort:
8344
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8345
                             " status.\nPlease check the instance.")
8346
      if not instance.admin_up:
8347
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8348
    elif not instance.admin_up:
8349
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8350
                           " not supposed to be running because no wait for"
8351
                           " sync mode was requested.")
8352

    
8353

    
8354
class LUQueryInstanceData(NoHooksLU):
8355
  """Query runtime instance data.
8356

8357
  """
8358
  _OP_PARAMS = [
8359
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8360
    ("static", False, ht.TBool),
8361
    ]
8362
  REQ_BGL = False
8363

    
8364
  def ExpandNames(self):
8365
    self.needed_locks = {}
8366
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8367

    
8368
    if self.op.instances:
8369
      self.wanted_names = []
8370
      for name in self.op.instances:
8371
        full_name = _ExpandInstanceName(self.cfg, name)
8372
        self.wanted_names.append(full_name)
8373
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8374
    else:
8375
      self.wanted_names = None
8376
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8377

    
8378
    self.needed_locks[locking.LEVEL_NODE] = []
8379
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8380

    
8381
  def DeclareLocks(self, level):
8382
    if level == locking.LEVEL_NODE:
8383
      self._LockInstancesNodes()
8384

    
8385
  def CheckPrereq(self):
8386
    """Check prerequisites.
8387

8388
    This only checks the optional instance list against the existing names.
8389

8390
    """
8391
    if self.wanted_names is None:
8392
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8393

    
8394
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8395
                             in self.wanted_names]
8396

    
8397
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8398
    """Returns the status of a block device
8399

8400
    """
8401
    if self.op.static or not node:
8402
      return None
8403

    
8404
    self.cfg.SetDiskID(dev, node)
8405

    
8406
    result = self.rpc.call_blockdev_find(node, dev)
8407
    if result.offline:
8408
      return None
8409

    
8410
    result.Raise("Can't compute disk status for %s" % instance_name)
8411

    
8412
    status = result.payload
8413
    if status is None:
8414
      return None
8415

    
8416
    return (status.dev_path, status.major, status.minor,
8417
            status.sync_percent, status.estimated_time,
8418
            status.is_degraded, status.ldisk_status)
8419

    
8420
  def _ComputeDiskStatus(self, instance, snode, dev):
8421
    """Compute block device status.
8422

8423
    """
8424
    if dev.dev_type in constants.LDS_DRBD:
8425
      # we change the snode then (otherwise we use the one passed in)
8426
      if dev.logical_id[0] == instance.primary_node:
8427
        snode = dev.logical_id[1]
8428
      else:
8429
        snode = dev.logical_id[0]
8430

    
8431
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8432
                                              instance.name, dev)
8433
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8434

    
8435
    if dev.children:
8436
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8437
                      for child in dev.children]
8438
    else:
8439
      dev_children = []
8440

    
8441
    data = {
8442
      "iv_name": dev.iv_name,
8443
      "dev_type": dev.dev_type,
8444
      "logical_id": dev.logical_id,
8445
      "physical_id": dev.physical_id,
8446
      "pstatus": dev_pstatus,
8447
      "sstatus": dev_sstatus,
8448
      "children": dev_children,
8449
      "mode": dev.mode,
8450
      "size": dev.size,
8451
      }
8452

    
8453
    return data
8454

    
8455
  def Exec(self, feedback_fn):
8456
    """Gather and return data"""
8457
    result = {}
8458

    
8459
    cluster = self.cfg.GetClusterInfo()
8460

    
8461
    for instance in self.wanted_instances:
8462
      if not self.op.static:
8463
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8464
                                                  instance.name,
8465
                                                  instance.hypervisor)
8466
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8467
        remote_info = remote_info.payload
8468
        if remote_info and "state" in remote_info:
8469
          remote_state = "up"
8470
        else:
8471
          remote_state = "down"
8472
      else:
8473
        remote_state = None
8474
      if instance.admin_up:
8475
        config_state = "up"
8476
      else:
8477
        config_state = "down"
8478

    
8479
      disks = [self._ComputeDiskStatus(instance, None, device)
8480
               for device in instance.disks]
8481

    
8482
      idict = {
8483
        "name": instance.name,
8484
        "config_state": config_state,
8485
        "run_state": remote_state,
8486
        "pnode": instance.primary_node,
8487
        "snodes": instance.secondary_nodes,
8488
        "os": instance.os,
8489
        # this happens to be the same format used for hooks
8490
        "nics": _NICListToTuple(self, instance.nics),
8491
        "disk_template": instance.disk_template,
8492
        "disks": disks,
8493
        "hypervisor": instance.hypervisor,
8494
        "network_port": instance.network_port,
8495
        "hv_instance": instance.hvparams,
8496
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8497
        "be_instance": instance.beparams,
8498
        "be_actual": cluster.FillBE(instance),
8499
        "os_instance": instance.osparams,
8500
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8501
        "serial_no": instance.serial_no,
8502
        "mtime": instance.mtime,
8503
        "ctime": instance.ctime,
8504
        "uuid": instance.uuid,
8505
        }
8506

    
8507
      result[instance.name] = idict
8508

    
8509
    return result
8510

    
8511

    
8512
class LUSetInstanceParams(LogicalUnit):
8513
  """Modifies an instances's parameters.
8514

8515
  """
8516
  HPATH = "instance-modify"
8517
  HTYPE = constants.HTYPE_INSTANCE
8518
  _OP_PARAMS = [
8519
    _PInstanceName,
8520
    ("nics", ht.EmptyList, ht.TList),
8521
    ("disks", ht.EmptyList, ht.TList),
8522
    ("beparams", ht.EmptyDict, ht.TDict),
8523
    ("hvparams", ht.EmptyDict, ht.TDict),
8524
    ("disk_template", None, ht.TMaybeString),
8525
    ("remote_node", None, ht.TMaybeString),
8526
    ("os_name", None, ht.TMaybeString),
8527
    ("force_variant", False, ht.TBool),
8528
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
8529
    _PForce,
8530
    ]
8531
  REQ_BGL = False
8532

    
8533
  def CheckArguments(self):
8534
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8535
            self.op.hvparams or self.op.beparams or self.op.os_name):
8536
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8537

    
8538
    if self.op.hvparams:
8539
      _CheckGlobalHvParams(self.op.hvparams)
8540

    
8541
    # Disk validation
8542
    disk_addremove = 0
8543
    for disk_op, disk_dict in self.op.disks:
8544
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8545
      if disk_op == constants.DDM_REMOVE:
8546
        disk_addremove += 1
8547
        continue
8548
      elif disk_op == constants.DDM_ADD:
8549
        disk_addremove += 1
8550
      else:
8551
        if not isinstance(disk_op, int):
8552
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8553
        if not isinstance(disk_dict, dict):
8554
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8555
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8556

    
8557
      if disk_op == constants.DDM_ADD:
8558
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8559
        if mode not in constants.DISK_ACCESS_SET:
8560
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8561
                                     errors.ECODE_INVAL)
8562
        size = disk_dict.get('size', None)
8563
        if size is None:
8564
          raise errors.OpPrereqError("Required disk parameter size missing",
8565
                                     errors.ECODE_INVAL)
8566
        try:
8567
          size = int(size)
8568
        except (TypeError, ValueError), err:
8569
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8570
                                     str(err), errors.ECODE_INVAL)
8571
        disk_dict['size'] = size
8572
      else:
8573
        # modification of disk
8574
        if 'size' in disk_dict:
8575
          raise errors.OpPrereqError("Disk size change not possible, use"
8576
                                     " grow-disk", errors.ECODE_INVAL)
8577

    
8578
    if disk_addremove > 1:
8579
      raise errors.OpPrereqError("Only one disk add or remove operation"
8580
                                 " supported at a time", errors.ECODE_INVAL)
8581

    
8582
    if self.op.disks and self.op.disk_template is not None:
8583
      raise errors.OpPrereqError("Disk template conversion and other disk"
8584
                                 " changes not supported at the same time",
8585
                                 errors.ECODE_INVAL)
8586

    
8587
    if self.op.disk_template:
8588
      _CheckDiskTemplate(self.op.disk_template)
8589
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8590
          self.op.remote_node is None):
8591
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8592
                                   " one requires specifying a secondary node",
8593
                                   errors.ECODE_INVAL)
8594

    
8595
    # NIC validation
8596
    nic_addremove = 0
8597
    for nic_op, nic_dict in self.op.nics:
8598
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8599
      if nic_op == constants.DDM_REMOVE:
8600
        nic_addremove += 1
8601
        continue
8602
      elif nic_op == constants.DDM_ADD:
8603
        nic_addremove += 1
8604
      else:
8605
        if not isinstance(nic_op, int):
8606
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8607
        if not isinstance(nic_dict, dict):
8608
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8609
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8610

    
8611
      # nic_dict should be a dict
8612
      nic_ip = nic_dict.get('ip', None)
8613
      if nic_ip is not None:
8614
        if nic_ip.lower() == constants.VALUE_NONE:
8615
          nic_dict['ip'] = None
8616
        else:
8617
          if not netutils.IPAddress.IsValid(nic_ip):
8618
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8619
                                       errors.ECODE_INVAL)
8620

    
8621
      nic_bridge = nic_dict.get('bridge', None)
8622
      nic_link = nic_dict.get('link', None)
8623
      if nic_bridge and nic_link:
8624
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8625
                                   " at the same time", errors.ECODE_INVAL)
8626
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8627
        nic_dict['bridge'] = None
8628
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8629
        nic_dict['link'] = None
8630

    
8631
      if nic_op == constants.DDM_ADD:
8632
        nic_mac = nic_dict.get('mac', None)
8633
        if nic_mac is None:
8634
          nic_dict['mac'] = constants.VALUE_AUTO
8635

    
8636
      if 'mac' in nic_dict:
8637
        nic_mac = nic_dict['mac']
8638
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8639
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8640

    
8641
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8642
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8643
                                     " modifying an existing nic",
8644
                                     errors.ECODE_INVAL)
8645

    
8646
    if nic_addremove > 1:
8647
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8648
                                 " supported at a time", errors.ECODE_INVAL)
8649

    
8650
  def ExpandNames(self):
8651
    self._ExpandAndLockInstance()
8652
    self.needed_locks[locking.LEVEL_NODE] = []
8653
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8654

    
8655
  def DeclareLocks(self, level):
8656
    if level == locking.LEVEL_NODE:
8657
      self._LockInstancesNodes()
8658
      if self.op.disk_template and self.op.remote_node:
8659
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8660
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8661

    
8662
  def BuildHooksEnv(self):
8663
    """Build hooks env.
8664

8665
    This runs on the master, primary and secondaries.
8666

8667
    """
8668
    args = dict()
8669
    if constants.BE_MEMORY in self.be_new:
8670
      args['memory'] = self.be_new[constants.BE_MEMORY]
8671
    if constants.BE_VCPUS in self.be_new:
8672
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8673
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8674
    # information at all.
8675
    if self.op.nics:
8676
      args['nics'] = []
8677
      nic_override = dict(self.op.nics)
8678
      for idx, nic in enumerate(self.instance.nics):
8679
        if idx in nic_override:
8680
          this_nic_override = nic_override[idx]
8681
        else:
8682
          this_nic_override = {}
8683
        if 'ip' in this_nic_override:
8684
          ip = this_nic_override['ip']
8685
        else:
8686
          ip = nic.ip
8687
        if 'mac' in this_nic_override:
8688
          mac = this_nic_override['mac']
8689
        else:
8690
          mac = nic.mac
8691
        if idx in self.nic_pnew:
8692
          nicparams = self.nic_pnew[idx]
8693
        else:
8694
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8695
        mode = nicparams[constants.NIC_MODE]
8696
        link = nicparams[constants.NIC_LINK]
8697
        args['nics'].append((ip, mac, mode, link))
8698
      if constants.DDM_ADD in nic_override:
8699
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8700
        mac = nic_override[constants.DDM_ADD]['mac']
8701
        nicparams = self.nic_pnew[constants.DDM_ADD]
8702
        mode = nicparams[constants.NIC_MODE]
8703
        link = nicparams[constants.NIC_LINK]
8704
        args['nics'].append((ip, mac, mode, link))
8705
      elif constants.DDM_REMOVE in nic_override:
8706
        del args['nics'][-1]
8707

    
8708
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8709
    if self.op.disk_template:
8710
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8711
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8712
    return env, nl, nl
8713

    
8714
  def CheckPrereq(self):
8715
    """Check prerequisites.
8716

8717
    This only checks the instance list against the existing names.
8718

8719
    """
8720
    # checking the new params on the primary/secondary nodes
8721

    
8722
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8723
    cluster = self.cluster = self.cfg.GetClusterInfo()
8724
    assert self.instance is not None, \
8725
      "Cannot retrieve locked instance %s" % self.op.instance_name
8726
    pnode = instance.primary_node
8727
    nodelist = list(instance.all_nodes)
8728

    
8729
    # OS change
8730
    if self.op.os_name and not self.op.force:
8731
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8732
                      self.op.force_variant)
8733
      instance_os = self.op.os_name
8734
    else:
8735
      instance_os = instance.os
8736

    
8737
    if self.op.disk_template:
8738
      if instance.disk_template == self.op.disk_template:
8739
        raise errors.OpPrereqError("Instance already has disk template %s" %
8740
                                   instance.disk_template, errors.ECODE_INVAL)
8741

    
8742
      if (instance.disk_template,
8743
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8744
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8745
                                   " %s to %s" % (instance.disk_template,
8746
                                                  self.op.disk_template),
8747
                                   errors.ECODE_INVAL)
8748
      _CheckInstanceDown(self, instance, "cannot change disk template")
8749
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8750
        if self.op.remote_node == pnode:
8751
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8752
                                     " as the primary node of the instance" %
8753
                                     self.op.remote_node, errors.ECODE_STATE)
8754
        _CheckNodeOnline(self, self.op.remote_node)
8755
        _CheckNodeNotDrained(self, self.op.remote_node)
8756
        disks = [{"size": d.size} for d in instance.disks]
8757
        required = _ComputeDiskSize(self.op.disk_template, disks)
8758
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8759

    
8760
    # hvparams processing
8761
    if self.op.hvparams:
8762
      hv_type = instance.hypervisor
8763
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8764
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8765
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8766

    
8767
      # local check
8768
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8769
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8770
      self.hv_new = hv_new # the new actual values
8771
      self.hv_inst = i_hvdict # the new dict (without defaults)
8772
    else:
8773
      self.hv_new = self.hv_inst = {}
8774

    
8775
    # beparams processing
8776
    if self.op.beparams:
8777
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8778
                                   use_none=True)
8779
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8780
      be_new = cluster.SimpleFillBE(i_bedict)
8781
      self.be_new = be_new # the new actual values
8782
      self.be_inst = i_bedict # the new dict (without defaults)
8783
    else:
8784
      self.be_new = self.be_inst = {}
8785

    
8786
    # osparams processing
8787
    if self.op.osparams:
8788
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8789
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8790
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8791
      self.os_inst = i_osdict # the new dict (without defaults)
8792
    else:
8793
      self.os_new = self.os_inst = {}
8794

    
8795
    self.warn = []
8796

    
8797
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8798
      mem_check_list = [pnode]
8799
      if be_new[constants.BE_AUTO_BALANCE]:
8800
        # either we changed auto_balance to yes or it was from before
8801
        mem_check_list.extend(instance.secondary_nodes)
8802
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8803
                                                  instance.hypervisor)
8804
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8805
                                         instance.hypervisor)
8806
      pninfo = nodeinfo[pnode]
8807
      msg = pninfo.fail_msg
8808
      if msg:
8809
        # Assume the primary node is unreachable and go ahead
8810
        self.warn.append("Can't get info from primary node %s: %s" %
8811
                         (pnode,  msg))
8812
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8813
        self.warn.append("Node data from primary node %s doesn't contain"
8814
                         " free memory information" % pnode)
8815
      elif instance_info.fail_msg:
8816
        self.warn.append("Can't get instance runtime information: %s" %
8817
                        instance_info.fail_msg)
8818
      else:
8819
        if instance_info.payload:
8820
          current_mem = int(instance_info.payload['memory'])
8821
        else:
8822
          # Assume instance not running
8823
          # (there is a slight race condition here, but it's not very probable,
8824
          # and we have no other way to check)
8825
          current_mem = 0
8826
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8827
                    pninfo.payload['memory_free'])
8828
        if miss_mem > 0:
8829
          raise errors.OpPrereqError("This change will prevent the instance"
8830
                                     " from starting, due to %d MB of memory"
8831
                                     " missing on its primary node" % miss_mem,
8832
                                     errors.ECODE_NORES)
8833

    
8834
      if be_new[constants.BE_AUTO_BALANCE]:
8835
        for node, nres in nodeinfo.items():
8836
          if node not in instance.secondary_nodes:
8837
            continue
8838
          msg = nres.fail_msg
8839
          if msg:
8840
            self.warn.append("Can't get info from secondary node %s: %s" %
8841
                             (node, msg))
8842
          elif not isinstance(nres.payload.get('memory_free', None), int):
8843
            self.warn.append("Secondary node %s didn't return free"
8844
                             " memory information" % node)
8845
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8846
            self.warn.append("Not enough memory to failover instance to"
8847
                             " secondary node %s" % node)
8848

    
8849
    # NIC processing
8850
    self.nic_pnew = {}
8851
    self.nic_pinst = {}
8852
    for nic_op, nic_dict in self.op.nics:
8853
      if nic_op == constants.DDM_REMOVE:
8854
        if not instance.nics:
8855
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8856
                                     errors.ECODE_INVAL)
8857
        continue
8858
      if nic_op != constants.DDM_ADD:
8859
        # an existing nic
8860
        if not instance.nics:
8861
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8862
                                     " no NICs" % nic_op,
8863
                                     errors.ECODE_INVAL)
8864
        if nic_op < 0 or nic_op >= len(instance.nics):
8865
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8866
                                     " are 0 to %d" %
8867
                                     (nic_op, len(instance.nics) - 1),
8868
                                     errors.ECODE_INVAL)
8869
        old_nic_params = instance.nics[nic_op].nicparams
8870
        old_nic_ip = instance.nics[nic_op].ip
8871
      else:
8872
        old_nic_params = {}
8873
        old_nic_ip = None
8874

    
8875
      update_params_dict = dict([(key, nic_dict[key])
8876
                                 for key in constants.NICS_PARAMETERS
8877
                                 if key in nic_dict])
8878

    
8879
      if 'bridge' in nic_dict:
8880
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8881

    
8882
      new_nic_params = _GetUpdatedParams(old_nic_params,
8883
                                         update_params_dict)
8884
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8885
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8886
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8887
      self.nic_pinst[nic_op] = new_nic_params
8888
      self.nic_pnew[nic_op] = new_filled_nic_params
8889
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8890

    
8891
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8892
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8893
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8894
        if msg:
8895
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8896
          if self.op.force:
8897
            self.warn.append(msg)
8898
          else:
8899
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8900
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8901
        if 'ip' in nic_dict:
8902
          nic_ip = nic_dict['ip']
8903
        else:
8904
          nic_ip = old_nic_ip
8905
        if nic_ip is None:
8906
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8907
                                     ' on a routed nic', errors.ECODE_INVAL)
8908
      if 'mac' in nic_dict:
8909
        nic_mac = nic_dict['mac']
8910
        if nic_mac is None:
8911
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8912
                                     errors.ECODE_INVAL)
8913
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8914
          # otherwise generate the mac
8915
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8916
        else:
8917
          # or validate/reserve the current one
8918
          try:
8919
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8920
          except errors.ReservationError:
8921
            raise errors.OpPrereqError("MAC address %s already in use"
8922
                                       " in cluster" % nic_mac,
8923
                                       errors.ECODE_NOTUNIQUE)
8924

    
8925
    # DISK processing
8926
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8927
      raise errors.OpPrereqError("Disk operations not supported for"
8928
                                 " diskless instances",
8929
                                 errors.ECODE_INVAL)
8930
    for disk_op, _ in self.op.disks:
8931
      if disk_op == constants.DDM_REMOVE:
8932
        if len(instance.disks) == 1:
8933
          raise errors.OpPrereqError("Cannot remove the last disk of"
8934
                                     " an instance", errors.ECODE_INVAL)
8935
        _CheckInstanceDown(self, instance, "cannot remove disks")
8936

    
8937
      if (disk_op == constants.DDM_ADD and
8938
          len(instance.nics) >= constants.MAX_DISKS):
8939
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8940
                                   " add more" % constants.MAX_DISKS,
8941
                                   errors.ECODE_STATE)
8942
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8943
        # an existing disk
8944
        if disk_op < 0 or disk_op >= len(instance.disks):
8945
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8946
                                     " are 0 to %d" %
8947
                                     (disk_op, len(instance.disks)),
8948
                                     errors.ECODE_INVAL)
8949

    
8950
    return
8951

    
8952
  def _ConvertPlainToDrbd(self, feedback_fn):
8953
    """Converts an instance from plain to drbd.
8954

8955
    """
8956
    feedback_fn("Converting template to drbd")
8957
    instance = self.instance
8958
    pnode = instance.primary_node
8959
    snode = self.op.remote_node
8960

    
8961
    # create a fake disk info for _GenerateDiskTemplate
8962
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8963
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8964
                                      instance.name, pnode, [snode],
8965
                                      disk_info, None, None, 0)
8966
    info = _GetInstanceInfoText(instance)
8967
    feedback_fn("Creating aditional volumes...")
8968
    # first, create the missing data and meta devices
8969
    for disk in new_disks:
8970
      # unfortunately this is... not too nice
8971
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8972
                            info, True)
8973
      for child in disk.children:
8974
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8975
    # at this stage, all new LVs have been created, we can rename the
8976
    # old ones
8977
    feedback_fn("Renaming original volumes...")
8978
    rename_list = [(o, n.children[0].logical_id)
8979
                   for (o, n) in zip(instance.disks, new_disks)]
8980
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8981
    result.Raise("Failed to rename original LVs")
8982

    
8983
    feedback_fn("Initializing DRBD devices...")
8984
    # all child devices are in place, we can now create the DRBD devices
8985
    for disk in new_disks:
8986
      for node in [pnode, snode]:
8987
        f_create = node == pnode
8988
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8989

    
8990
    # at this point, the instance has been modified
8991
    instance.disk_template = constants.DT_DRBD8
8992
    instance.disks = new_disks
8993
    self.cfg.Update(instance, feedback_fn)
8994

    
8995
    # disks are created, waiting for sync
8996
    disk_abort = not _WaitForSync(self, instance)
8997
    if disk_abort:
8998
      raise errors.OpExecError("There are some degraded disks for"
8999
                               " this instance, please cleanup manually")
9000

    
9001
  def _ConvertDrbdToPlain(self, feedback_fn):
9002
    """Converts an instance from drbd to plain.
9003

9004
    """
9005
    instance = self.instance
9006
    assert len(instance.secondary_nodes) == 1
9007
    pnode = instance.primary_node
9008
    snode = instance.secondary_nodes[0]
9009
    feedback_fn("Converting template to plain")
9010

    
9011
    old_disks = instance.disks
9012
    new_disks = [d.children[0] for d in old_disks]
9013

    
9014
    # copy over size and mode
9015
    for parent, child in zip(old_disks, new_disks):
9016
      child.size = parent.size
9017
      child.mode = parent.mode
9018

    
9019
    # update instance structure
9020
    instance.disks = new_disks
9021
    instance.disk_template = constants.DT_PLAIN
9022
    self.cfg.Update(instance, feedback_fn)
9023

    
9024
    feedback_fn("Removing volumes on the secondary node...")
9025
    for disk in old_disks:
9026
      self.cfg.SetDiskID(disk, snode)
9027
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9028
      if msg:
9029
        self.LogWarning("Could not remove block device %s on node %s,"
9030
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9031

    
9032
    feedback_fn("Removing unneeded volumes on the primary node...")
9033
    for idx, disk in enumerate(old_disks):
9034
      meta = disk.children[1]
9035
      self.cfg.SetDiskID(meta, pnode)
9036
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9037
      if msg:
9038
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9039
                        " continuing anyway: %s", idx, pnode, msg)
9040

    
9041

    
9042
  def Exec(self, feedback_fn):
9043
    """Modifies an instance.
9044

9045
    All parameters take effect only at the next restart of the instance.
9046

9047
    """
9048
    # Process here the warnings from CheckPrereq, as we don't have a
9049
    # feedback_fn there.
9050
    for warn in self.warn:
9051
      feedback_fn("WARNING: %s" % warn)
9052

    
9053
    result = []
9054
    instance = self.instance
9055
    # disk changes
9056
    for disk_op, disk_dict in self.op.disks:
9057
      if disk_op == constants.DDM_REMOVE:
9058
        # remove the last disk
9059
        device = instance.disks.pop()
9060
        device_idx = len(instance.disks)
9061
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9062
          self.cfg.SetDiskID(disk, node)
9063
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9064
          if msg:
9065
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9066
                            " continuing anyway", device_idx, node, msg)
9067
        result.append(("disk/%d" % device_idx, "remove"))
9068
      elif disk_op == constants.DDM_ADD:
9069
        # add a new disk
9070
        if instance.disk_template == constants.DT_FILE:
9071
          file_driver, file_path = instance.disks[0].logical_id
9072
          file_path = os.path.dirname(file_path)
9073
        else:
9074
          file_driver = file_path = None
9075
        disk_idx_base = len(instance.disks)
9076
        new_disk = _GenerateDiskTemplate(self,
9077
                                         instance.disk_template,
9078
                                         instance.name, instance.primary_node,
9079
                                         instance.secondary_nodes,
9080
                                         [disk_dict],
9081
                                         file_path,
9082
                                         file_driver,
9083
                                         disk_idx_base)[0]
9084
        instance.disks.append(new_disk)
9085
        info = _GetInstanceInfoText(instance)
9086

    
9087
        logging.info("Creating volume %s for instance %s",
9088
                     new_disk.iv_name, instance.name)
9089
        # Note: this needs to be kept in sync with _CreateDisks
9090
        #HARDCODE
9091
        for node in instance.all_nodes:
9092
          f_create = node == instance.primary_node
9093
          try:
9094
            _CreateBlockDev(self, node, instance, new_disk,
9095
                            f_create, info, f_create)
9096
          except errors.OpExecError, err:
9097
            self.LogWarning("Failed to create volume %s (%s) on"
9098
                            " node %s: %s",
9099
                            new_disk.iv_name, new_disk, node, err)
9100
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9101
                       (new_disk.size, new_disk.mode)))
9102
      else:
9103
        # change a given disk
9104
        instance.disks[disk_op].mode = disk_dict['mode']
9105
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9106

    
9107
    if self.op.disk_template:
9108
      r_shut = _ShutdownInstanceDisks(self, instance)
9109
      if not r_shut:
9110
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9111
                                 " proceed with disk template conversion")
9112
      mode = (instance.disk_template, self.op.disk_template)
9113
      try:
9114
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9115
      except:
9116
        self.cfg.ReleaseDRBDMinors(instance.name)
9117
        raise
9118
      result.append(("disk_template", self.op.disk_template))
9119

    
9120
    # NIC changes
9121
    for nic_op, nic_dict in self.op.nics:
9122
      if nic_op == constants.DDM_REMOVE:
9123
        # remove the last nic
9124
        del instance.nics[-1]
9125
        result.append(("nic.%d" % len(instance.nics), "remove"))
9126
      elif nic_op == constants.DDM_ADD:
9127
        # mac and bridge should be set, by now
9128
        mac = nic_dict['mac']
9129
        ip = nic_dict.get('ip', None)
9130
        nicparams = self.nic_pinst[constants.DDM_ADD]
9131
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9132
        instance.nics.append(new_nic)
9133
        result.append(("nic.%d" % (len(instance.nics) - 1),
9134
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9135
                       (new_nic.mac, new_nic.ip,
9136
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9137
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9138
                       )))
9139
      else:
9140
        for key in 'mac', 'ip':
9141
          if key in nic_dict:
9142
            setattr(instance.nics[nic_op], key, nic_dict[key])
9143
        if nic_op in self.nic_pinst:
9144
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9145
        for key, val in nic_dict.iteritems():
9146
          result.append(("nic.%s/%d" % (key, nic_op), val))
9147

    
9148
    # hvparams changes
9149
    if self.op.hvparams:
9150
      instance.hvparams = self.hv_inst
9151
      for key, val in self.op.hvparams.iteritems():
9152
        result.append(("hv/%s" % key, val))
9153

    
9154
    # beparams changes
9155
    if self.op.beparams:
9156
      instance.beparams = self.be_inst
9157
      for key, val in self.op.beparams.iteritems():
9158
        result.append(("be/%s" % key, val))
9159

    
9160
    # OS change
9161
    if self.op.os_name:
9162
      instance.os = self.op.os_name
9163

    
9164
    # osparams changes
9165
    if self.op.osparams:
9166
      instance.osparams = self.os_inst
9167
      for key, val in self.op.osparams.iteritems():
9168
        result.append(("os/%s" % key, val))
9169

    
9170
    self.cfg.Update(instance, feedback_fn)
9171

    
9172
    return result
9173

    
9174
  _DISK_CONVERSIONS = {
9175
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9176
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9177
    }
9178

    
9179

    
9180
class LUQueryExports(NoHooksLU):
9181
  """Query the exports list
9182

9183
  """
9184
  _OP_PARAMS = [
9185
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9186
    ("use_locking", False, ht.TBool),
9187
    ]
9188
  REQ_BGL = False
9189

    
9190
  def ExpandNames(self):
9191
    self.needed_locks = {}
9192
    self.share_locks[locking.LEVEL_NODE] = 1
9193
    if not self.op.nodes:
9194
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9195
    else:
9196
      self.needed_locks[locking.LEVEL_NODE] = \
9197
        _GetWantedNodes(self, self.op.nodes)
9198

    
9199
  def Exec(self, feedback_fn):
9200
    """Compute the list of all the exported system images.
9201

9202
    @rtype: dict
9203
    @return: a dictionary with the structure node->(export-list)
9204
        where export-list is a list of the instances exported on
9205
        that node.
9206

9207
    """
9208
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9209
    rpcresult = self.rpc.call_export_list(self.nodes)
9210
    result = {}
9211
    for node in rpcresult:
9212
      if rpcresult[node].fail_msg:
9213
        result[node] = False
9214
      else:
9215
        result[node] = rpcresult[node].payload
9216

    
9217
    return result
9218

    
9219

    
9220
class LUPrepareExport(NoHooksLU):
9221
  """Prepares an instance for an export and returns useful information.
9222

9223
  """
9224
  _OP_PARAMS = [
9225
    _PInstanceName,
9226
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9227
    ]
9228
  REQ_BGL = False
9229

    
9230
  def ExpandNames(self):
9231
    self._ExpandAndLockInstance()
9232

    
9233
  def CheckPrereq(self):
9234
    """Check prerequisites.
9235

9236
    """
9237
    instance_name = self.op.instance_name
9238

    
9239
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9240
    assert self.instance is not None, \
9241
          "Cannot retrieve locked instance %s" % self.op.instance_name
9242
    _CheckNodeOnline(self, self.instance.primary_node)
9243

    
9244
    self._cds = _GetClusterDomainSecret()
9245

    
9246
  def Exec(self, feedback_fn):
9247
    """Prepares an instance for an export.
9248

9249
    """
9250
    instance = self.instance
9251

    
9252
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9253
      salt = utils.GenerateSecret(8)
9254

    
9255
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9256
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9257
                                              constants.RIE_CERT_VALIDITY)
9258
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9259

    
9260
      (name, cert_pem) = result.payload
9261

    
9262
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9263
                                             cert_pem)
9264

    
9265
      return {
9266
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9267
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9268
                          salt),
9269
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9270
        }
9271

    
9272
    return None
9273

    
9274

    
9275
class LUExportInstance(LogicalUnit):
9276
  """Export an instance to an image in the cluster.
9277

9278
  """
9279
  HPATH = "instance-export"
9280
  HTYPE = constants.HTYPE_INSTANCE
9281
  _OP_PARAMS = [
9282
    _PInstanceName,
9283
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9284
    ("shutdown", True, ht.TBool),
9285
    _PShutdownTimeout,
9286
    ("remove_instance", False, ht.TBool),
9287
    ("ignore_remove_failures", False, ht.TBool),
9288
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9289
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9290
    ("destination_x509_ca", None, ht.TMaybeString),
9291
    ]
9292
  REQ_BGL = False
9293

    
9294
  def CheckArguments(self):
9295
    """Check the arguments.
9296

9297
    """
9298
    self.x509_key_name = self.op.x509_key_name
9299
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9300

    
9301
    if self.op.remove_instance and not self.op.shutdown:
9302
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9303
                                 " down before")
9304

    
9305
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9306
      if not self.x509_key_name:
9307
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9308
                                   errors.ECODE_INVAL)
9309

    
9310
      if not self.dest_x509_ca_pem:
9311
        raise errors.OpPrereqError("Missing destination X509 CA",
9312
                                   errors.ECODE_INVAL)
9313

    
9314
  def ExpandNames(self):
9315
    self._ExpandAndLockInstance()
9316

    
9317
    # Lock all nodes for local exports
9318
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9319
      # FIXME: lock only instance primary and destination node
9320
      #
9321
      # Sad but true, for now we have do lock all nodes, as we don't know where
9322
      # the previous export might be, and in this LU we search for it and
9323
      # remove it from its current node. In the future we could fix this by:
9324
      #  - making a tasklet to search (share-lock all), then create the
9325
      #    new one, then one to remove, after
9326
      #  - removing the removal operation altogether
9327
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9328

    
9329
  def DeclareLocks(self, level):
9330
    """Last minute lock declaration."""
9331
    # All nodes are locked anyway, so nothing to do here.
9332

    
9333
  def BuildHooksEnv(self):
9334
    """Build hooks env.
9335

9336
    This will run on the master, primary node and target node.
9337

9338
    """
9339
    env = {
9340
      "EXPORT_MODE": self.op.mode,
9341
      "EXPORT_NODE": self.op.target_node,
9342
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9343
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9344
      # TODO: Generic function for boolean env variables
9345
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9346
      }
9347

    
9348
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9349

    
9350
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9351

    
9352
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9353
      nl.append(self.op.target_node)
9354

    
9355
    return env, nl, nl
9356

    
9357
  def CheckPrereq(self):
9358
    """Check prerequisites.
9359

9360
    This checks that the instance and node names are valid.
9361

9362
    """
9363
    instance_name = self.op.instance_name
9364

    
9365
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9366
    assert self.instance is not None, \
9367
          "Cannot retrieve locked instance %s" % self.op.instance_name
9368
    _CheckNodeOnline(self, self.instance.primary_node)
9369

    
9370
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9371
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9372
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9373
      assert self.dst_node is not None
9374

    
9375
      _CheckNodeOnline(self, self.dst_node.name)
9376
      _CheckNodeNotDrained(self, self.dst_node.name)
9377

    
9378
      self._cds = None
9379
      self.dest_disk_info = None
9380
      self.dest_x509_ca = None
9381

    
9382
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9383
      self.dst_node = None
9384

    
9385
      if len(self.op.target_node) != len(self.instance.disks):
9386
        raise errors.OpPrereqError(("Received destination information for %s"
9387
                                    " disks, but instance %s has %s disks") %
9388
                                   (len(self.op.target_node), instance_name,
9389
                                    len(self.instance.disks)),
9390
                                   errors.ECODE_INVAL)
9391

    
9392
      cds = _GetClusterDomainSecret()
9393

    
9394
      # Check X509 key name
9395
      try:
9396
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9397
      except (TypeError, ValueError), err:
9398
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9399

    
9400
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9401
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9402
                                   errors.ECODE_INVAL)
9403

    
9404
      # Load and verify CA
9405
      try:
9406
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9407
      except OpenSSL.crypto.Error, err:
9408
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9409
                                   (err, ), errors.ECODE_INVAL)
9410

    
9411
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9412
      if errcode is not None:
9413
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9414
                                   (msg, ), errors.ECODE_INVAL)
9415

    
9416
      self.dest_x509_ca = cert
9417

    
9418
      # Verify target information
9419
      disk_info = []
9420
      for idx, disk_data in enumerate(self.op.target_node):
9421
        try:
9422
          (host, port, magic) = \
9423
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9424
        except errors.GenericError, err:
9425
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9426
                                     (idx, err), errors.ECODE_INVAL)
9427

    
9428
        disk_info.append((host, port, magic))
9429

    
9430
      assert len(disk_info) == len(self.op.target_node)
9431
      self.dest_disk_info = disk_info
9432

    
9433
    else:
9434
      raise errors.ProgrammerError("Unhandled export mode %r" %
9435
                                   self.op.mode)
9436

    
9437
    # instance disk type verification
9438
    # TODO: Implement export support for file-based disks
9439
    for disk in self.instance.disks:
9440
      if disk.dev_type == constants.LD_FILE:
9441
        raise errors.OpPrereqError("Export not supported for instances with"
9442
                                   " file-based disks", errors.ECODE_INVAL)
9443

    
9444
  def _CleanupExports(self, feedback_fn):
9445
    """Removes exports of current instance from all other nodes.
9446

9447
    If an instance in a cluster with nodes A..D was exported to node C, its
9448
    exports will be removed from the nodes A, B and D.
9449

9450
    """
9451
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9452

    
9453
    nodelist = self.cfg.GetNodeList()
9454
    nodelist.remove(self.dst_node.name)
9455

    
9456
    # on one-node clusters nodelist will be empty after the removal
9457
    # if we proceed the backup would be removed because OpQueryExports
9458
    # substitutes an empty list with the full cluster node list.
9459
    iname = self.instance.name
9460
    if nodelist:
9461
      feedback_fn("Removing old exports for instance %s" % iname)
9462
      exportlist = self.rpc.call_export_list(nodelist)
9463
      for node in exportlist:
9464
        if exportlist[node].fail_msg:
9465
          continue
9466
        if iname in exportlist[node].payload:
9467
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9468
          if msg:
9469
            self.LogWarning("Could not remove older export for instance %s"
9470
                            " on node %s: %s", iname, node, msg)
9471

    
9472
  def Exec(self, feedback_fn):
9473
    """Export an instance to an image in the cluster.
9474

9475
    """
9476
    assert self.op.mode in constants.EXPORT_MODES
9477

    
9478
    instance = self.instance
9479
    src_node = instance.primary_node
9480

    
9481
    if self.op.shutdown:
9482
      # shutdown the instance, but not the disks
9483
      feedback_fn("Shutting down instance %s" % instance.name)
9484
      result = self.rpc.call_instance_shutdown(src_node, instance,
9485
                                               self.op.shutdown_timeout)
9486
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9487
      result.Raise("Could not shutdown instance %s on"
9488
                   " node %s" % (instance.name, src_node))
9489

    
9490
    # set the disks ID correctly since call_instance_start needs the
9491
    # correct drbd minor to create the symlinks
9492
    for disk in instance.disks:
9493
      self.cfg.SetDiskID(disk, src_node)
9494

    
9495
    activate_disks = (not instance.admin_up)
9496

    
9497
    if activate_disks:
9498
      # Activate the instance disks if we'exporting a stopped instance
9499
      feedback_fn("Activating disks for %s" % instance.name)
9500
      _StartInstanceDisks(self, instance, None)
9501

    
9502
    try:
9503
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9504
                                                     instance)
9505

    
9506
      helper.CreateSnapshots()
9507
      try:
9508
        if (self.op.shutdown and instance.admin_up and
9509
            not self.op.remove_instance):
9510
          assert not activate_disks
9511
          feedback_fn("Starting instance %s" % instance.name)
9512
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9513
          msg = result.fail_msg
9514
          if msg:
9515
            feedback_fn("Failed to start instance: %s" % msg)
9516
            _ShutdownInstanceDisks(self, instance)
9517
            raise errors.OpExecError("Could not start instance: %s" % msg)
9518

    
9519
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9520
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9521
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9522
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9523
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9524

    
9525
          (key_name, _, _) = self.x509_key_name
9526

    
9527
          dest_ca_pem = \
9528
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9529
                                            self.dest_x509_ca)
9530

    
9531
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9532
                                                     key_name, dest_ca_pem,
9533
                                                     timeouts)
9534
      finally:
9535
        helper.Cleanup()
9536

    
9537
      # Check for backwards compatibility
9538
      assert len(dresults) == len(instance.disks)
9539
      assert compat.all(isinstance(i, bool) for i in dresults), \
9540
             "Not all results are boolean: %r" % dresults
9541

    
9542
    finally:
9543
      if activate_disks:
9544
        feedback_fn("Deactivating disks for %s" % instance.name)
9545
        _ShutdownInstanceDisks(self, instance)
9546

    
9547
    if not (compat.all(dresults) and fin_resu):
9548
      failures = []
9549
      if not fin_resu:
9550
        failures.append("export finalization")
9551
      if not compat.all(dresults):
9552
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9553
                               if not dsk)
9554
        failures.append("disk export: disk(s) %s" % fdsk)
9555

    
9556
      raise errors.OpExecError("Export failed, errors in %s" %
9557
                               utils.CommaJoin(failures))
9558

    
9559
    # At this point, the export was successful, we can cleanup/finish
9560

    
9561
    # Remove instance if requested
9562
    if self.op.remove_instance:
9563
      feedback_fn("Removing instance %s" % instance.name)
9564
      _RemoveInstance(self, feedback_fn, instance,
9565
                      self.op.ignore_remove_failures)
9566

    
9567
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9568
      self._CleanupExports(feedback_fn)
9569

    
9570
    return fin_resu, dresults
9571

    
9572

    
9573
class LURemoveExport(NoHooksLU):
9574
  """Remove exports related to the named instance.
9575

9576
  """
9577
  _OP_PARAMS = [
9578
    _PInstanceName,
9579
    ]
9580
  REQ_BGL = False
9581

    
9582
  def ExpandNames(self):
9583
    self.needed_locks = {}
9584
    # We need all nodes to be locked in order for RemoveExport to work, but we
9585
    # don't need to lock the instance itself, as nothing will happen to it (and
9586
    # we can remove exports also for a removed instance)
9587
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9588

    
9589
  def Exec(self, feedback_fn):
9590
    """Remove any export.
9591

9592
    """
9593
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9594
    # If the instance was not found we'll try with the name that was passed in.
9595
    # This will only work if it was an FQDN, though.
9596
    fqdn_warn = False
9597
    if not instance_name:
9598
      fqdn_warn = True
9599
      instance_name = self.op.instance_name
9600

    
9601
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9602
    exportlist = self.rpc.call_export_list(locked_nodes)
9603
    found = False
9604
    for node in exportlist:
9605
      msg = exportlist[node].fail_msg
9606
      if msg:
9607
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9608
        continue
9609
      if instance_name in exportlist[node].payload:
9610
        found = True
9611
        result = self.rpc.call_export_remove(node, instance_name)
9612
        msg = result.fail_msg
9613
        if msg:
9614
          logging.error("Could not remove export for instance %s"
9615
                        " on node %s: %s", instance_name, node, msg)
9616

    
9617
    if fqdn_warn and not found:
9618
      feedback_fn("Export not found. If trying to remove an export belonging"
9619
                  " to a deleted instance please use its Fully Qualified"
9620
                  " Domain Name.")
9621

    
9622

    
9623
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9624
  """Generic tags LU.
9625

9626
  This is an abstract class which is the parent of all the other tags LUs.
9627

9628
  """
9629

    
9630
  def ExpandNames(self):
9631
    self.needed_locks = {}
9632
    if self.op.kind == constants.TAG_NODE:
9633
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9634
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9635
    elif self.op.kind == constants.TAG_INSTANCE:
9636
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9637
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9638

    
9639
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
9640
    # not possible to acquire the BGL based on opcode parameters)
9641

    
9642
  def CheckPrereq(self):
9643
    """Check prerequisites.
9644

9645
    """
9646
    if self.op.kind == constants.TAG_CLUSTER:
9647
      self.target = self.cfg.GetClusterInfo()
9648
    elif self.op.kind == constants.TAG_NODE:
9649
      self.target = self.cfg.GetNodeInfo(self.op.name)
9650
    elif self.op.kind == constants.TAG_INSTANCE:
9651
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9652
    else:
9653
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9654
                                 str(self.op.kind), errors.ECODE_INVAL)
9655

    
9656

    
9657
class LUGetTags(TagsLU):
9658
  """Returns the tags of a given object.
9659

9660
  """
9661
  _OP_PARAMS = [
9662
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9663
    # Name is only meaningful for nodes and instances
9664
    ("name", ht.NoDefault, ht.TMaybeString),
9665
    ]
9666
  REQ_BGL = False
9667

    
9668
  def ExpandNames(self):
9669
    TagsLU.ExpandNames(self)
9670

    
9671
    # Share locks as this is only a read operation
9672
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9673

    
9674
  def Exec(self, feedback_fn):
9675
    """Returns the tag list.
9676

9677
    """
9678
    return list(self.target.GetTags())
9679

    
9680

    
9681
class LUSearchTags(NoHooksLU):
9682
  """Searches the tags for a given pattern.
9683

9684
  """
9685
  _OP_PARAMS = [
9686
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
9687
    ]
9688
  REQ_BGL = False
9689

    
9690
  def ExpandNames(self):
9691
    self.needed_locks = {}
9692

    
9693
  def CheckPrereq(self):
9694
    """Check prerequisites.
9695

9696
    This checks the pattern passed for validity by compiling it.
9697

9698
    """
9699
    try:
9700
      self.re = re.compile(self.op.pattern)
9701
    except re.error, err:
9702
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9703
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9704

    
9705
  def Exec(self, feedback_fn):
9706
    """Returns the tag list.
9707

9708
    """
9709
    cfg = self.cfg
9710
    tgts = [("/cluster", cfg.GetClusterInfo())]
9711
    ilist = cfg.GetAllInstancesInfo().values()
9712
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9713
    nlist = cfg.GetAllNodesInfo().values()
9714
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9715
    results = []
9716
    for path, target in tgts:
9717
      for tag in target.GetTags():
9718
        if self.re.search(tag):
9719
          results.append((path, tag))
9720
    return results
9721

    
9722

    
9723
class LUAddTags(TagsLU):
9724
  """Sets a tag on a given object.
9725

9726
  """
9727
  _OP_PARAMS = [
9728
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9729
    # Name is only meaningful for nodes and instances
9730
    ("name", ht.NoDefault, ht.TMaybeString),
9731
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
9732
    ]
9733
  REQ_BGL = False
9734

    
9735
  def CheckPrereq(self):
9736
    """Check prerequisites.
9737

9738
    This checks the type and length of the tag name and value.
9739

9740
    """
9741
    TagsLU.CheckPrereq(self)
9742
    for tag in self.op.tags:
9743
      objects.TaggableObject.ValidateTag(tag)
9744

    
9745
  def Exec(self, feedback_fn):
9746
    """Sets the tag.
9747

9748
    """
9749
    try:
9750
      for tag in self.op.tags:
9751
        self.target.AddTag(tag)
9752
    except errors.TagError, err:
9753
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9754
    self.cfg.Update(self.target, feedback_fn)
9755

    
9756

    
9757
class LUDelTags(TagsLU):
9758
  """Delete a list of tags from a given object.
9759

9760
  """
9761
  _OP_PARAMS = [
9762
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
9763
    # Name is only meaningful for nodes and instances
9764
    ("name", ht.NoDefault, ht.TMaybeString),
9765
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
9766
    ]
9767
  REQ_BGL = False
9768

    
9769
  def CheckPrereq(self):
9770
    """Check prerequisites.
9771

9772
    This checks that we have the given tag.
9773

9774
    """
9775
    TagsLU.CheckPrereq(self)
9776
    for tag in self.op.tags:
9777
      objects.TaggableObject.ValidateTag(tag)
9778
    del_tags = frozenset(self.op.tags)
9779
    cur_tags = self.target.GetTags()
9780

    
9781
    diff_tags = del_tags - cur_tags
9782
    if diff_tags:
9783
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
9784
      raise errors.OpPrereqError("Tag(s) %s not found" %
9785
                                 (utils.CommaJoin(diff_names), ),
9786
                                 errors.ECODE_NOENT)
9787

    
9788
  def Exec(self, feedback_fn):
9789
    """Remove the tag from the object.
9790

9791
    """
9792
    for tag in self.op.tags:
9793
      self.target.RemoveTag(tag)
9794
    self.cfg.Update(self.target, feedback_fn)
9795

    
9796

    
9797
class LUTestDelay(NoHooksLU):
9798
  """Sleep for a specified amount of time.
9799

9800
  This LU sleeps on the master and/or nodes for a specified amount of
9801
  time.
9802

9803
  """
9804
  _OP_PARAMS = [
9805
    ("duration", ht.NoDefault, ht.TFloat),
9806
    ("on_master", True, ht.TBool),
9807
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9808
    ("repeat", 0, ht.TPositiveInt)
9809
    ]
9810
  REQ_BGL = False
9811

    
9812
  def ExpandNames(self):
9813
    """Expand names and set required locks.
9814

9815
    This expands the node list, if any.
9816

9817
    """
9818
    self.needed_locks = {}
9819
    if self.op.on_nodes:
9820
      # _GetWantedNodes can be used here, but is not always appropriate to use
9821
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9822
      # more information.
9823
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9824
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9825

    
9826
  def _TestDelay(self):
9827
    """Do the actual sleep.
9828

9829
    """
9830
    if self.op.on_master:
9831
      if not utils.TestDelay(self.op.duration):
9832
        raise errors.OpExecError("Error during master delay test")
9833
    if self.op.on_nodes:
9834
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9835
      for node, node_result in result.items():
9836
        node_result.Raise("Failure during rpc call to node %s" % node)
9837

    
9838
  def Exec(self, feedback_fn):
9839
    """Execute the test delay opcode, with the wanted repetitions.
9840

9841
    """
9842
    if self.op.repeat == 0:
9843
      self._TestDelay()
9844
    else:
9845
      top_value = self.op.repeat - 1
9846
      for i in range(self.op.repeat):
9847
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9848
        self._TestDelay()
9849

    
9850

    
9851
class LUTestJobqueue(NoHooksLU):
9852
  """Utility LU to test some aspects of the job queue.
9853

9854
  """
9855
  _OP_PARAMS = [
9856
    ("notify_waitlock", False, ht.TBool),
9857
    ("notify_exec", False, ht.TBool),
9858
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
9859
    ("fail", False, ht.TBool),
9860
    ]
9861
  REQ_BGL = False
9862

    
9863
  # Must be lower than default timeout for WaitForJobChange to see whether it
9864
  # notices changed jobs
9865
  _CLIENT_CONNECT_TIMEOUT = 20.0
9866
  _CLIENT_CONFIRM_TIMEOUT = 60.0
9867

    
9868
  @classmethod
9869
  def _NotifyUsingSocket(cls, cb, errcls):
9870
    """Opens a Unix socket and waits for another program to connect.
9871

9872
    @type cb: callable
9873
    @param cb: Callback to send socket name to client
9874
    @type errcls: class
9875
    @param errcls: Exception class to use for errors
9876

9877
    """
9878
    # Using a temporary directory as there's no easy way to create temporary
9879
    # sockets without writing a custom loop around tempfile.mktemp and
9880
    # socket.bind
9881
    tmpdir = tempfile.mkdtemp()
9882
    try:
9883
      tmpsock = utils.PathJoin(tmpdir, "sock")
9884

    
9885
      logging.debug("Creating temporary socket at %s", tmpsock)
9886
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9887
      try:
9888
        sock.bind(tmpsock)
9889
        sock.listen(1)
9890

    
9891
        # Send details to client
9892
        cb(tmpsock)
9893

    
9894
        # Wait for client to connect before continuing
9895
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
9896
        try:
9897
          (conn, _) = sock.accept()
9898
        except socket.error, err:
9899
          raise errcls("Client didn't connect in time (%s)" % err)
9900
      finally:
9901
        sock.close()
9902
    finally:
9903
      # Remove as soon as client is connected
9904
      shutil.rmtree(tmpdir)
9905

    
9906
    # Wait for client to close
9907
    try:
9908
      try:
9909
        # pylint: disable-msg=E1101
9910
        # Instance of '_socketobject' has no ... member
9911
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
9912
        conn.recv(1)
9913
      except socket.error, err:
9914
        raise errcls("Client failed to confirm notification (%s)" % err)
9915
    finally:
9916
      conn.close()
9917

    
9918
  def _SendNotification(self, test, arg, sockname):
9919
    """Sends a notification to the client.
9920

9921
    @type test: string
9922
    @param test: Test name
9923
    @param arg: Test argument (depends on test)
9924
    @type sockname: string
9925
    @param sockname: Socket path
9926

9927
    """
9928
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
9929

    
9930
  def _Notify(self, prereq, test, arg):
9931
    """Notifies the client of a test.
9932

9933
    @type prereq: bool
9934
    @param prereq: Whether this is a prereq-phase test
9935
    @type test: string
9936
    @param test: Test name
9937
    @param arg: Test argument (depends on test)
9938

9939
    """
9940
    if prereq:
9941
      errcls = errors.OpPrereqError
9942
    else:
9943
      errcls = errors.OpExecError
9944

    
9945
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
9946
                                                  test, arg),
9947
                                   errcls)
9948

    
9949
  def CheckArguments(self):
9950
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
9951
    self.expandnames_calls = 0
9952

    
9953
  def ExpandNames(self):
9954
    checkargs_calls = getattr(self, "checkargs_calls", 0)
9955
    if checkargs_calls < 1:
9956
      raise errors.ProgrammerError("CheckArguments was not called")
9957

    
9958
    self.expandnames_calls += 1
9959

    
9960
    if self.op.notify_waitlock:
9961
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
9962

    
9963
    self.LogInfo("Expanding names")
9964

    
9965
    # Get lock on master node (just to get a lock, not for a particular reason)
9966
    self.needed_locks = {
9967
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
9968
      }
9969

    
9970
  def Exec(self, feedback_fn):
9971
    if self.expandnames_calls < 1:
9972
      raise errors.ProgrammerError("ExpandNames was not called")
9973

    
9974
    if self.op.notify_exec:
9975
      self._Notify(False, constants.JQT_EXEC, None)
9976

    
9977
    self.LogInfo("Executing")
9978

    
9979
    if self.op.log_messages:
9980
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
9981
      for idx, msg in enumerate(self.op.log_messages):
9982
        self.LogInfo("Sending log message %s", idx + 1)
9983
        feedback_fn(constants.JQT_MSGPREFIX + msg)
9984
        # Report how many test messages have been sent
9985
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
9986

    
9987
    if self.op.fail:
9988
      raise errors.OpExecError("Opcode failure was requested")
9989

    
9990
    return True
9991

    
9992

    
9993
class IAllocator(object):
9994
  """IAllocator framework.
9995

9996
  An IAllocator instance has three sets of attributes:
9997
    - cfg that is needed to query the cluster
9998
    - input data (all members of the _KEYS class attribute are required)
9999
    - four buffer attributes (in|out_data|text), that represent the
10000
      input (to the external script) in text and data structure format,
10001
      and the output from it, again in two formats
10002
    - the result variables from the script (success, info, nodes) for
10003
      easy usage
10004

10005
  """
10006
  # pylint: disable-msg=R0902
10007
  # lots of instance attributes
10008
  _ALLO_KEYS = [
10009
    "name", "mem_size", "disks", "disk_template",
10010
    "os", "tags", "nics", "vcpus", "hypervisor",
10011
    ]
10012
  _RELO_KEYS = [
10013
    "name", "relocate_from",
10014
    ]
10015
  _EVAC_KEYS = [
10016
    "evac_nodes",
10017
    ]
10018

    
10019
  def __init__(self, cfg, rpc, mode, **kwargs):
10020
    self.cfg = cfg
10021
    self.rpc = rpc
10022
    # init buffer variables
10023
    self.in_text = self.out_text = self.in_data = self.out_data = None
10024
    # init all input fields so that pylint is happy
10025
    self.mode = mode
10026
    self.mem_size = self.disks = self.disk_template = None
10027
    self.os = self.tags = self.nics = self.vcpus = None
10028
    self.hypervisor = None
10029
    self.relocate_from = None
10030
    self.name = None
10031
    self.evac_nodes = None
10032
    # computed fields
10033
    self.required_nodes = None
10034
    # init result fields
10035
    self.success = self.info = self.result = None
10036
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10037
      keyset = self._ALLO_KEYS
10038
      fn = self._AddNewInstance
10039
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10040
      keyset = self._RELO_KEYS
10041
      fn = self._AddRelocateInstance
10042
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10043
      keyset = self._EVAC_KEYS
10044
      fn = self._AddEvacuateNodes
10045
    else:
10046
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10047
                                   " IAllocator" % self.mode)
10048
    for key in kwargs:
10049
      if key not in keyset:
10050
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10051
                                     " IAllocator" % key)
10052
      setattr(self, key, kwargs[key])
10053

    
10054
    for key in keyset:
10055
      if key not in kwargs:
10056
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10057
                                     " IAllocator" % key)
10058
    self._BuildInputData(fn)
10059

    
10060
  def _ComputeClusterData(self):
10061
    """Compute the generic allocator input data.
10062

10063
    This is the data that is independent of the actual operation.
10064

10065
    """
10066
    cfg = self.cfg
10067
    cluster_info = cfg.GetClusterInfo()
10068
    # cluster data
10069
    data = {
10070
      "version": constants.IALLOCATOR_VERSION,
10071
      "cluster_name": cfg.GetClusterName(),
10072
      "cluster_tags": list(cluster_info.GetTags()),
10073
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10074
      # we don't have job IDs
10075
      }
10076
    iinfo = cfg.GetAllInstancesInfo().values()
10077
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10078

    
10079
    # node data
10080
    node_results = {}
10081
    node_list = cfg.GetNodeList()
10082

    
10083
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10084
      hypervisor_name = self.hypervisor
10085
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10086
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10087
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10088
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10089

    
10090
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10091
                                        hypervisor_name)
10092
    node_iinfo = \
10093
      self.rpc.call_all_instances_info(node_list,
10094
                                       cluster_info.enabled_hypervisors)
10095
    for nname, nresult in node_data.items():
10096
      # first fill in static (config-based) values
10097
      ninfo = cfg.GetNodeInfo(nname)
10098
      pnr = {
10099
        "tags": list(ninfo.GetTags()),
10100
        "primary_ip": ninfo.primary_ip,
10101
        "secondary_ip": ninfo.secondary_ip,
10102
        "offline": ninfo.offline,
10103
        "drained": ninfo.drained,
10104
        "master_candidate": ninfo.master_candidate,
10105
        }
10106

    
10107
      if not (ninfo.offline or ninfo.drained):
10108
        nresult.Raise("Can't get data for node %s" % nname)
10109
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10110
                                nname)
10111
        remote_info = nresult.payload
10112

    
10113
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10114
                     'vg_size', 'vg_free', 'cpu_total']:
10115
          if attr not in remote_info:
10116
            raise errors.OpExecError("Node '%s' didn't return attribute"
10117
                                     " '%s'" % (nname, attr))
10118
          if not isinstance(remote_info[attr], int):
10119
            raise errors.OpExecError("Node '%s' returned invalid value"
10120
                                     " for '%s': %s" %
10121
                                     (nname, attr, remote_info[attr]))
10122
        # compute memory used by primary instances
10123
        i_p_mem = i_p_up_mem = 0
10124
        for iinfo, beinfo in i_list:
10125
          if iinfo.primary_node == nname:
10126
            i_p_mem += beinfo[constants.BE_MEMORY]
10127
            if iinfo.name not in node_iinfo[nname].payload:
10128
              i_used_mem = 0
10129
            else:
10130
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10131
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10132
            remote_info['memory_free'] -= max(0, i_mem_diff)
10133

    
10134
            if iinfo.admin_up:
10135
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10136

    
10137
        # compute memory used by instances
10138
        pnr_dyn = {
10139
          "total_memory": remote_info['memory_total'],
10140
          "reserved_memory": remote_info['memory_dom0'],
10141
          "free_memory": remote_info['memory_free'],
10142
          "total_disk": remote_info['vg_size'],
10143
          "free_disk": remote_info['vg_free'],
10144
          "total_cpus": remote_info['cpu_total'],
10145
          "i_pri_memory": i_p_mem,
10146
          "i_pri_up_memory": i_p_up_mem,
10147
          }
10148
        pnr.update(pnr_dyn)
10149

    
10150
      node_results[nname] = pnr
10151
    data["nodes"] = node_results
10152

    
10153
    # instance data
10154
    instance_data = {}
10155
    for iinfo, beinfo in i_list:
10156
      nic_data = []
10157
      for nic in iinfo.nics:
10158
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10159
        nic_dict = {"mac": nic.mac,
10160
                    "ip": nic.ip,
10161
                    "mode": filled_params[constants.NIC_MODE],
10162
                    "link": filled_params[constants.NIC_LINK],
10163
                   }
10164
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10165
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10166
        nic_data.append(nic_dict)
10167
      pir = {
10168
        "tags": list(iinfo.GetTags()),
10169
        "admin_up": iinfo.admin_up,
10170
        "vcpus": beinfo[constants.BE_VCPUS],
10171
        "memory": beinfo[constants.BE_MEMORY],
10172
        "os": iinfo.os,
10173
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10174
        "nics": nic_data,
10175
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10176
        "disk_template": iinfo.disk_template,
10177
        "hypervisor": iinfo.hypervisor,
10178
        }
10179
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10180
                                                 pir["disks"])
10181
      instance_data[iinfo.name] = pir
10182

    
10183
    data["instances"] = instance_data
10184

    
10185
    self.in_data = data
10186

    
10187
  def _AddNewInstance(self):
10188
    """Add new instance data to allocator structure.
10189

10190
    This in combination with _AllocatorGetClusterData will create the
10191
    correct structure needed as input for the allocator.
10192

10193
    The checks for the completeness of the opcode must have already been
10194
    done.
10195

10196
    """
10197
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10198

    
10199
    if self.disk_template in constants.DTS_NET_MIRROR:
10200
      self.required_nodes = 2
10201
    else:
10202
      self.required_nodes = 1
10203
    request = {
10204
      "name": self.name,
10205
      "disk_template": self.disk_template,
10206
      "tags": self.tags,
10207
      "os": self.os,
10208
      "vcpus": self.vcpus,
10209
      "memory": self.mem_size,
10210
      "disks": self.disks,
10211
      "disk_space_total": disk_space,
10212
      "nics": self.nics,
10213
      "required_nodes": self.required_nodes,
10214
      }
10215
    return request
10216

    
10217
  def _AddRelocateInstance(self):
10218
    """Add relocate instance data to allocator structure.
10219

10220
    This in combination with _IAllocatorGetClusterData will create the
10221
    correct structure needed as input for the allocator.
10222

10223
    The checks for the completeness of the opcode must have already been
10224
    done.
10225

10226
    """
10227
    instance = self.cfg.GetInstanceInfo(self.name)
10228
    if instance is None:
10229
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10230
                                   " IAllocator" % self.name)
10231

    
10232
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10233
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10234
                                 errors.ECODE_INVAL)
10235

    
10236
    if len(instance.secondary_nodes) != 1:
10237
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10238
                                 errors.ECODE_STATE)
10239

    
10240
    self.required_nodes = 1
10241
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10242
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10243

    
10244
    request = {
10245
      "name": self.name,
10246
      "disk_space_total": disk_space,
10247
      "required_nodes": self.required_nodes,
10248
      "relocate_from": self.relocate_from,
10249
      }
10250
    return request
10251

    
10252
  def _AddEvacuateNodes(self):
10253
    """Add evacuate nodes data to allocator structure.
10254

10255
    """
10256
    request = {
10257
      "evac_nodes": self.evac_nodes
10258
      }
10259
    return request
10260

    
10261
  def _BuildInputData(self, fn):
10262
    """Build input data structures.
10263

10264
    """
10265
    self._ComputeClusterData()
10266

    
10267
    request = fn()
10268
    request["type"] = self.mode
10269
    self.in_data["request"] = request
10270

    
10271
    self.in_text = serializer.Dump(self.in_data)
10272

    
10273
  def Run(self, name, validate=True, call_fn=None):
10274
    """Run an instance allocator and return the results.
10275

10276
    """
10277
    if call_fn is None:
10278
      call_fn = self.rpc.call_iallocator_runner
10279

    
10280
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10281
    result.Raise("Failure while running the iallocator script")
10282

    
10283
    self.out_text = result.payload
10284
    if validate:
10285
      self._ValidateResult()
10286

    
10287
  def _ValidateResult(self):
10288
    """Process the allocator results.
10289

10290
    This will process and if successful save the result in
10291
    self.out_data and the other parameters.
10292

10293
    """
10294
    try:
10295
      rdict = serializer.Load(self.out_text)
10296
    except Exception, err:
10297
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10298

    
10299
    if not isinstance(rdict, dict):
10300
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10301

    
10302
    # TODO: remove backwards compatiblity in later versions
10303
    if "nodes" in rdict and "result" not in rdict:
10304
      rdict["result"] = rdict["nodes"]
10305
      del rdict["nodes"]
10306

    
10307
    for key in "success", "info", "result":
10308
      if key not in rdict:
10309
        raise errors.OpExecError("Can't parse iallocator results:"
10310
                                 " missing key '%s'" % key)
10311
      setattr(self, key, rdict[key])
10312

    
10313
    if not isinstance(rdict["result"], list):
10314
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10315
                               " is not a list")
10316
    self.out_data = rdict
10317

    
10318

    
10319
class LUTestAllocator(NoHooksLU):
10320
  """Run allocator tests.
10321

10322
  This LU runs the allocator tests
10323

10324
  """
10325
  _OP_PARAMS = [
10326
    ("direction", ht.NoDefault,
10327
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10328
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
10329
    ("name", ht.NoDefault, ht.TNonEmptyString),
10330
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
10331
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
10332
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
10333
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
10334
    ("hypervisor", None, ht.TMaybeString),
10335
    ("allocator", None, ht.TMaybeString),
10336
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10337
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10338
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
10339
    ("os", None, ht.TMaybeString),
10340
    ("disk_template", None, ht.TMaybeString),
10341
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
10342
    ]
10343

    
10344
  def CheckPrereq(self):
10345
    """Check prerequisites.
10346

10347
    This checks the opcode parameters depending on the director and mode test.
10348

10349
    """
10350
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10351
      for attr in ["mem_size", "disks", "disk_template",
10352
                   "os", "tags", "nics", "vcpus"]:
10353
        if not hasattr(self.op, attr):
10354
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10355
                                     attr, errors.ECODE_INVAL)
10356
      iname = self.cfg.ExpandInstanceName(self.op.name)
10357
      if iname is not None:
10358
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10359
                                   iname, errors.ECODE_EXISTS)
10360
      if not isinstance(self.op.nics, list):
10361
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10362
                                   errors.ECODE_INVAL)
10363
      if not isinstance(self.op.disks, list):
10364
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10365
                                   errors.ECODE_INVAL)
10366
      for row in self.op.disks:
10367
        if (not isinstance(row, dict) or
10368
            "size" not in row or
10369
            not isinstance(row["size"], int) or
10370
            "mode" not in row or
10371
            row["mode"] not in ['r', 'w']):
10372
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10373
                                     " parameter", errors.ECODE_INVAL)
10374
      if self.op.hypervisor is None:
10375
        self.op.hypervisor = self.cfg.GetHypervisorType()
10376
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10377
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10378
      self.op.name = fname
10379
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10380
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10381
      if not hasattr(self.op, "evac_nodes"):
10382
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10383
                                   " opcode input", errors.ECODE_INVAL)
10384
    else:
10385
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10386
                                 self.op.mode, errors.ECODE_INVAL)
10387

    
10388
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10389
      if self.op.allocator is None:
10390
        raise errors.OpPrereqError("Missing allocator name",
10391
                                   errors.ECODE_INVAL)
10392
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10393
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10394
                                 self.op.direction, errors.ECODE_INVAL)
10395

    
10396
  def Exec(self, feedback_fn):
10397
    """Run the allocator test.
10398

10399
    """
10400
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10401
      ial = IAllocator(self.cfg, self.rpc,
10402
                       mode=self.op.mode,
10403
                       name=self.op.name,
10404
                       mem_size=self.op.mem_size,
10405
                       disks=self.op.disks,
10406
                       disk_template=self.op.disk_template,
10407
                       os=self.op.os,
10408
                       tags=self.op.tags,
10409
                       nics=self.op.nics,
10410
                       vcpus=self.op.vcpus,
10411
                       hypervisor=self.op.hypervisor,
10412
                       )
10413
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10414
      ial = IAllocator(self.cfg, self.rpc,
10415
                       mode=self.op.mode,
10416
                       name=self.op.name,
10417
                       relocate_from=list(self.relocate_from),
10418
                       )
10419
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10420
      ial = IAllocator(self.cfg, self.rpc,
10421
                       mode=self.op.mode,
10422
                       evac_nodes=self.op.evac_nodes)
10423
    else:
10424
      raise errors.ProgrammerError("Uncatched mode %s in"
10425
                                   " LUTestAllocator.Exec", self.op.mode)
10426

    
10427
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10428
      result = ial.in_text
10429
    else:
10430
      ial.Run(self.op.allocator, validate=False)
10431
      result = ial.out_text
10432
    return result