Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 84d7e26b

History | View | Annotate | Download (392.3 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
from ganeti import query
58
from ganeti import qlang
59

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

    
62
# Common opcode attributes
63

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

    
67

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

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

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

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

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

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

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

    
91

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

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

105
  Note that all commands require root permissions.
106

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

112
  """
113
  HPATH = None
114
  HTYPE = None
115
  _OP_PARAMS = []
116
  REQ_BGL = True
117

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

121
    This needs to be overridden in derived classes in order to check op
122
    validity.
123

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

    
151
    # Tasklets
152
    self.tasklets = None
153

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

    
181
    self.CheckArguments()
182

    
183
  def __GetSSH(self):
184
    """Returns the SshRunner object
185

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

    
191
  ssh = property(fget=__GetSSH)
192

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

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

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

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

208
    """
209
    pass
210

    
211
  def ExpandNames(self):
212
    """Expand names for this LU.
213

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

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

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

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

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

236
    Examples::
237

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

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

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

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

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

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

275
    """
276

    
277
  def CheckPrereq(self):
278
    """Check prerequisites for this LU.
279

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

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

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

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

    
300
  def Exec(self, feedback_fn):
301
    """Execute the LU.
302

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

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

    
315
  def BuildHooksEnv(self):
316
    """Build hooks environment for this LU.
317

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

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

329
    No nodes should be returned as an empty list (and not None).
330

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

334
    """
335
    raise NotImplementedError
336

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

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

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

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

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

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

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

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

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

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

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

394
    If should be called in DeclareLocks in a way similar to::
395

396
      if level == locking.LEVEL_NODE:
397
        self._LockInstancesNodes()
398

399
    @type primary_only: boolean
400
    @param primary_only: only lock primary nodes of locked instances
401

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

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

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

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

    
423
    del self.recalculate_locks[locking.LEVEL_NODE]
424

    
425

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

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

432
  """
433
  HPATH = None
434
  HTYPE = None
435

    
436
  def BuildHooksEnv(self):
437
    """Empty BuildHooksEnv for NoHooksLu.
438

439
    This just raises an error.
440

441
    """
442
    assert False, "BuildHooksEnv called for NoHooksLUs"
443

    
444

    
445
class Tasklet:
446
  """Tasklet base class.
447

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

452
  Subclasses must follow these rules:
453
    - Implement CheckPrereq
454
    - Implement Exec
455

456
  """
457
  def __init__(self, lu):
458
    self.lu = lu
459

    
460
    # Shortcuts
461
    self.cfg = lu.cfg
462
    self.rpc = lu.rpc
463

    
464
  def CheckPrereq(self):
465
    """Check prerequisites for this tasklets.
466

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

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

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

477
    """
478
    pass
479

    
480
  def Exec(self, feedback_fn):
481
    """Execute the tasklet.
482

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

487
    """
488
    raise NotImplementedError
489

    
490

    
491
class _QueryBase:
492
  """Base for query utility classes.
493

494
  """
495
  #: Attribute holding field definitions
496
  FIELDS = None
497

    
498
  def __init__(self, names, fields, use_locking):
499
    """Initializes this class.
500

501
    """
502
    self.names = names
503
    self.use_locking = use_locking
504

    
505
    self.query = query.Query(self.FIELDS, fields)
506
    self.requested_data = self.query.RequestedData()
507

    
508
  @classmethod
509
  def FieldsQuery(cls, fields):
510
    """Returns list of available fields.
511

512
    @return: List of L{objects.QueryFieldDefinition}
513

514
    """
515
    if fields is None:
516
      # Client requests all fields
517
      fdefs = query.GetAllFields(cls.FIELDS.values())
518
    else:
519
      fdefs = query.Query(cls.FIELDS, fields).GetFields()
520

    
521
    return {
522
      "fields": [fdef.ToDict() for fdef in fdefs],
523
      }
524

    
525
  def ExpandNames(self, lu):
526
    """Expand names for this query.
527

528
    See L{LogicalUnit.ExpandNames}.
529

530
    """
531
    raise NotImplementedError()
532

    
533
  def DeclareLocks(self, level):
534
    """Declare locks for this query.
535

536
    See L{LogicalUnit.DeclareLocks}.
537

538
    """
539
    raise NotImplementedError()
540

    
541
  def _GetQueryData(self, lu):
542
    """Collects all data for this query.
543

544
    @return: Query data object
545

546
    """
547
    raise NotImplementedError()
548

    
549
  def NewStyleQuery(self, lu):
550
    """Collect data and execute query.
551

552
    """
553
    data = self._GetQueryData(lu)
554

    
555
    return {
556
      "data": self.query.Query(data),
557
      "fields": [fdef.ToDict()
558
                 for fdef in self.query.GetFields()],
559
      }
560

    
561
  def OldStyleQuery(self, lu):
562
    """Collect data and execute query.
563

564
    """
565
    return self.query.OldStyleQuery(self._GetQueryData(lu))
566

    
567

    
568
def _GetWantedNodes(lu, nodes):
569
  """Returns list of checked and expanded node names.
570

571
  @type lu: L{LogicalUnit}
572
  @param lu: the logical unit on whose behalf we execute
573
  @type nodes: list
574
  @param nodes: list of node names or None for all nodes
575
  @rtype: list
576
  @return: the list of nodes, sorted
577
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
578

579
  """
580
  if not nodes:
581
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
582
      " non-empty list of nodes whose name is to be expanded.")
583

    
584
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
585
  return utils.NiceSort(wanted)
586

    
587

    
588
def _GetWantedInstances(lu, instances):
589
  """Returns list of checked and expanded instance names.
590

591
  @type lu: L{LogicalUnit}
592
  @param lu: the logical unit on whose behalf we execute
593
  @type instances: list
594
  @param instances: list of instance names or None for all instances
595
  @rtype: list
596
  @return: the list of instances, sorted
597
  @raise errors.OpPrereqError: if the instances parameter is wrong type
598
  @raise errors.OpPrereqError: if any of the passed instances is not found
599

600
  """
601
  if instances:
602
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
603
  else:
604
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
605
  return wanted
606

    
607

    
608
def _GetUpdatedParams(old_params, update_dict,
609
                      use_default=True, use_none=False):
610
  """Return the new version of a parameter dictionary.
611

612
  @type old_params: dict
613
  @param old_params: old parameters
614
  @type update_dict: dict
615
  @param update_dict: dict containing new parameter values, or
616
      constants.VALUE_DEFAULT to reset the parameter to its default
617
      value
618
  @param use_default: boolean
619
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
620
      values as 'to be deleted' values
621
  @param use_none: boolean
622
  @type use_none: whether to recognise C{None} values as 'to be
623
      deleted' values
624
  @rtype: dict
625
  @return: the new parameter dictionary
626

627
  """
628
  params_copy = copy.deepcopy(old_params)
629
  for key, val in update_dict.iteritems():
630
    if ((use_default and val == constants.VALUE_DEFAULT) or
631
        (use_none and val is None)):
632
      try:
633
        del params_copy[key]
634
      except KeyError:
635
        pass
636
    else:
637
      params_copy[key] = val
638
  return params_copy
639

    
640

    
641
def _CheckOutputFields(static, dynamic, selected):
642
  """Checks whether all selected fields are valid.
643

644
  @type static: L{utils.FieldSet}
645
  @param static: static fields set
646
  @type dynamic: L{utils.FieldSet}
647
  @param dynamic: dynamic fields set
648

649
  """
650
  f = utils.FieldSet()
651
  f.Extend(static)
652
  f.Extend(dynamic)
653

    
654
  delta = f.NonMatching(selected)
655
  if delta:
656
    raise errors.OpPrereqError("Unknown output fields selected: %s"
657
                               % ",".join(delta), errors.ECODE_INVAL)
658

    
659

    
660
def _CheckGlobalHvParams(params):
661
  """Validates that given hypervisor params are not global ones.
662

663
  This will ensure that instances don't get customised versions of
664
  global params.
665

666
  """
667
  used_globals = constants.HVC_GLOBALS.intersection(params)
668
  if used_globals:
669
    msg = ("The following hypervisor parameters are global and cannot"
670
           " be customized at instance level, please modify them at"
671
           " cluster level: %s" % utils.CommaJoin(used_globals))
672
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
673

    
674

    
675
def _CheckNodeOnline(lu, node, msg=None):
676
  """Ensure that a given node is online.
677

678
  @param lu: the LU on behalf of which we make the check
679
  @param node: the node to check
680
  @param msg: if passed, should be a message to replace the default one
681
  @raise errors.OpPrereqError: if the node is offline
682

683
  """
684
  if msg is None:
685
    msg = "Can't use offline node"
686
  if lu.cfg.GetNodeInfo(node).offline:
687
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
688

    
689

    
690
def _CheckNodeNotDrained(lu, node):
691
  """Ensure that a given node is not drained.
692

693
  @param lu: the LU on behalf of which we make the check
694
  @param node: the node to check
695
  @raise errors.OpPrereqError: if the node is drained
696

697
  """
698
  if lu.cfg.GetNodeInfo(node).drained:
699
    raise errors.OpPrereqError("Can't use drained node %s" % node,
700
                               errors.ECODE_STATE)
701

    
702

    
703
def _CheckNodeVmCapable(lu, node):
704
  """Ensure that a given node is vm capable.
705

706
  @param lu: the LU on behalf of which we make the check
707
  @param node: the node to check
708
  @raise errors.OpPrereqError: if the node is not vm capable
709

710
  """
711
  if not lu.cfg.GetNodeInfo(node).vm_capable:
712
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
713
                               errors.ECODE_STATE)
714

    
715

    
716
def _CheckNodeHasOS(lu, node, os_name, force_variant):
717
  """Ensure that a node supports a given OS.
718

719
  @param lu: the LU on behalf of which we make the check
720
  @param node: the node to check
721
  @param os_name: the OS to query about
722
  @param force_variant: whether to ignore variant errors
723
  @raise errors.OpPrereqError: if the node is not supporting the OS
724

725
  """
726
  result = lu.rpc.call_os_get(node, os_name)
727
  result.Raise("OS '%s' not in supported OS list for node %s" %
728
               (os_name, node),
729
               prereq=True, ecode=errors.ECODE_INVAL)
730
  if not force_variant:
731
    _CheckOSVariant(result.payload, os_name)
732

    
733

    
734
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
735
  """Ensure that a node has the given secondary ip.
736

737
  @type lu: L{LogicalUnit}
738
  @param lu: the LU on behalf of which we make the check
739
  @type node: string
740
  @param node: the node to check
741
  @type secondary_ip: string
742
  @param secondary_ip: the ip to check
743
  @type prereq: boolean
744
  @param prereq: whether to throw a prerequisite or an execute error
745
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
746
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
747

748
  """
749
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
750
  result.Raise("Failure checking secondary ip on node %s" % node,
751
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
752
  if not result.payload:
753
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
754
           " please fix and re-run this command" % secondary_ip)
755
    if prereq:
756
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
757
    else:
758
      raise errors.OpExecError(msg)
759

    
760

    
761
def _RequireFileStorage():
762
  """Checks that file storage is enabled.
763

764
  @raise errors.OpPrereqError: when file storage is disabled
765

766
  """
767
  if not constants.ENABLE_FILE_STORAGE:
768
    raise errors.OpPrereqError("File storage disabled at configure time",
769
                               errors.ECODE_INVAL)
770

    
771

    
772
def _CheckDiskTemplate(template):
773
  """Ensure a given disk template is valid.
774

775
  """
776
  if template not in constants.DISK_TEMPLATES:
777
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
778
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
779
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
780
  if template == constants.DT_FILE:
781
    _RequireFileStorage()
782
  return True
783

    
784

    
785
def _CheckStorageType(storage_type):
786
  """Ensure a given storage type is valid.
787

788
  """
789
  if storage_type not in constants.VALID_STORAGE_TYPES:
790
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
791
                               errors.ECODE_INVAL)
792
  if storage_type == constants.ST_FILE:
793
    _RequireFileStorage()
794
  return True
795

    
796

    
797
def _GetClusterDomainSecret():
798
  """Reads the cluster domain secret.
799

800
  """
801
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
802
                               strict=True)
803

    
804

    
805
def _CheckInstanceDown(lu, instance, reason):
806
  """Ensure that an instance is not running."""
807
  if instance.admin_up:
808
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
809
                               (instance.name, reason), errors.ECODE_STATE)
810

    
811
  pnode = instance.primary_node
812
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
813
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
814
              prereq=True, ecode=errors.ECODE_ENVIRON)
815

    
816
  if instance.name in ins_l.payload:
817
    raise errors.OpPrereqError("Instance %s is running, %s" %
818
                               (instance.name, reason), errors.ECODE_STATE)
819

    
820

    
821
def _ExpandItemName(fn, name, kind):
822
  """Expand an item name.
823

824
  @param fn: the function to use for expansion
825
  @param name: requested item name
826
  @param kind: text description ('Node' or 'Instance')
827
  @return: the resolved (full) name
828
  @raise errors.OpPrereqError: if the item is not found
829

830
  """
831
  full_name = fn(name)
832
  if full_name is None:
833
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
834
                               errors.ECODE_NOENT)
835
  return full_name
836

    
837

    
838
def _ExpandNodeName(cfg, name):
839
  """Wrapper over L{_ExpandItemName} for nodes."""
840
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
841

    
842

    
843
def _ExpandInstanceName(cfg, name):
844
  """Wrapper over L{_ExpandItemName} for instance."""
845
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
846

    
847

    
848
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
849
                          memory, vcpus, nics, disk_template, disks,
850
                          bep, hvp, hypervisor_name):
851
  """Builds instance related env variables for hooks
852

853
  This builds the hook environment from individual variables.
854

855
  @type name: string
856
  @param name: the name of the instance
857
  @type primary_node: string
858
  @param primary_node: the name of the instance's primary node
859
  @type secondary_nodes: list
860
  @param secondary_nodes: list of secondary nodes as strings
861
  @type os_type: string
862
  @param os_type: the name of the instance's OS
863
  @type status: boolean
864
  @param status: the should_run status of the instance
865
  @type memory: string
866
  @param memory: the memory size of the instance
867
  @type vcpus: string
868
  @param vcpus: the count of VCPUs the instance has
869
  @type nics: list
870
  @param nics: list of tuples (ip, mac, mode, link) representing
871
      the NICs the instance has
872
  @type disk_template: string
873
  @param disk_template: the disk template of the instance
874
  @type disks: list
875
  @param disks: the list of (size, mode) pairs
876
  @type bep: dict
877
  @param bep: the backend parameters for the instance
878
  @type hvp: dict
879
  @param hvp: the hypervisor parameters for the instance
880
  @type hypervisor_name: string
881
  @param hypervisor_name: the hypervisor for the instance
882
  @rtype: dict
883
  @return: the hook environment for this instance
884

885
  """
886
  if status:
887
    str_status = "up"
888
  else:
889
    str_status = "down"
890
  env = {
891
    "OP_TARGET": name,
892
    "INSTANCE_NAME": name,
893
    "INSTANCE_PRIMARY": primary_node,
894
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
895
    "INSTANCE_OS_TYPE": os_type,
896
    "INSTANCE_STATUS": str_status,
897
    "INSTANCE_MEMORY": memory,
898
    "INSTANCE_VCPUS": vcpus,
899
    "INSTANCE_DISK_TEMPLATE": disk_template,
900
    "INSTANCE_HYPERVISOR": hypervisor_name,
901
  }
902

    
903
  if nics:
904
    nic_count = len(nics)
905
    for idx, (ip, mac, mode, link) in enumerate(nics):
906
      if ip is None:
907
        ip = ""
908
      env["INSTANCE_NIC%d_IP" % idx] = ip
909
      env["INSTANCE_NIC%d_MAC" % idx] = mac
910
      env["INSTANCE_NIC%d_MODE" % idx] = mode
911
      env["INSTANCE_NIC%d_LINK" % idx] = link
912
      if mode == constants.NIC_MODE_BRIDGED:
913
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
914
  else:
915
    nic_count = 0
916

    
917
  env["INSTANCE_NIC_COUNT"] = nic_count
918

    
919
  if disks:
920
    disk_count = len(disks)
921
    for idx, (size, mode) in enumerate(disks):
922
      env["INSTANCE_DISK%d_SIZE" % idx] = size
923
      env["INSTANCE_DISK%d_MODE" % idx] = mode
924
  else:
925
    disk_count = 0
926

    
927
  env["INSTANCE_DISK_COUNT"] = disk_count
928

    
929
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
930
    for key, value in source.items():
931
      env["INSTANCE_%s_%s" % (kind, key)] = value
932

    
933
  return env
934

    
935

    
936
def _NICListToTuple(lu, nics):
937
  """Build a list of nic information tuples.
938

939
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
940
  value in LUQueryInstanceData.
941

942
  @type lu:  L{LogicalUnit}
943
  @param lu: the logical unit on whose behalf we execute
944
  @type nics: list of L{objects.NIC}
945
  @param nics: list of nics to convert to hooks tuples
946

947
  """
948
  hooks_nics = []
949
  cluster = lu.cfg.GetClusterInfo()
950
  for nic in nics:
951
    ip = nic.ip
952
    mac = nic.mac
953
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
954
    mode = filled_params[constants.NIC_MODE]
955
    link = filled_params[constants.NIC_LINK]
956
    hooks_nics.append((ip, mac, mode, link))
957
  return hooks_nics
958

    
959

    
960
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
961
  """Builds instance related env variables for hooks from an object.
962

963
  @type lu: L{LogicalUnit}
964
  @param lu: the logical unit on whose behalf we execute
965
  @type instance: L{objects.Instance}
966
  @param instance: the instance for which we should build the
967
      environment
968
  @type override: dict
969
  @param override: dictionary with key/values that will override
970
      our values
971
  @rtype: dict
972
  @return: the hook environment dictionary
973

974
  """
975
  cluster = lu.cfg.GetClusterInfo()
976
  bep = cluster.FillBE(instance)
977
  hvp = cluster.FillHV(instance)
978
  args = {
979
    'name': instance.name,
980
    'primary_node': instance.primary_node,
981
    'secondary_nodes': instance.secondary_nodes,
982
    'os_type': instance.os,
983
    'status': instance.admin_up,
984
    'memory': bep[constants.BE_MEMORY],
985
    'vcpus': bep[constants.BE_VCPUS],
986
    'nics': _NICListToTuple(lu, instance.nics),
987
    'disk_template': instance.disk_template,
988
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
989
    'bep': bep,
990
    'hvp': hvp,
991
    'hypervisor_name': instance.hypervisor,
992
  }
993
  if override:
994
    args.update(override)
995
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
996

    
997

    
998
def _AdjustCandidatePool(lu, exceptions):
999
  """Adjust the candidate pool after node operations.
1000

1001
  """
1002
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1003
  if mod_list:
1004
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1005
               utils.CommaJoin(node.name for node in mod_list))
1006
    for name in mod_list:
1007
      lu.context.ReaddNode(name)
1008
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1009
  if mc_now > mc_max:
1010
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1011
               (mc_now, mc_max))
1012

    
1013

    
1014
def _DecideSelfPromotion(lu, exceptions=None):
1015
  """Decide whether I should promote myself as a master candidate.
1016

1017
  """
1018
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1019
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1020
  # the new node will increase mc_max with one, so:
1021
  mc_should = min(mc_should + 1, cp_size)
1022
  return mc_now < mc_should
1023

    
1024

    
1025
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1026
  """Check that the brigdes needed by a list of nics exist.
1027

1028
  """
1029
  cluster = lu.cfg.GetClusterInfo()
1030
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1031
  brlist = [params[constants.NIC_LINK] for params in paramslist
1032
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1033
  if brlist:
1034
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1035
    result.Raise("Error checking bridges on destination node '%s'" %
1036
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1037

    
1038

    
1039
def _CheckInstanceBridgesExist(lu, instance, node=None):
1040
  """Check that the brigdes needed by an instance exist.
1041

1042
  """
1043
  if node is None:
1044
    node = instance.primary_node
1045
  _CheckNicsBridgesExist(lu, instance.nics, node)
1046

    
1047

    
1048
def _CheckOSVariant(os_obj, name):
1049
  """Check whether an OS name conforms to the os variants specification.
1050

1051
  @type os_obj: L{objects.OS}
1052
  @param os_obj: OS object to check
1053
  @type name: string
1054
  @param name: OS name passed by the user, to check for validity
1055

1056
  """
1057
  if not os_obj.supported_variants:
1058
    return
1059
  variant = objects.OS.GetVariant(name)
1060
  if not variant:
1061
    raise errors.OpPrereqError("OS name must include a variant",
1062
                               errors.ECODE_INVAL)
1063

    
1064
  if variant not in os_obj.supported_variants:
1065
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1066

    
1067

    
1068
def _GetNodeInstancesInner(cfg, fn):
1069
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1070

    
1071

    
1072
def _GetNodeInstances(cfg, node_name):
1073
  """Returns a list of all primary and secondary instances on a node.
1074

1075
  """
1076

    
1077
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1078

    
1079

    
1080
def _GetNodePrimaryInstances(cfg, node_name):
1081
  """Returns primary instances on a node.
1082

1083
  """
1084
  return _GetNodeInstancesInner(cfg,
1085
                                lambda inst: node_name == inst.primary_node)
1086

    
1087

    
1088
def _GetNodeSecondaryInstances(cfg, node_name):
1089
  """Returns secondary instances on a node.
1090

1091
  """
1092
  return _GetNodeInstancesInner(cfg,
1093
                                lambda inst: node_name in inst.secondary_nodes)
1094

    
1095

    
1096
def _GetStorageTypeArgs(cfg, storage_type):
1097
  """Returns the arguments for a storage type.
1098

1099
  """
1100
  # Special case for file storage
1101
  if storage_type == constants.ST_FILE:
1102
    # storage.FileStorage wants a list of storage directories
1103
    return [[cfg.GetFileStorageDir()]]
1104

    
1105
  return []
1106

    
1107

    
1108
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1109
  faulty = []
1110

    
1111
  for dev in instance.disks:
1112
    cfg.SetDiskID(dev, node_name)
1113

    
1114
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1115
  result.Raise("Failed to get disk status from node %s" % node_name,
1116
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1117

    
1118
  for idx, bdev_status in enumerate(result.payload):
1119
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1120
      faulty.append(idx)
1121

    
1122
  return faulty
1123

    
1124

    
1125
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1126
  """Check the sanity of iallocator and node arguments and use the
1127
  cluster-wide iallocator if appropriate.
1128

1129
  Check that at most one of (iallocator, node) is specified. If none is
1130
  specified, then the LU's opcode's iallocator slot is filled with the
1131
  cluster-wide default iallocator.
1132

1133
  @type iallocator_slot: string
1134
  @param iallocator_slot: the name of the opcode iallocator slot
1135
  @type node_slot: string
1136
  @param node_slot: the name of the opcode target node slot
1137

1138
  """
1139
  node = getattr(lu.op, node_slot, None)
1140
  iallocator = getattr(lu.op, iallocator_slot, None)
1141

    
1142
  if node is not None and iallocator is not None:
1143
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1144
                               errors.ECODE_INVAL)
1145
  elif node is None and iallocator is None:
1146
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1147
    if default_iallocator:
1148
      setattr(lu.op, iallocator_slot, default_iallocator)
1149
    else:
1150
      raise errors.OpPrereqError("No iallocator or node given and no"
1151
                                 " cluster-wide default iallocator found."
1152
                                 " Please specify either an iallocator or a"
1153
                                 " node, or set a cluster-wide default"
1154
                                 " iallocator.")
1155

    
1156

    
1157
class LUPostInitCluster(LogicalUnit):
1158
  """Logical unit for running hooks after cluster initialization.
1159

1160
  """
1161
  HPATH = "cluster-init"
1162
  HTYPE = constants.HTYPE_CLUSTER
1163

    
1164
  def BuildHooksEnv(self):
1165
    """Build hooks env.
1166

1167
    """
1168
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1169
    mn = self.cfg.GetMasterNode()
1170
    return env, [], [mn]
1171

    
1172
  def Exec(self, feedback_fn):
1173
    """Nothing to do.
1174

1175
    """
1176
    return True
1177

    
1178

    
1179
class LUDestroyCluster(LogicalUnit):
1180
  """Logical unit for destroying the cluster.
1181

1182
  """
1183
  HPATH = "cluster-destroy"
1184
  HTYPE = constants.HTYPE_CLUSTER
1185

    
1186
  def BuildHooksEnv(self):
1187
    """Build hooks env.
1188

1189
    """
1190
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1191
    return env, [], []
1192

    
1193
  def CheckPrereq(self):
1194
    """Check prerequisites.
1195

1196
    This checks whether the cluster is empty.
1197

1198
    Any errors are signaled by raising errors.OpPrereqError.
1199

1200
    """
1201
    master = self.cfg.GetMasterNode()
1202

    
1203
    nodelist = self.cfg.GetNodeList()
1204
    if len(nodelist) != 1 or nodelist[0] != master:
1205
      raise errors.OpPrereqError("There are still %d node(s) in"
1206
                                 " this cluster." % (len(nodelist) - 1),
1207
                                 errors.ECODE_INVAL)
1208
    instancelist = self.cfg.GetInstanceList()
1209
    if instancelist:
1210
      raise errors.OpPrereqError("There are still %d instance(s) in"
1211
                                 " this cluster." % len(instancelist),
1212
                                 errors.ECODE_INVAL)
1213

    
1214
  def Exec(self, feedback_fn):
1215
    """Destroys the cluster.
1216

1217
    """
1218
    master = self.cfg.GetMasterNode()
1219

    
1220
    # Run post hooks on master node before it's removed
1221
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1222
    try:
1223
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1224
    except:
1225
      # pylint: disable-msg=W0702
1226
      self.LogWarning("Errors occurred running hooks on %s" % master)
1227

    
1228
    result = self.rpc.call_node_stop_master(master, False)
1229
    result.Raise("Could not disable the master role")
1230

    
1231
    return master
1232

    
1233

    
1234
def _VerifyCertificate(filename):
1235
  """Verifies a certificate for LUVerifyCluster.
1236

1237
  @type filename: string
1238
  @param filename: Path to PEM file
1239

1240
  """
1241
  try:
1242
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1243
                                           utils.ReadFile(filename))
1244
  except Exception, err: # pylint: disable-msg=W0703
1245
    return (LUVerifyCluster.ETYPE_ERROR,
1246
            "Failed to load X509 certificate %s: %s" % (filename, err))
1247

    
1248
  (errcode, msg) = \
1249
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1250
                                constants.SSL_CERT_EXPIRATION_ERROR)
1251

    
1252
  if msg:
1253
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1254
  else:
1255
    fnamemsg = None
1256

    
1257
  if errcode is None:
1258
    return (None, fnamemsg)
1259
  elif errcode == utils.CERT_WARNING:
1260
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1261
  elif errcode == utils.CERT_ERROR:
1262
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1263

    
1264
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1265

    
1266

    
1267
class LUVerifyCluster(LogicalUnit):
1268
  """Verifies the cluster status.
1269

1270
  """
1271
  HPATH = "cluster-verify"
1272
  HTYPE = constants.HTYPE_CLUSTER
1273
  _OP_PARAMS = [
1274
    ("skip_checks", ht.EmptyList,
1275
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1276
    ("verbose", False, ht.TBool),
1277
    ("error_codes", False, ht.TBool),
1278
    ("debug_simulate_errors", False, ht.TBool),
1279
    ]
1280
  REQ_BGL = False
1281

    
1282
  TCLUSTER = "cluster"
1283
  TNODE = "node"
1284
  TINSTANCE = "instance"
1285

    
1286
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1287
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1288
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1289
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1290
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1291
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1292
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1293
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1294
  ENODEDRBD = (TNODE, "ENODEDRBD")
1295
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1296
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1297
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1298
  ENODEHV = (TNODE, "ENODEHV")
1299
  ENODELVM = (TNODE, "ENODELVM")
1300
  ENODEN1 = (TNODE, "ENODEN1")
1301
  ENODENET = (TNODE, "ENODENET")
1302
  ENODEOS = (TNODE, "ENODEOS")
1303
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1304
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1305
  ENODERPC = (TNODE, "ENODERPC")
1306
  ENODESSH = (TNODE, "ENODESSH")
1307
  ENODEVERSION = (TNODE, "ENODEVERSION")
1308
  ENODESETUP = (TNODE, "ENODESETUP")
1309
  ENODETIME = (TNODE, "ENODETIME")
1310

    
1311
  ETYPE_FIELD = "code"
1312
  ETYPE_ERROR = "ERROR"
1313
  ETYPE_WARNING = "WARNING"
1314

    
1315
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1316

    
1317
  class NodeImage(object):
1318
    """A class representing the logical and physical status of a node.
1319

1320
    @type name: string
1321
    @ivar name: the node name to which this object refers
1322
    @ivar volumes: a structure as returned from
1323
        L{ganeti.backend.GetVolumeList} (runtime)
1324
    @ivar instances: a list of running instances (runtime)
1325
    @ivar pinst: list of configured primary instances (config)
1326
    @ivar sinst: list of configured secondary instances (config)
1327
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1328
        of this node (config)
1329
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1330
    @ivar dfree: free disk, as reported by the node (runtime)
1331
    @ivar offline: the offline status (config)
1332
    @type rpc_fail: boolean
1333
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1334
        not whether the individual keys were correct) (runtime)
1335
    @type lvm_fail: boolean
1336
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1337
    @type hyp_fail: boolean
1338
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1339
    @type ghost: boolean
1340
    @ivar ghost: whether this is a known node or not (config)
1341
    @type os_fail: boolean
1342
    @ivar os_fail: whether the RPC call didn't return valid OS data
1343
    @type oslist: list
1344
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1345
    @type vm_capable: boolean
1346
    @ivar vm_capable: whether the node can host instances
1347

1348
    """
1349
    def __init__(self, offline=False, name=None, vm_capable=True):
1350
      self.name = name
1351
      self.volumes = {}
1352
      self.instances = []
1353
      self.pinst = []
1354
      self.sinst = []
1355
      self.sbp = {}
1356
      self.mfree = 0
1357
      self.dfree = 0
1358
      self.offline = offline
1359
      self.vm_capable = vm_capable
1360
      self.rpc_fail = False
1361
      self.lvm_fail = False
1362
      self.hyp_fail = False
1363
      self.ghost = False
1364
      self.os_fail = False
1365
      self.oslist = {}
1366

    
1367
  def ExpandNames(self):
1368
    self.needed_locks = {
1369
      locking.LEVEL_NODE: locking.ALL_SET,
1370
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1371
    }
1372
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1373

    
1374
  def _Error(self, ecode, item, msg, *args, **kwargs):
1375
    """Format an error message.
1376

1377
    Based on the opcode's error_codes parameter, either format a
1378
    parseable error code, or a simpler error string.
1379

1380
    This must be called only from Exec and functions called from Exec.
1381

1382
    """
1383
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1384
    itype, etxt = ecode
1385
    # first complete the msg
1386
    if args:
1387
      msg = msg % args
1388
    # then format the whole message
1389
    if self.op.error_codes:
1390
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1391
    else:
1392
      if item:
1393
        item = " " + item
1394
      else:
1395
        item = ""
1396
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1397
    # and finally report it via the feedback_fn
1398
    self._feedback_fn("  - %s" % msg)
1399

    
1400
  def _ErrorIf(self, cond, *args, **kwargs):
1401
    """Log an error message if the passed condition is True.
1402

1403
    """
1404
    cond = bool(cond) or self.op.debug_simulate_errors
1405
    if cond:
1406
      self._Error(*args, **kwargs)
1407
    # do not mark the operation as failed for WARN cases only
1408
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1409
      self.bad = self.bad or cond
1410

    
1411
  def _VerifyNode(self, ninfo, nresult):
1412
    """Perform some basic validation on data returned from a node.
1413

1414
      - check the result data structure is well formed and has all the
1415
        mandatory fields
1416
      - check ganeti version
1417

1418
    @type ninfo: L{objects.Node}
1419
    @param ninfo: the node to check
1420
    @param nresult: the results from the node
1421
    @rtype: boolean
1422
    @return: whether overall this call was successful (and we can expect
1423
         reasonable values in the respose)
1424

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

    
1429
    # main result, nresult should be a non-empty dict
1430
    test = not nresult or not isinstance(nresult, dict)
1431
    _ErrorIf(test, self.ENODERPC, node,
1432
                  "unable to verify node: no data returned")
1433
    if test:
1434
      return False
1435

    
1436
    # compares ganeti version
1437
    local_version = constants.PROTOCOL_VERSION
1438
    remote_version = nresult.get("version", None)
1439
    test = not (remote_version and
1440
                isinstance(remote_version, (list, tuple)) and
1441
                len(remote_version) == 2)
1442
    _ErrorIf(test, self.ENODERPC, node,
1443
             "connection to node returned invalid data")
1444
    if test:
1445
      return False
1446

    
1447
    test = local_version != remote_version[0]
1448
    _ErrorIf(test, self.ENODEVERSION, node,
1449
             "incompatible protocol versions: master %s,"
1450
             " node %s", local_version, remote_version[0])
1451
    if test:
1452
      return False
1453

    
1454
    # node seems compatible, we can actually try to look into its results
1455

    
1456
    # full package version
1457
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1458
                  self.ENODEVERSION, node,
1459
                  "software version mismatch: master %s, node %s",
1460
                  constants.RELEASE_VERSION, remote_version[1],
1461
                  code=self.ETYPE_WARNING)
1462

    
1463
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1464
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1465
      for hv_name, hv_result in hyp_result.iteritems():
1466
        test = hv_result is not None
1467
        _ErrorIf(test, self.ENODEHV, node,
1468
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1469

    
1470
    test = nresult.get(constants.NV_NODESETUP,
1471
                           ["Missing NODESETUP results"])
1472
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1473
             "; ".join(test))
1474

    
1475
    return True
1476

    
1477
  def _VerifyNodeTime(self, ninfo, nresult,
1478
                      nvinfo_starttime, nvinfo_endtime):
1479
    """Check the node time.
1480

1481
    @type ninfo: L{objects.Node}
1482
    @param ninfo: the node to check
1483
    @param nresult: the remote results for the node
1484
    @param nvinfo_starttime: the start time of the RPC call
1485
    @param nvinfo_endtime: the end time of the RPC call
1486

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

    
1491
    ntime = nresult.get(constants.NV_TIME, None)
1492
    try:
1493
      ntime_merged = utils.MergeTime(ntime)
1494
    except (ValueError, TypeError):
1495
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1496
      return
1497

    
1498
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1499
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1500
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1501
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1502
    else:
1503
      ntime_diff = None
1504

    
1505
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1506
             "Node time diverges by at least %s from master node time",
1507
             ntime_diff)
1508

    
1509
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1510
    """Check the node time.
1511

1512
    @type ninfo: L{objects.Node}
1513
    @param ninfo: the node to check
1514
    @param nresult: the remote results for the node
1515
    @param vg_name: the configured VG name
1516

1517
    """
1518
    if vg_name is None:
1519
      return
1520

    
1521
    node = ninfo.name
1522
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1523

    
1524
    # checks vg existence and size > 20G
1525
    vglist = nresult.get(constants.NV_VGLIST, None)
1526
    test = not vglist
1527
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1528
    if not test:
1529
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1530
                                            constants.MIN_VG_SIZE)
1531
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1532

    
1533
    # check pv names
1534
    pvlist = nresult.get(constants.NV_PVLIST, None)
1535
    test = pvlist is None
1536
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1537
    if not test:
1538
      # check that ':' is not present in PV names, since it's a
1539
      # special character for lvcreate (denotes the range of PEs to
1540
      # use on the PV)
1541
      for _, pvname, owner_vg in pvlist:
1542
        test = ":" in pvname
1543
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1544
                 " '%s' of VG '%s'", pvname, owner_vg)
1545

    
1546
  def _VerifyNodeNetwork(self, ninfo, nresult):
1547
    """Check the node time.
1548

1549
    @type ninfo: L{objects.Node}
1550
    @param ninfo: the node to check
1551
    @param nresult: the remote results for the node
1552

1553
    """
1554
    node = ninfo.name
1555
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1556

    
1557
    test = constants.NV_NODELIST not in nresult
1558
    _ErrorIf(test, self.ENODESSH, node,
1559
             "node hasn't returned node ssh connectivity data")
1560
    if not test:
1561
      if nresult[constants.NV_NODELIST]:
1562
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1563
          _ErrorIf(True, self.ENODESSH, node,
1564
                   "ssh communication with node '%s': %s", a_node, a_msg)
1565

    
1566
    test = constants.NV_NODENETTEST not in nresult
1567
    _ErrorIf(test, self.ENODENET, node,
1568
             "node hasn't returned node tcp connectivity data")
1569
    if not test:
1570
      if nresult[constants.NV_NODENETTEST]:
1571
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1572
        for anode in nlist:
1573
          _ErrorIf(True, self.ENODENET, node,
1574
                   "tcp communication with node '%s': %s",
1575
                   anode, nresult[constants.NV_NODENETTEST][anode])
1576

    
1577
    test = constants.NV_MASTERIP not in nresult
1578
    _ErrorIf(test, self.ENODENET, node,
1579
             "node hasn't returned node master IP reachability data")
1580
    if not test:
1581
      if not nresult[constants.NV_MASTERIP]:
1582
        if node == self.master_node:
1583
          msg = "the master node cannot reach the master IP (not configured?)"
1584
        else:
1585
          msg = "cannot reach the master IP"
1586
        _ErrorIf(True, self.ENODENET, node, msg)
1587

    
1588
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1589
                      diskstatus):
1590
    """Verify an instance.
1591

1592
    This function checks to see if the required block devices are
1593
    available on the instance's node.
1594

1595
    """
1596
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1597
    node_current = instanceconfig.primary_node
1598

    
1599
    node_vol_should = {}
1600
    instanceconfig.MapLVsByNode(node_vol_should)
1601

    
1602
    for node in node_vol_should:
1603
      n_img = node_image[node]
1604
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1605
        # ignore missing volumes on offline or broken nodes
1606
        continue
1607
      for volume in node_vol_should[node]:
1608
        test = volume not in n_img.volumes
1609
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1610
                 "volume %s missing on node %s", volume, node)
1611

    
1612
    if instanceconfig.admin_up:
1613
      pri_img = node_image[node_current]
1614
      test = instance not in pri_img.instances and not pri_img.offline
1615
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1616
               "instance not running on its primary node %s",
1617
               node_current)
1618

    
1619
    for node, n_img in node_image.items():
1620
      if (not node == node_current):
1621
        test = instance in n_img.instances
1622
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1623
                 "instance should not run on node %s", node)
1624

    
1625
    diskdata = [(nname, success, status, idx)
1626
                for (nname, disks) in diskstatus.items()
1627
                for idx, (success, status) in enumerate(disks)]
1628

    
1629
    for nname, success, bdev_status, idx in diskdata:
1630
      _ErrorIf(instanceconfig.admin_up and not success,
1631
               self.EINSTANCEFAULTYDISK, instance,
1632
               "couldn't retrieve status for disk/%s on %s: %s",
1633
               idx, nname, bdev_status)
1634
      _ErrorIf((instanceconfig.admin_up and success and
1635
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1636
               self.EINSTANCEFAULTYDISK, instance,
1637
               "disk/%s on %s is faulty", idx, nname)
1638

    
1639
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1640
    """Verify if there are any unknown volumes in the cluster.
1641

1642
    The .os, .swap and backup volumes are ignored. All other volumes are
1643
    reported as unknown.
1644

1645
    @type reserved: L{ganeti.utils.FieldSet}
1646
    @param reserved: a FieldSet of reserved volume names
1647

1648
    """
1649
    for node, n_img in node_image.items():
1650
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1651
        # skip non-healthy nodes
1652
        continue
1653
      for volume in n_img.volumes:
1654
        test = ((node not in node_vol_should or
1655
                volume not in node_vol_should[node]) and
1656
                not reserved.Matches(volume))
1657
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1658
                      "volume %s is unknown", volume)
1659

    
1660
  def _VerifyOrphanInstances(self, instancelist, node_image):
1661
    """Verify the list of running instances.
1662

1663
    This checks what instances are running but unknown to the cluster.
1664

1665
    """
1666
    for node, n_img in node_image.items():
1667
      for o_inst in n_img.instances:
1668
        test = o_inst not in instancelist
1669
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1670
                      "instance %s on node %s should not exist", o_inst, node)
1671

    
1672
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1673
    """Verify N+1 Memory Resilience.
1674

1675
    Check that if one single node dies we can still start all the
1676
    instances it was primary for.
1677

1678
    """
1679
    for node, n_img in node_image.items():
1680
      # This code checks that every node which is now listed as
1681
      # secondary has enough memory to host all instances it is
1682
      # supposed to should a single other node in the cluster fail.
1683
      # FIXME: not ready for failover to an arbitrary node
1684
      # FIXME: does not support file-backed instances
1685
      # WARNING: we currently take into account down instances as well
1686
      # as up ones, considering that even if they're down someone
1687
      # might want to start them even in the event of a node failure.
1688
      for prinode, instances in n_img.sbp.items():
1689
        needed_mem = 0
1690
        for instance in instances:
1691
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1692
          if bep[constants.BE_AUTO_BALANCE]:
1693
            needed_mem += bep[constants.BE_MEMORY]
1694
        test = n_img.mfree < needed_mem
1695
        self._ErrorIf(test, self.ENODEN1, node,
1696
                      "not enough memory on to accommodate"
1697
                      " failovers should peer node %s fail", prinode)
1698

    
1699
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1700
                       master_files):
1701
    """Verifies and computes the node required file checksums.
1702

1703
    @type ninfo: L{objects.Node}
1704
    @param ninfo: the node to check
1705
    @param nresult: the remote results for the node
1706
    @param file_list: required list of files
1707
    @param local_cksum: dictionary of local files and their checksums
1708
    @param master_files: list of files that only masters should have
1709

1710
    """
1711
    node = ninfo.name
1712
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1713

    
1714
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1715
    test = not isinstance(remote_cksum, dict)
1716
    _ErrorIf(test, self.ENODEFILECHECK, node,
1717
             "node hasn't returned file checksum data")
1718
    if test:
1719
      return
1720

    
1721
    for file_name in file_list:
1722
      node_is_mc = ninfo.master_candidate
1723
      must_have = (file_name not in master_files) or node_is_mc
1724
      # missing
1725
      test1 = file_name not in remote_cksum
1726
      # invalid checksum
1727
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1728
      # existing and good
1729
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1730
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1731
               "file '%s' missing", file_name)
1732
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1733
               "file '%s' has wrong checksum", file_name)
1734
      # not candidate and this is not a must-have file
1735
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1736
               "file '%s' should not exist on non master"
1737
               " candidates (and the file is outdated)", file_name)
1738
      # all good, except non-master/non-must have combination
1739
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1740
               "file '%s' should not exist"
1741
               " on non master candidates", file_name)
1742

    
1743
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1744
                      drbd_map):
1745
    """Verifies and the node DRBD status.
1746

1747
    @type ninfo: L{objects.Node}
1748
    @param ninfo: the node to check
1749
    @param nresult: the remote results for the node
1750
    @param instanceinfo: the dict of instances
1751
    @param drbd_helper: the configured DRBD usermode helper
1752
    @param drbd_map: the DRBD map as returned by
1753
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1754

1755
    """
1756
    node = ninfo.name
1757
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1758

    
1759
    if drbd_helper:
1760
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1761
      test = (helper_result == None)
1762
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1763
               "no drbd usermode helper returned")
1764
      if helper_result:
1765
        status, payload = helper_result
1766
        test = not status
1767
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1768
                 "drbd usermode helper check unsuccessful: %s", payload)
1769
        test = status and (payload != drbd_helper)
1770
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1771
                 "wrong drbd usermode helper: %s", payload)
1772

    
1773
    # compute the DRBD minors
1774
    node_drbd = {}
1775
    for minor, instance in drbd_map[node].items():
1776
      test = instance not in instanceinfo
1777
      _ErrorIf(test, self.ECLUSTERCFG, None,
1778
               "ghost instance '%s' in temporary DRBD map", instance)
1779
        # ghost instance should not be running, but otherwise we
1780
        # don't give double warnings (both ghost instance and
1781
        # unallocated minor in use)
1782
      if test:
1783
        node_drbd[minor] = (instance, False)
1784
      else:
1785
        instance = instanceinfo[instance]
1786
        node_drbd[minor] = (instance.name, instance.admin_up)
1787

    
1788
    # and now check them
1789
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1790
    test = not isinstance(used_minors, (tuple, list))
1791
    _ErrorIf(test, self.ENODEDRBD, node,
1792
             "cannot parse drbd status file: %s", str(used_minors))
1793
    if test:
1794
      # we cannot check drbd status
1795
      return
1796

    
1797
    for minor, (iname, must_exist) in node_drbd.items():
1798
      test = minor not in used_minors and must_exist
1799
      _ErrorIf(test, self.ENODEDRBD, node,
1800
               "drbd minor %d of instance %s is not active", minor, iname)
1801
    for minor in used_minors:
1802
      test = minor not in node_drbd
1803
      _ErrorIf(test, self.ENODEDRBD, node,
1804
               "unallocated drbd minor %d is in use", minor)
1805

    
1806
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1807
    """Builds the node OS structures.
1808

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

1814
    """
1815
    node = ninfo.name
1816
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1817

    
1818
    remote_os = nresult.get(constants.NV_OSLIST, None)
1819
    test = (not isinstance(remote_os, list) or
1820
            not compat.all(isinstance(v, list) and len(v) == 7
1821
                           for v in remote_os))
1822

    
1823
    _ErrorIf(test, self.ENODEOS, node,
1824
             "node hasn't returned valid OS data")
1825

    
1826
    nimg.os_fail = test
1827

    
1828
    if test:
1829
      return
1830

    
1831
    os_dict = {}
1832

    
1833
    for (name, os_path, status, diagnose,
1834
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1835

    
1836
      if name not in os_dict:
1837
        os_dict[name] = []
1838

    
1839
      # parameters is a list of lists instead of list of tuples due to
1840
      # JSON lacking a real tuple type, fix it:
1841
      parameters = [tuple(v) for v in parameters]
1842
      os_dict[name].append((os_path, status, diagnose,
1843
                            set(variants), set(parameters), set(api_ver)))
1844

    
1845
    nimg.oslist = os_dict
1846

    
1847
  def _VerifyNodeOS(self, ninfo, nimg, base):
1848
    """Verifies the node OS list.
1849

1850
    @type ninfo: L{objects.Node}
1851
    @param ninfo: the node to check
1852
    @param nimg: the node image object
1853
    @param base: the 'template' node we match against (e.g. from the master)
1854

1855
    """
1856
    node = ninfo.name
1857
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1858

    
1859
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1860

    
1861
    for os_name, os_data in nimg.oslist.items():
1862
      assert os_data, "Empty OS status for OS %s?!" % os_name
1863
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1864
      _ErrorIf(not f_status, self.ENODEOS, node,
1865
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1866
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1867
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1868
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1869
      # this will catched in backend too
1870
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1871
               and not f_var, self.ENODEOS, node,
1872
               "OS %s with API at least %d does not declare any variant",
1873
               os_name, constants.OS_API_V15)
1874
      # comparisons with the 'base' image
1875
      test = os_name not in base.oslist
1876
      _ErrorIf(test, self.ENODEOS, node,
1877
               "Extra OS %s not present on reference node (%s)",
1878
               os_name, base.name)
1879
      if test:
1880
        continue
1881
      assert base.oslist[os_name], "Base node has empty OS status?"
1882
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1883
      if not b_status:
1884
        # base OS is invalid, skipping
1885
        continue
1886
      for kind, a, b in [("API version", f_api, b_api),
1887
                         ("variants list", f_var, b_var),
1888
                         ("parameters", f_param, b_param)]:
1889
        _ErrorIf(a != b, self.ENODEOS, node,
1890
                 "OS %s %s differs from reference node %s: %s vs. %s",
1891
                 kind, os_name, base.name,
1892
                 utils.CommaJoin(a), utils.CommaJoin(b))
1893

    
1894
    # check any missing OSes
1895
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1896
    _ErrorIf(missing, self.ENODEOS, node,
1897
             "OSes present on reference node %s but missing on this node: %s",
1898
             base.name, utils.CommaJoin(missing))
1899

    
1900
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1901
    """Verifies and updates the node volume data.
1902

1903
    This function will update a L{NodeImage}'s internal structures
1904
    with data from the remote call.
1905

1906
    @type ninfo: L{objects.Node}
1907
    @param ninfo: the node to check
1908
    @param nresult: the remote results for the node
1909
    @param nimg: the node image object
1910
    @param vg_name: the configured VG name
1911

1912
    """
1913
    node = ninfo.name
1914
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1915

    
1916
    nimg.lvm_fail = True
1917
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1918
    if vg_name is None:
1919
      pass
1920
    elif isinstance(lvdata, basestring):
1921
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1922
               utils.SafeEncode(lvdata))
1923
    elif not isinstance(lvdata, dict):
1924
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1925
    else:
1926
      nimg.volumes = lvdata
1927
      nimg.lvm_fail = False
1928

    
1929
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1930
    """Verifies and updates the node instance list.
1931

1932
    If the listing was successful, then updates this node's instance
1933
    list. Otherwise, it marks the RPC call as failed for the instance
1934
    list key.
1935

1936
    @type ninfo: L{objects.Node}
1937
    @param ninfo: the node to check
1938
    @param nresult: the remote results for the node
1939
    @param nimg: the node image object
1940

1941
    """
1942
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1943
    test = not isinstance(idata, list)
1944
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1945
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1946
    if test:
1947
      nimg.hyp_fail = True
1948
    else:
1949
      nimg.instances = idata
1950

    
1951
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1952
    """Verifies and computes a node information map
1953

1954
    @type ninfo: L{objects.Node}
1955
    @param ninfo: the node to check
1956
    @param nresult: the remote results for the node
1957
    @param nimg: the node image object
1958
    @param vg_name: the configured VG name
1959

1960
    """
1961
    node = ninfo.name
1962
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1963

    
1964
    # try to read free memory (from the hypervisor)
1965
    hv_info = nresult.get(constants.NV_HVINFO, None)
1966
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1967
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1968
    if not test:
1969
      try:
1970
        nimg.mfree = int(hv_info["memory_free"])
1971
      except (ValueError, TypeError):
1972
        _ErrorIf(True, self.ENODERPC, node,
1973
                 "node returned invalid nodeinfo, check hypervisor")
1974

    
1975
    # FIXME: devise a free space model for file based instances as well
1976
    if vg_name is not None:
1977
      test = (constants.NV_VGLIST not in nresult or
1978
              vg_name not in nresult[constants.NV_VGLIST])
1979
      _ErrorIf(test, self.ENODELVM, node,
1980
               "node didn't return data for the volume group '%s'"
1981
               " - it is either missing or broken", vg_name)
1982
      if not test:
1983
        try:
1984
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1985
        except (ValueError, TypeError):
1986
          _ErrorIf(True, self.ENODERPC, node,
1987
                   "node returned invalid LVM info, check LVM status")
1988

    
1989
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1990
    """Gets per-disk status information for all instances.
1991

1992
    @type nodelist: list of strings
1993
    @param nodelist: Node names
1994
    @type node_image: dict of (name, L{objects.Node})
1995
    @param node_image: Node objects
1996
    @type instanceinfo: dict of (name, L{objects.Instance})
1997
    @param instanceinfo: Instance objects
1998

1999
    """
2000
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2001

    
2002
    node_disks = {}
2003
    node_disks_devonly = {}
2004

    
2005
    for nname in nodelist:
2006
      disks = [(inst, disk)
2007
               for instlist in [node_image[nname].pinst,
2008
                                node_image[nname].sinst]
2009
               for inst in instlist
2010
               for disk in instanceinfo[inst].disks]
2011

    
2012
      if not disks:
2013
        # No need to collect data
2014
        continue
2015

    
2016
      node_disks[nname] = disks
2017

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

    
2022
      for dev in devonly:
2023
        self.cfg.SetDiskID(dev, nname)
2024

    
2025
      node_disks_devonly[nname] = devonly
2026

    
2027
    assert len(node_disks) == len(node_disks_devonly)
2028

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

    
2033
    assert len(result) == len(node_disks)
2034

    
2035
    instdisk = {}
2036

    
2037
    for (nname, nres) in result.items():
2038
      if nres.offline:
2039
        # Ignore offline node
2040
        continue
2041

    
2042
      disks = node_disks[nname]
2043

    
2044
      msg = nres.fail_msg
2045
      _ErrorIf(msg, self.ENODERPC, nname,
2046
               "while getting disk information: %s", nres.fail_msg)
2047
      if msg:
2048
        # No data from this node
2049
        data = len(disks) * [None]
2050
      else:
2051
        data = nres.payload
2052

    
2053
      for ((inst, _), status) in zip(disks, data):
2054
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2055

    
2056
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2057
                      len(nnames) <= len(instanceinfo[inst].all_nodes)
2058
                      for inst, nnames in instdisk.items()
2059
                      for nname, statuses in nnames.items())
2060

    
2061
    return instdisk
2062

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

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

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

    
2077
    return env, [], all_nodes
2078

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

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

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

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

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

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

    
2123
    local_checksums = utils.FingerprintFiles(file_names)
2124

    
2125
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2126
    node_verify_param = {
2127
      constants.NV_FILELIST: file_names,
2128
      constants.NV_NODELIST: [node.name for node in nodeinfo
2129
                              if not node.offline],
2130
      constants.NV_HYPERVISOR: hypervisors,
2131
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2132
                                  node.secondary_ip) for node in nodeinfo
2133
                                 if not node.offline],
2134
      constants.NV_INSTANCELIST: hypervisors,
2135
      constants.NV_VERSION: None,
2136
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2137
      constants.NV_NODESETUP: None,
2138
      constants.NV_TIME: None,
2139
      constants.NV_MASTERIP: (master_node, master_ip),
2140
      constants.NV_OSLIST: None,
2141
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2142
      }
2143

    
2144
    if vg_name is not None:
2145
      node_verify_param[constants.NV_VGLIST] = None
2146
      node_verify_param[constants.NV_LVLIST] = vg_name
2147
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2148
      node_verify_param[constants.NV_DRBDLIST] = None
2149

    
2150
    if drbd_helper:
2151
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2152

    
2153
    # Build our expected cluster state
2154
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2155
                                                 name=node.name,
2156
                                                 vm_capable=node.vm_capable))
2157
                      for node in nodeinfo)
2158

    
2159
    for instance in instancelist:
2160
      inst_config = instanceinfo[instance]
2161

    
2162
      for nname in inst_config.all_nodes:
2163
        if nname not in node_image:
2164
          # ghost node
2165
          gnode = self.NodeImage(name=nname)
2166
          gnode.ghost = True
2167
          node_image[nname] = gnode
2168

    
2169
      inst_config.MapLVsByNode(node_vol_should)
2170

    
2171
      pnode = inst_config.primary_node
2172
      node_image[pnode].pinst.append(instance)
2173

    
2174
      for snode in inst_config.secondary_nodes:
2175
        nimg = node_image[snode]
2176
        nimg.sinst.append(instance)
2177
        if pnode not in nimg.sbp:
2178
          nimg.sbp[pnode] = []
2179
        nimg.sbp[pnode].append(instance)
2180

    
2181
    # At this point, we have the in-memory data structures complete,
2182
    # except for the runtime information, which we'll gather next
2183

    
2184
    # Due to the way our RPC system works, exact response times cannot be
2185
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2186
    # time before and after executing the request, we can at least have a time
2187
    # window.
2188
    nvinfo_starttime = time.time()
2189
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2190
                                           self.cfg.GetClusterName())
2191
    nvinfo_endtime = time.time()
2192

    
2193
    all_drbd_map = self.cfg.ComputeDRBDMap()
2194

    
2195
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2196
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2197

    
2198
    feedback_fn("* Verifying node status")
2199

    
2200
    refos_img = None
2201

    
2202
    for node_i in nodeinfo:
2203
      node = node_i.name
2204
      nimg = node_image[node]
2205

    
2206
      if node_i.offline:
2207
        if verbose:
2208
          feedback_fn("* Skipping offline node %s" % (node,))
2209
        n_offline += 1
2210
        continue
2211

    
2212
      if node == master_node:
2213
        ntype = "master"
2214
      elif node_i.master_candidate:
2215
        ntype = "master candidate"
2216
      elif node_i.drained:
2217
        ntype = "drained"
2218
        n_drained += 1
2219
      else:
2220
        ntype = "regular"
2221
      if verbose:
2222
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2223

    
2224
      msg = all_nvinfo[node].fail_msg
2225
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2226
      if msg:
2227
        nimg.rpc_fail = True
2228
        continue
2229

    
2230
      nresult = all_nvinfo[node].payload
2231

    
2232
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2233
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2234
      self._VerifyNodeNetwork(node_i, nresult)
2235
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2236
                            master_files)
2237

    
2238
      if nimg.vm_capable:
2239
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2240
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2241
                             all_drbd_map)
2242

    
2243
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2244
        self._UpdateNodeInstances(node_i, nresult, nimg)
2245
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2246
        self._UpdateNodeOS(node_i, nresult, nimg)
2247
        if not nimg.os_fail:
2248
          if refos_img is None:
2249
            refos_img = nimg
2250
          self._VerifyNodeOS(node_i, nimg, refos_img)
2251

    
2252
    feedback_fn("* Verifying instance status")
2253
    for instance in instancelist:
2254
      if verbose:
2255
        feedback_fn("* Verifying instance %s" % instance)
2256
      inst_config = instanceinfo[instance]
2257
      self._VerifyInstance(instance, inst_config, node_image,
2258
                           instdisk[instance])
2259
      inst_nodes_offline = []
2260

    
2261
      pnode = inst_config.primary_node
2262
      pnode_img = node_image[pnode]
2263
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2264
               self.ENODERPC, pnode, "instance %s, connection to"
2265
               " primary node failed", instance)
2266

    
2267
      if pnode_img.offline:
2268
        inst_nodes_offline.append(pnode)
2269

    
2270
      # If the instance is non-redundant we cannot survive losing its primary
2271
      # node, so we are not N+1 compliant. On the other hand we have no disk
2272
      # templates with more than one secondary so that situation is not well
2273
      # supported either.
2274
      # FIXME: does not support file-backed instances
2275
      if not inst_config.secondary_nodes:
2276
        i_non_redundant.append(instance)
2277
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2278
               instance, "instance has multiple secondary nodes: %s",
2279
               utils.CommaJoin(inst_config.secondary_nodes),
2280
               code=self.ETYPE_WARNING)
2281

    
2282
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2283
        i_non_a_balanced.append(instance)
2284

    
2285
      for snode in inst_config.secondary_nodes:
2286
        s_img = node_image[snode]
2287
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2288
                 "instance %s, connection to secondary node failed", instance)
2289

    
2290
        if s_img.offline:
2291
          inst_nodes_offline.append(snode)
2292

    
2293
      # warn that the instance lives on offline nodes
2294
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2295
               "instance lives on offline node(s) %s",
2296
               utils.CommaJoin(inst_nodes_offline))
2297
      # ... or ghost/non-vm_capable nodes
2298
      for node in inst_config.all_nodes:
2299
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2300
                 "instance lives on ghost node %s", node)
2301
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2302
                 instance, "instance lives on non-vm_capable node %s", node)
2303

    
2304
    feedback_fn("* Verifying orphan volumes")
2305
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2306
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2307

    
2308
    feedback_fn("* Verifying orphan instances")
2309
    self._VerifyOrphanInstances(instancelist, node_image)
2310

    
2311
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2312
      feedback_fn("* Verifying N+1 Memory redundancy")
2313
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2314

    
2315
    feedback_fn("* Other Notes")
2316
    if i_non_redundant:
2317
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2318
                  % len(i_non_redundant))
2319

    
2320
    if i_non_a_balanced:
2321
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2322
                  % len(i_non_a_balanced))
2323

    
2324
    if n_offline:
2325
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2326

    
2327
    if n_drained:
2328
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2329

    
2330
    return not self.bad
2331

    
2332
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2333
    """Analyze the post-hooks' result
2334

2335
    This method analyses the hook result, handles it, and sends some
2336
    nicely-formatted feedback back to the user.
2337

2338
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2339
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2340
    @param hooks_results: the results of the multi-node hooks rpc call
2341
    @param feedback_fn: function used send feedback back to the caller
2342
    @param lu_result: previous Exec result
2343
    @return: the new Exec result, based on the previous result
2344
        and hook results
2345

2346
    """
2347
    # We only really run POST phase hooks, and are only interested in
2348
    # their results
2349
    if phase == constants.HOOKS_PHASE_POST:
2350
      # Used to change hooks' output to proper indentation
2351
      feedback_fn("* Hooks Results")
2352
      assert hooks_results, "invalid result from hooks"
2353

    
2354
      for node_name in hooks_results:
2355
        res = hooks_results[node_name]
2356
        msg = res.fail_msg
2357
        test = msg and not res.offline
2358
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2359
                      "Communication failure in hooks execution: %s", msg)
2360
        if res.offline or msg:
2361
          # No need to investigate payload if node is offline or gave an error.
2362
          # override manually lu_result here as _ErrorIf only
2363
          # overrides self.bad
2364
          lu_result = 1
2365
          continue
2366
        for script, hkr, output in res.payload:
2367
          test = hkr == constants.HKR_FAIL
2368
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2369
                        "Script %s failed, output:", script)
2370
          if test:
2371
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2372
            feedback_fn("%s" % output)
2373
            lu_result = 0
2374

    
2375
      return lu_result
2376

    
2377

    
2378
class LUVerifyDisks(NoHooksLU):
2379
  """Verifies the cluster disks status.
2380

2381
  """
2382
  REQ_BGL = False
2383

    
2384
  def ExpandNames(self):
2385
    self.needed_locks = {
2386
      locking.LEVEL_NODE: locking.ALL_SET,
2387
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2388
    }
2389
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2390

    
2391
  def Exec(self, feedback_fn):
2392
    """Verify integrity of cluster disks.
2393

2394
    @rtype: tuple of three items
2395
    @return: a tuple of (dict of node-to-node_error, list of instances
2396
        which need activate-disks, dict of instance: (node, volume) for
2397
        missing volumes
2398

2399
    """
2400
    result = res_nodes, res_instances, res_missing = {}, [], {}
2401

    
2402
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2403
    instances = [self.cfg.GetInstanceInfo(name)
2404
                 for name in self.cfg.GetInstanceList()]
2405

    
2406
    nv_dict = {}
2407
    for inst in instances:
2408
      inst_lvs = {}
2409
      if (not inst.admin_up or
2410
          inst.disk_template not in constants.DTS_NET_MIRROR):
2411
        continue
2412
      inst.MapLVsByNode(inst_lvs)
2413
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2414
      for node, vol_list in inst_lvs.iteritems():
2415
        for vol in vol_list:
2416
          nv_dict[(node, vol)] = inst
2417

    
2418
    if not nv_dict:
2419
      return result
2420

    
2421
    vg_names = self.rpc.call_vg_list(nodes)
2422
    vg_names.Raise("Cannot get list of VGs")
2423

    
2424
    for node in nodes:
2425
      # node_volume
2426
      node_res = self.rpc.call_lv_list([node],
2427
                                       vg_names[node].payload.keys())[node]
2428
      if node_res.offline:
2429
        continue
2430
      msg = node_res.fail_msg
2431
      if msg:
2432
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2433
        res_nodes[node] = msg
2434
        continue
2435

    
2436
      lvs = node_res.payload
2437
      for lv_name, (_, _, lv_online) in lvs.items():
2438
        inst = nv_dict.pop((node, lv_name), None)
2439
        if (not lv_online and inst is not None
2440
            and inst.name not in res_instances):
2441
          res_instances.append(inst.name)
2442

    
2443
    # any leftover items in nv_dict are missing LVs, let's arrange the
2444
    # data better
2445
    for key, inst in nv_dict.iteritems():
2446
      if inst.name not in res_missing:
2447
        res_missing[inst.name] = []
2448
      res_missing[inst.name].append(key)
2449

    
2450
    return result
2451

    
2452

    
2453
class LURepairDiskSizes(NoHooksLU):
2454
  """Verifies the cluster disks sizes.
2455

2456
  """
2457
  _OP_PARAMS = [("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString))]
2458
  REQ_BGL = False
2459

    
2460
  def ExpandNames(self):
2461
    if self.op.instances:
2462
      self.wanted_names = []
2463
      for name in self.op.instances:
2464
        full_name = _ExpandInstanceName(self.cfg, name)
2465
        self.wanted_names.append(full_name)
2466
      self.needed_locks = {
2467
        locking.LEVEL_NODE: [],
2468
        locking.LEVEL_INSTANCE: self.wanted_names,
2469
        }
2470
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2471
    else:
2472
      self.wanted_names = None
2473
      self.needed_locks = {
2474
        locking.LEVEL_NODE: locking.ALL_SET,
2475
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2476
        }
2477
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2478

    
2479
  def DeclareLocks(self, level):
2480
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2481
      self._LockInstancesNodes(primary_only=True)
2482

    
2483
  def CheckPrereq(self):
2484
    """Check prerequisites.
2485

2486
    This only checks the optional instance list against the existing names.
2487

2488
    """
2489
    if self.wanted_names is None:
2490
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2491

    
2492
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2493
                             in self.wanted_names]
2494

    
2495
  def _EnsureChildSizes(self, disk):
2496
    """Ensure children of the disk have the needed disk size.
2497

2498
    This is valid mainly for DRBD8 and fixes an issue where the
2499
    children have smaller disk size.
2500

2501
    @param disk: an L{ganeti.objects.Disk} object
2502

2503
    """
2504
    if disk.dev_type == constants.LD_DRBD8:
2505
      assert disk.children, "Empty children for DRBD8?"
2506
      fchild = disk.children[0]
2507
      mismatch = fchild.size < disk.size
2508
      if mismatch:
2509
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2510
                     fchild.size, disk.size)
2511
        fchild.size = disk.size
2512

    
2513
      # and we recurse on this child only, not on the metadev
2514
      return self._EnsureChildSizes(fchild) or mismatch
2515
    else:
2516
      return False
2517

    
2518
  def Exec(self, feedback_fn):
2519
    """Verify the size of cluster disks.
2520

2521
    """
2522
    # TODO: check child disks too
2523
    # TODO: check differences in size between primary/secondary nodes
2524
    per_node_disks = {}
2525
    for instance in self.wanted_instances:
2526
      pnode = instance.primary_node
2527
      if pnode not in per_node_disks:
2528
        per_node_disks[pnode] = []
2529
      for idx, disk in enumerate(instance.disks):
2530
        per_node_disks[pnode].append((instance, idx, disk))
2531

    
2532
    changed = []
2533
    for node, dskl in per_node_disks.items():
2534
      newl = [v[2].Copy() for v in dskl]
2535
      for dsk in newl:
2536
        self.cfg.SetDiskID(dsk, node)
2537
      result = self.rpc.call_blockdev_getsizes(node, newl)
2538
      if result.fail_msg:
2539
        self.LogWarning("Failure in blockdev_getsizes call to node"
2540
                        " %s, ignoring", node)
2541
        continue
2542
      if len(result.data) != len(dskl):
2543
        self.LogWarning("Invalid result from node %s, ignoring node results",
2544
                        node)
2545
        continue
2546
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2547
        if size is None:
2548
          self.LogWarning("Disk %d of instance %s did not return size"
2549
                          " information, ignoring", idx, instance.name)
2550
          continue
2551
        if not isinstance(size, (int, long)):
2552
          self.LogWarning("Disk %d of instance %s did not return valid"
2553
                          " size information, ignoring", idx, instance.name)
2554
          continue
2555
        size = size >> 20
2556
        if size != disk.size:
2557
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2558
                       " correcting: recorded %d, actual %d", idx,
2559
                       instance.name, disk.size, size)
2560
          disk.size = size
2561
          self.cfg.Update(instance, feedback_fn)
2562
          changed.append((instance.name, idx, size))
2563
        if self._EnsureChildSizes(disk):
2564
          self.cfg.Update(instance, feedback_fn)
2565
          changed.append((instance.name, idx, disk.size))
2566
    return changed
2567

    
2568

    
2569
class LURenameCluster(LogicalUnit):
2570
  """Rename the cluster.
2571

2572
  """
2573
  HPATH = "cluster-rename"
2574
  HTYPE = constants.HTYPE_CLUSTER
2575
  _OP_PARAMS = [("name", ht.NoDefault, ht.TNonEmptyString)]
2576

    
2577
  def BuildHooksEnv(self):
2578
    """Build hooks env.
2579

2580
    """
2581
    env = {
2582
      "OP_TARGET": self.cfg.GetClusterName(),
2583
      "NEW_NAME": self.op.name,
2584
      }
2585
    mn = self.cfg.GetMasterNode()
2586
    all_nodes = self.cfg.GetNodeList()
2587
    return env, [mn], all_nodes
2588

    
2589
  def CheckPrereq(self):
2590
    """Verify that the passed name is a valid one.
2591

2592
    """
2593
    hostname = netutils.GetHostname(name=self.op.name,
2594
                                    family=self.cfg.GetPrimaryIPFamily())
2595

    
2596
    new_name = hostname.name
2597
    self.ip = new_ip = hostname.ip
2598
    old_name = self.cfg.GetClusterName()
2599
    old_ip = self.cfg.GetMasterIP()
2600
    if new_name == old_name and new_ip == old_ip:
2601
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2602
                                 " cluster has changed",
2603
                                 errors.ECODE_INVAL)
2604
    if new_ip != old_ip:
2605
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2606
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2607
                                   " reachable on the network" %
2608
                                   new_ip, errors.ECODE_NOTUNIQUE)
2609

    
2610
    self.op.name = new_name
2611

    
2612
  def Exec(self, feedback_fn):
2613
    """Rename the cluster.
2614

2615
    """
2616
    clustername = self.op.name
2617
    ip = self.ip
2618

    
2619
    # shutdown the master IP
2620
    master = self.cfg.GetMasterNode()
2621
    result = self.rpc.call_node_stop_master(master, False)
2622
    result.Raise("Could not disable the master role")
2623

    
2624
    try:
2625
      cluster = self.cfg.GetClusterInfo()
2626
      cluster.cluster_name = clustername
2627
      cluster.master_ip = ip
2628
      self.cfg.Update(cluster, feedback_fn)
2629

    
2630
      # update the known hosts file
2631
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2632
      node_list = self.cfg.GetOnlineNodeList()
2633
      try:
2634
        node_list.remove(master)
2635
      except ValueError:
2636
        pass
2637
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2638
    finally:
2639
      result = self.rpc.call_node_start_master(master, False, False)
2640
      msg = result.fail_msg
2641
      if msg:
2642
        self.LogWarning("Could not re-enable the master role on"
2643
                        " the master, please restart manually: %s", msg)
2644

    
2645
    return clustername
2646

    
2647

    
2648
class LUSetClusterParams(LogicalUnit):
2649
  """Change the parameters of the cluster.
2650

2651
  """
2652
  HPATH = "cluster-modify"
2653
  HTYPE = constants.HTYPE_CLUSTER
2654
  _OP_PARAMS = [
2655
    ("vg_name", None, ht.TMaybeString),
2656
    ("enabled_hypervisors", None,
2657
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
2658
            ht.TNone)),
2659
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2660
                              ht.TNone)),
2661
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone)),
2662
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2663
                            ht.TNone)),
2664
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2665
                              ht.TNone)),
2666
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
2667
    ("uid_pool", None, ht.NoType),
2668
    ("add_uids", None, ht.NoType),
2669
    ("remove_uids", None, ht.NoType),
2670
    ("maintain_node_health", None, ht.TMaybeBool),
2671
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
2672
    ("nicparams", None, ht.TOr(ht.TDict, ht.TNone)),
2673
    ("ndparams", None, ht.TOr(ht.TDict, ht.TNone)),
2674
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
2675
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
2676
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
2677
    ("hidden_os", None, ht.TOr(ht.TListOf(\
2678
          ht.TAnd(ht.TList,
2679
                ht.TIsLength(2),
2680
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2681
          ht.TNone)),
2682
    ("blacklisted_os", None, ht.TOr(ht.TListOf(\
2683
          ht.TAnd(ht.TList,
2684
                ht.TIsLength(2),
2685
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2686
          ht.TNone)),
2687
    ]
2688
  REQ_BGL = False
2689

    
2690
  def CheckArguments(self):
2691
    """Check parameters
2692

2693
    """
2694
    if self.op.uid_pool:
2695
      uidpool.CheckUidPool(self.op.uid_pool)
2696

    
2697
    if self.op.add_uids:
2698
      uidpool.CheckUidPool(self.op.add_uids)
2699

    
2700
    if self.op.remove_uids:
2701
      uidpool.CheckUidPool(self.op.remove_uids)
2702

    
2703
  def ExpandNames(self):
2704
    # FIXME: in the future maybe other cluster params won't require checking on
2705
    # all nodes to be modified.
2706
    self.needed_locks = {
2707
      locking.LEVEL_NODE: locking.ALL_SET,
2708
    }
2709
    self.share_locks[locking.LEVEL_NODE] = 1
2710

    
2711
  def BuildHooksEnv(self):
2712
    """Build hooks env.
2713

2714
    """
2715
    env = {
2716
      "OP_TARGET": self.cfg.GetClusterName(),
2717
      "NEW_VG_NAME": self.op.vg_name,
2718
      }
2719
    mn = self.cfg.GetMasterNode()
2720
    return env, [mn], [mn]
2721

    
2722
  def CheckPrereq(self):
2723
    """Check prerequisites.
2724

2725
    This checks whether the given params don't conflict and
2726
    if the given volume group is valid.
2727

2728
    """
2729
    if self.op.vg_name is not None and not self.op.vg_name:
2730
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2731
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2732
                                   " instances exist", errors.ECODE_INVAL)
2733

    
2734
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2735
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2736
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2737
                                   " drbd-based instances exist",
2738
                                   errors.ECODE_INVAL)
2739

    
2740
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2741

    
2742
    # if vg_name not None, checks given volume group on all nodes
2743
    if self.op.vg_name:
2744
      vglist = self.rpc.call_vg_list(node_list)
2745
      for node in node_list:
2746
        msg = vglist[node].fail_msg
2747
        if msg:
2748
          # ignoring down node
2749
          self.LogWarning("Error while gathering data on node %s"
2750
                          " (ignoring node): %s", node, msg)
2751
          continue
2752
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2753
                                              self.op.vg_name,
2754
                                              constants.MIN_VG_SIZE)
2755
        if vgstatus:
2756
          raise errors.OpPrereqError("Error on node '%s': %s" %
2757
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2758

    
2759
    if self.op.drbd_helper:
2760
      # checks given drbd helper on all nodes
2761
      helpers = self.rpc.call_drbd_helper(node_list)
2762
      for node in node_list:
2763
        ninfo = self.cfg.GetNodeInfo(node)
2764
        if ninfo.offline:
2765
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2766
          continue
2767
        msg = helpers[node].fail_msg
2768
        if msg:
2769
          raise errors.OpPrereqError("Error checking drbd helper on node"
2770
                                     " '%s': %s" % (node, msg),
2771
                                     errors.ECODE_ENVIRON)
2772
        node_helper = helpers[node].payload
2773
        if node_helper != self.op.drbd_helper:
2774
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2775
                                     (node, node_helper), errors.ECODE_ENVIRON)
2776

    
2777
    self.cluster = cluster = self.cfg.GetClusterInfo()
2778
    # validate params changes
2779
    if self.op.beparams:
2780
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2781
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2782

    
2783
    if self.op.ndparams:
2784
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2785
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2786

    
2787
    if self.op.nicparams:
2788
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2789
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2790
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2791
      nic_errors = []
2792

    
2793
      # check all instances for consistency
2794
      for instance in self.cfg.GetAllInstancesInfo().values():
2795
        for nic_idx, nic in enumerate(instance.nics):
2796
          params_copy = copy.deepcopy(nic.nicparams)
2797
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2798

    
2799
          # check parameter syntax
2800
          try:
2801
            objects.NIC.CheckParameterSyntax(params_filled)
2802
          except errors.ConfigurationError, err:
2803
            nic_errors.append("Instance %s, nic/%d: %s" %
2804
                              (instance.name, nic_idx, err))
2805

    
2806
          # if we're moving instances to routed, check that they have an ip
2807
          target_mode = params_filled[constants.NIC_MODE]
2808
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2809
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2810
                              (instance.name, nic_idx))
2811
      if nic_errors:
2812
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2813
                                   "\n".join(nic_errors))
2814

    
2815
    # hypervisor list/parameters
2816
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2817
    if self.op.hvparams:
2818
      for hv_name, hv_dict in self.op.hvparams.items():
2819
        if hv_name not in self.new_hvparams:
2820
          self.new_hvparams[hv_name] = hv_dict
2821
        else:
2822
          self.new_hvparams[hv_name].update(hv_dict)
2823

    
2824
    # os hypervisor parameters
2825
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2826
    if self.op.os_hvp:
2827
      for os_name, hvs in self.op.os_hvp.items():
2828
        if os_name not in self.new_os_hvp:
2829
          self.new_os_hvp[os_name] = hvs
2830
        else:
2831
          for hv_name, hv_dict in hvs.items():
2832
            if hv_name not in self.new_os_hvp[os_name]:
2833
              self.new_os_hvp[os_name][hv_name] = hv_dict
2834
            else:
2835
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2836

    
2837
    # os parameters
2838
    self.new_osp = objects.FillDict(cluster.osparams, {})
2839
    if self.op.osparams:
2840
      for os_name, osp in self.op.osparams.items():
2841
        if os_name not in self.new_osp:
2842
          self.new_osp[os_name] = {}
2843

    
2844
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2845
                                                  use_none=True)
2846

    
2847
        if not self.new_osp[os_name]:
2848
          # we removed all parameters
2849
          del self.new_osp[os_name]
2850
        else:
2851
          # check the parameter validity (remote check)
2852
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2853
                         os_name, self.new_osp[os_name])
2854

    
2855
    # changes to the hypervisor list
2856
    if self.op.enabled_hypervisors is not None:
2857
      self.hv_list = self.op.enabled_hypervisors
2858
      for hv in self.hv_list:
2859
        # if the hypervisor doesn't already exist in the cluster
2860
        # hvparams, we initialize it to empty, and then (in both
2861
        # cases) we make sure to fill the defaults, as we might not
2862
        # have a complete defaults list if the hypervisor wasn't
2863
        # enabled before
2864
        if hv not in new_hvp:
2865
          new_hvp[hv] = {}
2866
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2867
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2868
    else:
2869
      self.hv_list = cluster.enabled_hypervisors
2870

    
2871
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2872
      # either the enabled list has changed, or the parameters have, validate
2873
      for hv_name, hv_params in self.new_hvparams.items():
2874
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2875
            (self.op.enabled_hypervisors and
2876
             hv_name in self.op.enabled_hypervisors)):
2877
          # either this is a new hypervisor, or its parameters have changed
2878
          hv_class = hypervisor.GetHypervisor(hv_name)
2879
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2880
          hv_class.CheckParameterSyntax(hv_params)
2881
          _CheckHVParams(self, node_list, hv_name, hv_params)
2882

    
2883
    if self.op.os_hvp:
2884
      # no need to check any newly-enabled hypervisors, since the
2885
      # defaults have already been checked in the above code-block
2886
      for os_name, os_hvp in self.new_os_hvp.items():
2887
        for hv_name, hv_params in os_hvp.items():
2888
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2889
          # we need to fill in the new os_hvp on top of the actual hv_p
2890
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2891
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2892
          hv_class = hypervisor.GetHypervisor(hv_name)
2893
          hv_class.CheckParameterSyntax(new_osp)
2894
          _CheckHVParams(self, node_list, hv_name, new_osp)
2895

    
2896
    if self.op.default_iallocator:
2897
      alloc_script = utils.FindFile(self.op.default_iallocator,
2898
                                    constants.IALLOCATOR_SEARCH_PATH,
2899
                                    os.path.isfile)
2900
      if alloc_script is None:
2901
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2902
                                   " specified" % self.op.default_iallocator,
2903
                                   errors.ECODE_INVAL)
2904

    
2905
  def Exec(self, feedback_fn):
2906
    """Change the parameters of the cluster.
2907

2908
    """
2909
    if self.op.vg_name is not None:
2910
      new_volume = self.op.vg_name
2911
      if not new_volume:
2912
        new_volume = None
2913
      if new_volume != self.cfg.GetVGName():
2914
        self.cfg.SetVGName(new_volume)
2915
      else:
2916
        feedback_fn("Cluster LVM configuration already in desired"
2917
                    " state, not changing")
2918
    if self.op.drbd_helper is not None:
2919
      new_helper = self.op.drbd_helper
2920
      if not new_helper:
2921
        new_helper = None
2922
      if new_helper != self.cfg.GetDRBDHelper():
2923
        self.cfg.SetDRBDHelper(new_helper)
2924
      else:
2925
        feedback_fn("Cluster DRBD helper already in desired state,"
2926
                    " not changing")
2927
    if self.op.hvparams:
2928
      self.cluster.hvparams = self.new_hvparams
2929
    if self.op.os_hvp:
2930
      self.cluster.os_hvp = self.new_os_hvp
2931
    if self.op.enabled_hypervisors is not None:
2932
      self.cluster.hvparams = self.new_hvparams
2933
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2934
    if self.op.beparams:
2935
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2936
    if self.op.nicparams:
2937
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2938
    if self.op.osparams:
2939
      self.cluster.osparams = self.new_osp
2940
    if self.op.ndparams:
2941
      self.cluster.ndparams = self.new_ndparams
2942

    
2943
    if self.op.candidate_pool_size is not None:
2944
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2945
      # we need to update the pool size here, otherwise the save will fail
2946
      _AdjustCandidatePool(self, [])
2947

    
2948
    if self.op.maintain_node_health is not None:
2949
      self.cluster.maintain_node_health = self.op.maintain_node_health
2950

    
2951
    if self.op.prealloc_wipe_disks is not None:
2952
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2953

    
2954
    if self.op.add_uids is not None:
2955
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2956

    
2957
    if self.op.remove_uids is not None:
2958
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2959

    
2960
    if self.op.uid_pool is not None:
2961
      self.cluster.uid_pool = self.op.uid_pool
2962

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

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

    
2969
    def helper_os(aname, mods, desc):
2970
      desc += " OS list"
2971
      lst = getattr(self.cluster, aname)
2972
      for key, val in mods:
2973
        if key == constants.DDM_ADD:
2974
          if val in lst:
2975
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2976
          else:
2977
            lst.append(val)
2978
        elif key == constants.DDM_REMOVE:
2979
          if val in lst:
2980
            lst.remove(val)
2981
          else:
2982
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
2983
        else:
2984
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2985

    
2986
    if self.op.hidden_os:
2987
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2988

    
2989
    if self.op.blacklisted_os:
2990
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2991

    
2992
    self.cfg.Update(self.cluster, feedback_fn)
2993

    
2994

    
2995
def _UploadHelper(lu, nodes, fname):
2996
  """Helper for uploading a file and showing warnings.
2997

2998
  """
2999
  if os.path.exists(fname):
3000
    result = lu.rpc.call_upload_file(nodes, fname)
3001
    for to_node, to_result in result.items():
3002
      msg = to_result.fail_msg
3003
      if msg:
3004
        msg = ("Copy of file %s to node %s failed: %s" %
3005
               (fname, to_node, msg))
3006
        lu.proc.LogWarning(msg)
3007

    
3008

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

3012
  ConfigWriter takes care of distributing the config and ssconf files, but
3013
  there are more files which should be distributed to all nodes. This function
3014
  makes sure those are copied.
3015

3016
  @param lu: calling logical unit
3017
  @param additional_nodes: list of nodes not in the config to distribute to
3018
  @type additional_vm: boolean
3019
  @param additional_vm: whether the additional nodes are vm-capable or not
3020

3021
  """
3022
  # 1. Gather target nodes
3023
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3024
  dist_nodes = lu.cfg.GetOnlineNodeList()
3025
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
3026
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
3027
  if additional_nodes is not None:
3028
    dist_nodes.extend(additional_nodes)
3029
    if additional_vm:
3030
      vm_nodes.extend(additional_nodes)
3031
  if myself.name in dist_nodes:
3032
    dist_nodes.remove(myself.name)
3033
  if myself.name in vm_nodes:
3034
    vm_nodes.remove(myself.name)
3035

    
3036
  # 2. Gather files to distribute
3037
  dist_files = set([constants.ETC_HOSTS,
3038
                    constants.SSH_KNOWN_HOSTS_FILE,
3039
                    constants.RAPI_CERT_FILE,
3040
                    constants.RAPI_USERS_FILE,
3041
                    constants.CONFD_HMAC_KEY,
3042
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3043
                   ])
3044

    
3045
  vm_files = set()
3046
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3047
  for hv_name in enabled_hypervisors:
3048
    hv_class = hypervisor.GetHypervisor(hv_name)
3049
    vm_files.update(hv_class.GetAncillaryFiles())
3050

    
3051
  # 3. Perform the files upload
3052
  for fname in dist_files:
3053
    _UploadHelper(lu, dist_nodes, fname)
3054
  for fname in vm_files:
3055
    _UploadHelper(lu, vm_nodes, fname)
3056

    
3057

    
3058
class LURedistributeConfig(NoHooksLU):
3059
  """Force the redistribution of cluster configuration.
3060

3061
  This is a very simple LU.
3062

3063
  """
3064
  REQ_BGL = False
3065

    
3066
  def ExpandNames(self):
3067
    self.needed_locks = {
3068
      locking.LEVEL_NODE: locking.ALL_SET,
3069
    }
3070
    self.share_locks[locking.LEVEL_NODE] = 1
3071

    
3072
  def Exec(self, feedback_fn):
3073
    """Redistribute the configuration.
3074

3075
    """
3076
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3077
    _RedistributeAncillaryFiles(self)
3078

    
3079

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

3083
  """
3084
  if not instance.disks or disks is not None and not disks:
3085
    return True
3086

    
3087
  disks = _ExpandCheckDisks(instance, disks)
3088

    
3089
  if not oneshot:
3090
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3091

    
3092
  node = instance.primary_node
3093

    
3094
  for dev in disks:
3095
    lu.cfg.SetDiskID(dev, node)
3096

    
3097
  # TODO: Convert to utils.Retry
3098

    
3099
  retries = 0
3100
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3101
  while True:
3102
    max_time = 0
3103
    done = True
3104
    cumul_degraded = False
3105
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3106
    msg = rstats.fail_msg
3107
    if msg:
3108
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3109
      retries += 1
3110
      if retries >= 10:
3111
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3112
                                 " aborting." % node)
3113
      time.sleep(6)
3114
      continue
3115
    rstats = rstats.payload
3116
    retries = 0
3117
    for i, mstat in enumerate(rstats):
3118
      if mstat is None:
3119
        lu.LogWarning("Can't compute data for node %s/%s",
3120
                           node, disks[i].iv_name)
3121
        continue
3122

    
3123
      cumul_degraded = (cumul_degraded or
3124
                        (mstat.is_degraded and mstat.sync_percent is None))
3125
      if mstat.sync_percent is not None:
3126
        done = False
3127
        if mstat.estimated_time is not None:
3128
          rem_time = ("%s remaining (estimated)" %
3129
                      utils.FormatSeconds(mstat.estimated_time))
3130
          max_time = mstat.estimated_time
3131
        else:
3132
          rem_time = "no time estimate"
3133
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3134
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3135

    
3136
    # if we're done but degraded, let's do a few small retries, to
3137
    # make sure we see a stable and not transient situation; therefore
3138
    # we force restart of the loop
3139
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3140
      logging.info("Degraded disks found, %d retries left", degr_retries)
3141
      degr_retries -= 1
3142
      time.sleep(1)
3143
      continue
3144

    
3145
    if done or oneshot:
3146
      break
3147

    
3148
    time.sleep(min(60, max_time))
3149

    
3150
  if done:
3151
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3152
  return not cumul_degraded
3153

    
3154

    
3155
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3156
  """Check that mirrors are not degraded.
3157

3158
  The ldisk parameter, if True, will change the test from the
3159
  is_degraded attribute (which represents overall non-ok status for
3160
  the device(s)) to the ldisk (representing the local storage status).
3161

3162
  """
3163
  lu.cfg.SetDiskID(dev, node)
3164

    
3165
  result = True
3166

    
3167
  if on_primary or dev.AssembleOnSecondary():
3168
    rstats = lu.rpc.call_blockdev_find(node, dev)
3169
    msg = rstats.fail_msg
3170
    if msg:
3171
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3172
      result = False
3173
    elif not rstats.payload:
3174
      lu.LogWarning("Can't find disk on node %s", node)
3175
      result = False
3176
    else:
3177
      if ldisk:
3178
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3179
      else:
3180
        result = result and not rstats.payload.is_degraded
3181

    
3182
  if dev.children:
3183
    for child in dev.children:
3184
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3185

    
3186
  return result
3187

    
3188

    
3189
class LUDiagnoseOS(NoHooksLU):
3190
  """Logical unit for OS diagnose/query.
3191

3192
  """
3193
  _OP_PARAMS = [
3194
    _POutputFields,
3195
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3196
    ]
3197
  REQ_BGL = False
3198
  _HID = "hidden"
3199
  _BLK = "blacklisted"
3200
  _VLD = "valid"
3201
  _FIELDS_STATIC = utils.FieldSet()
3202
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3203
                                   "parameters", "api_versions", _HID, _BLK)
3204

    
3205
  def CheckArguments(self):
3206
    if self.op.names:
3207
      raise errors.OpPrereqError("Selective OS query not supported",
3208
                                 errors.ECODE_INVAL)
3209

    
3210
    _CheckOutputFields(static=self._FIELDS_STATIC,
3211
                       dynamic=self._FIELDS_DYNAMIC,
3212
                       selected=self.op.output_fields)
3213

    
3214
  def ExpandNames(self):
3215
    # Lock all nodes, in shared mode
3216
    # Temporary removal of locks, should be reverted later
3217
    # TODO: reintroduce locks when they are lighter-weight
3218
    self.needed_locks = {}
3219
    #self.share_locks[locking.LEVEL_NODE] = 1
3220
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3221

    
3222
  @staticmethod
3223
  def _DiagnoseByOS(rlist):
3224
    """Remaps a per-node return list into an a per-os per-node dictionary
3225

3226
    @param rlist: a map with node names as keys and OS objects as values
3227

3228
    @rtype: dict
3229
    @return: a dictionary with osnames as keys and as value another
3230
        map, with nodes as keys and tuples of (path, status, diagnose,
3231
        variants, parameters, api_versions) as values, eg::
3232

3233
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3234
                                     (/srv/..., False, "invalid api")],
3235
                           "node2": [(/srv/..., True, "", [], [])]}
3236
          }
3237

3238
    """
3239
    all_os = {}
3240
    # we build here the list of nodes that didn't fail the RPC (at RPC
3241
    # level), so that nodes with a non-responding node daemon don't
3242
    # make all OSes invalid
3243
    good_nodes = [node_name for node_name in rlist
3244
                  if not rlist[node_name].fail_msg]
3245
    for node_name, nr in rlist.items():
3246
      if nr.fail_msg or not nr.payload:
3247
        continue
3248
      for (name, path, status, diagnose, variants,
3249
           params, api_versions) in nr.payload:
3250
        if name not in all_os:
3251
          # build a list of nodes for this os containing empty lists
3252
          # for each node in node_list
3253
          all_os[name] = {}
3254
          for nname in good_nodes:
3255
            all_os[name][nname] = []
3256
        # convert params from [name, help] to (name, help)
3257
        params = [tuple(v) for v in params]
3258
        all_os[name][node_name].append((path, status, diagnose,
3259
                                        variants, params, api_versions))
3260
    return all_os
3261

    
3262
  def Exec(self, feedback_fn):
3263
    """Compute the list of OSes.
3264

3265
    """
3266
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3267
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3268
    pol = self._DiagnoseByOS(node_data)
3269
    output = []
3270
    cluster = self.cfg.GetClusterInfo()
3271

    
3272
    for os_name in utils.NiceSort(pol.keys()):
3273
      os_data = pol[os_name]
3274
      row = []
3275
      valid = True
3276
      (variants, params, api_versions) = null_state = (set(), set(), set())
3277
      for idx, osl in enumerate(os_data.values()):
3278
        valid = bool(valid and osl and osl[0][1])
3279
        if not valid:
3280
          (variants, params, api_versions) = null_state
3281
          break
3282
        node_variants, node_params, node_api = osl[0][3:6]
3283
        if idx == 0: # first entry
3284
          variants = set(node_variants)
3285
          params = set(node_params)
3286
          api_versions = set(node_api)
3287
        else: # keep consistency
3288
          variants.intersection_update(node_variants)
3289
          params.intersection_update(node_params)
3290
          api_versions.intersection_update(node_api)
3291

    
3292
      is_hid = os_name in cluster.hidden_os
3293
      is_blk = os_name in cluster.blacklisted_os
3294
      if ((self._HID not in self.op.output_fields and is_hid) or
3295
          (self._BLK not in self.op.output_fields and is_blk) or
3296
          (self._VLD not in self.op.output_fields and not valid)):
3297
        continue
3298

    
3299
      for field in self.op.output_fields:
3300
        if field == "name":
3301
          val = os_name
3302
        elif field == self._VLD:
3303
          val = valid
3304
        elif field == "node_status":
3305
          # this is just a copy of the dict
3306
          val = {}
3307
          for node_name, nos_list in os_data.items():
3308
            val[node_name] = nos_list
3309
        elif field == "variants":
3310
          val = utils.NiceSort(list(variants))
3311
        elif field == "parameters":
3312
          val = list(params)
3313
        elif field == "api_versions":
3314
          val = list(api_versions)
3315
        elif field == self._HID:
3316
          val = is_hid
3317
        elif field == self._BLK:
3318
          val = is_blk
3319
        else:
3320
          raise errors.ParameterError(field)
3321
        row.append(val)
3322
      output.append(row)
3323

    
3324
    return output
3325

    
3326

    
3327
class LURemoveNode(LogicalUnit):
3328
  """Logical unit for removing a node.
3329

3330
  """
3331
  HPATH = "node-remove"
3332
  HTYPE = constants.HTYPE_NODE
3333
  _OP_PARAMS = [
3334
    _PNodeName,
3335
    ]
3336

    
3337
  def BuildHooksEnv(self):
3338
    """Build hooks env.
3339

3340
    This doesn't run on the target node in the pre phase as a failed
3341
    node would then be impossible to remove.
3342

3343
    """
3344
    env = {
3345
      "OP_TARGET": self.op.node_name,
3346
      "NODE_NAME": self.op.node_name,
3347
      }
3348
    all_nodes = self.cfg.GetNodeList()
3349
    try:
3350
      all_nodes.remove(self.op.node_name)
3351
    except ValueError:
3352
      logging.warning("Node %s which is about to be removed not found"
3353
                      " in the all nodes list", self.op.node_name)
3354
    return env, all_nodes, all_nodes
3355

    
3356
  def CheckPrereq(self):
3357
    """Check prerequisites.
3358

3359
    This checks:
3360
     - the node exists in the configuration
3361
     - it does not have primary or secondary instances
3362
     - it's not the master
3363

3364
    Any errors are signaled by raising errors.OpPrereqError.
3365

3366
    """
3367
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3368
    node = self.cfg.GetNodeInfo(self.op.node_name)
3369
    assert node is not None
3370

    
3371
    instance_list = self.cfg.GetInstanceList()
3372

    
3373
    masternode = self.cfg.GetMasterNode()
3374
    if node.name == masternode:
3375
      raise errors.OpPrereqError("Node is the master node,"
3376
                                 " you need to failover first.",
3377
                                 errors.ECODE_INVAL)
3378

    
3379
    for instance_name in instance_list:
3380
      instance = self.cfg.GetInstanceInfo(instance_name)
3381
      if node.name in instance.all_nodes:
3382
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3383
                                   " please remove first." % instance_name,
3384
                                   errors.ECODE_INVAL)
3385
    self.op.node_name = node.name
3386
    self.node = node
3387

    
3388
  def Exec(self, feedback_fn):
3389
    """Removes the node from the cluster.
3390

3391
    """
3392
    node = self.node
3393
    logging.info("Stopping the node daemon and removing configs from node %s",
3394
                 node.name)
3395

    
3396
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3397

    
3398
    # Promote nodes to master candidate as needed
3399
    _AdjustCandidatePool(self, exceptions=[node.name])
3400
    self.context.RemoveNode(node.name)
3401

    
3402
    # Run post hooks on the node before it's removed
3403
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3404
    try:
3405
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3406
    except:
3407
      # pylint: disable-msg=W0702
3408
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3409

    
3410
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3411
    msg = result.fail_msg
3412
    if msg:
3413
      self.LogWarning("Errors encountered on the remote node while leaving"
3414
                      " the cluster: %s", msg)
3415

    
3416
    # Remove node from our /etc/hosts
3417
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3418
      master_node = self.cfg.GetMasterNode()
3419
      result = self.rpc.call_etc_hosts_modify(master_node,
3420
                                              constants.ETC_HOSTS_REMOVE,
3421
                                              node.name, None)
3422
      result.Raise("Can't update hosts file with new host data")
3423
      _RedistributeAncillaryFiles(self)
3424

    
3425

    
3426
class _NodeQuery(_QueryBase):
3427
  FIELDS = query.NODE_FIELDS
3428

    
3429
  def ExpandNames(self, lu):
3430
    lu.needed_locks = {}
3431
    lu.share_locks[locking.LEVEL_NODE] = 1
3432

    
3433
    if self.names:
3434
      self.wanted = _GetWantedNodes(lu, self.names)
3435
    else:
3436
      self.wanted = locking.ALL_SET
3437

    
3438
    self.do_locking = (self.use_locking and
3439
                       query.NQ_LIVE in self.requested_data)
3440

    
3441
    if self.do_locking:
3442
      # if we don't request only static fields, we need to lock the nodes
3443
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3444

    
3445
  def DeclareLocks(self, _):
3446
    pass
3447

    
3448
  def _GetQueryData(self, lu):
3449
    """Computes the list of nodes and their attributes.
3450

3451
    """
3452
    all_info = lu.cfg.GetAllNodesInfo()
3453

    
3454
    if self.do_locking:
3455
      nodenames = lu.acquired_locks[locking.LEVEL_NODE]
3456
    elif self.wanted != locking.ALL_SET:
3457
      nodenames = self.wanted
3458
      missing = set(nodenames).difference(all_info.keys())
3459
      if missing:
3460
        raise errors.OpExecError("Some nodes were removed before retrieving"
3461
                                 " their data: %s" % missing)
3462
    else:
3463
      nodenames = all_info.keys()
3464

    
3465
    nodenames = utils.NiceSort(nodenames)
3466

    
3467
    # Gather data as requested
3468
    if query.NQ_LIVE in self.requested_data:
3469
      node_data = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
3470
                                        lu.cfg.GetHypervisorType())
3471
      live_data = dict((name, nresult.payload)
3472
                       for (name, nresult) in node_data.items()
3473
                       if not nresult.fail_msg and nresult.payload)
3474
    else:
3475
      live_data = None
3476

    
3477
    if query.NQ_INST in self.requested_data:
3478
      node_to_primary = dict([(name, set()) for name in nodenames])
3479
      node_to_secondary = dict([(name, set()) for name in nodenames])
3480

    
3481
      inst_data = lu.cfg.GetAllInstancesInfo()
3482

    
3483
      for inst in inst_data.values():
3484
        if inst.primary_node in node_to_primary:
3485
          node_to_primary[inst.primary_node].add(inst.name)
3486
        for secnode in inst.secondary_nodes:
3487
          if secnode in node_to_secondary:
3488
            node_to_secondary[secnode].add(inst.name)
3489
    else:
3490
      node_to_primary = None
3491
      node_to_secondary = None
3492

    
3493
    if query.NQ_GROUP in self.requested_data:
3494
      groups = lu.cfg.GetAllNodeGroupsInfo()
3495
    else:
3496
      groups = {}
3497

    
3498
    return query.NodeQueryData([all_info[name] for name in nodenames],
3499
                               live_data, lu.cfg.GetMasterNode(),
3500
                               node_to_primary, node_to_secondary, groups)
3501

    
3502

    
3503
class LUQueryNodes(NoHooksLU):
3504
  """Logical unit for querying nodes.
3505

3506
  """
3507
  # pylint: disable-msg=W0142
3508
  _OP_PARAMS = [
3509
    _POutputFields,
3510
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3511
    ("use_locking", False, ht.TBool),
3512
    ]
3513
  REQ_BGL = False
3514

    
3515
  def CheckArguments(self):
3516
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3517
                         self.op.use_locking)
3518

    
3519
  def ExpandNames(self):
3520
    self.nq.ExpandNames(self)
3521

    
3522
  def Exec(self, feedback_fn):
3523
    return self.nq.OldStyleQuery(self)
3524

    
3525

    
3526
class LUQueryNodeVolumes(NoHooksLU):
3527
  """Logical unit for getting volumes on node(s).
3528

3529
  """
3530
  _OP_PARAMS = [
3531
    _POutputFields,
3532
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3533
    ]
3534
  REQ_BGL = False
3535
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3536
  _FIELDS_STATIC = utils.FieldSet("node")
3537

    
3538
  def CheckArguments(self):
3539
    _CheckOutputFields(static=self._FIELDS_STATIC,
3540
                       dynamic=self._FIELDS_DYNAMIC,
3541
                       selected=self.op.output_fields)
3542

    
3543
  def ExpandNames(self):
3544
    self.needed_locks = {}
3545
    self.share_locks[locking.LEVEL_NODE] = 1
3546
    if not self.op.nodes:
3547
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3548
    else:
3549
      self.needed_locks[locking.LEVEL_NODE] = \
3550
        _GetWantedNodes(self, self.op.nodes)
3551

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

3555
    """
3556
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3557
    volumes = self.rpc.call_node_volumes(nodenames)
3558

    
3559
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3560
             in self.cfg.GetInstanceList()]
3561

    
3562
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3563

    
3564
    output = []
3565
    for node in nodenames:
3566
      nresult = volumes[node]
3567
      if nresult.offline:
3568
        continue
3569
      msg = nresult.fail_msg
3570
      if msg:
3571
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3572
        continue
3573

    
3574
      node_vols = nresult.payload[:]
3575
      node_vols.sort(key=lambda vol: vol['dev'])
3576

    
3577
      for vol in node_vols:
3578
        node_output = []
3579
        for field in self.op.output_fields:
3580
          if field == "node":
3581
            val = node
3582
          elif field == "phys":
3583
            val = vol['dev']
3584
          elif field == "vg":
3585
            val = vol['vg']
3586
          elif field == "name":
3587
            val = vol['name']
3588
          elif field == "size":
3589
            val = int(float(vol['size']))
3590
          elif field == "instance":
3591
            for inst in ilist:
3592
              if node not in lv_by_node[inst]:
3593
                continue
3594
              if vol['name'] in lv_by_node[inst][node]:
3595
                val = inst.name
3596
                break
3597
            else:
3598
              val = '-'
3599
          else:
3600
            raise errors.ParameterError(field)
3601
          node_output.append(str(val))
3602

    
3603
        output.append(node_output)
3604

    
3605
    return output
3606

    
3607

    
3608
class LUQueryNodeStorage(NoHooksLU):
3609
  """Logical unit for getting information on storage units on node(s).
3610

3611
  """
3612
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3613
  _OP_PARAMS = [
3614
    _POutputFields,
3615
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3616
    ("storage_type", ht.NoDefault, _CheckStorageType),
3617
    ("name", None, ht.TMaybeString),
3618
    ]
3619
  REQ_BGL = False
3620

    
3621
  def CheckArguments(self):
3622
    _CheckOutputFields(static=self._FIELDS_STATIC,
3623
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3624
                       selected=self.op.output_fields)
3625

    
3626
  def ExpandNames(self):
3627
    self.needed_locks = {}
3628
    self.share_locks[locking.LEVEL_NODE] = 1
3629

    
3630
    if self.op.nodes:
3631
      self.needed_locks[locking.LEVEL_NODE] = \
3632
        _GetWantedNodes(self, self.op.nodes)
3633
    else:
3634
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3635

    
3636
  def Exec(self, feedback_fn):
3637
    """Computes the list of nodes and their attributes.
3638

3639
    """
3640
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3641

    
3642
    # Always get name to sort by
3643
    if constants.SF_NAME in self.op.output_fields:
3644
      fields = self.op.output_fields[:]
3645
    else:
3646
      fields = [constants.SF_NAME] + self.op.output_fields
3647

    
3648
    # Never ask for node or type as it's only known to the LU
3649
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3650
      while extra in fields:
3651
        fields.remove(extra)
3652

    
3653
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3654
    name_idx = field_idx[constants.SF_NAME]
3655

    
3656
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3657
    data = self.rpc.call_storage_list(self.nodes,
3658
                                      self.op.storage_type, st_args,
3659
                                      self.op.name, fields)
3660

    
3661
    result = []
3662

    
3663
    for node in utils.NiceSort(self.nodes):
3664
      nresult = data[node]
3665
      if nresult.offline:
3666
        continue
3667

    
3668
      msg = nresult.fail_msg
3669
      if msg:
3670
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3671
        continue
3672

    
3673
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3674

    
3675
      for name in utils.NiceSort(rows.keys()):
3676
        row = rows[name]
3677

    
3678
        out = []
3679

    
3680
        for field in self.op.output_fields:
3681
          if field == constants.SF_NODE:
3682
            val = node
3683
          elif field == constants.SF_TYPE:
3684
            val = self.op.storage_type
3685
          elif field in field_idx:
3686
            val = row[field_idx[field]]
3687
          else:
3688
            raise errors.ParameterError(field)
3689

    
3690
          out.append(val)
3691

    
3692
        result.append(out)
3693

    
3694
    return result
3695

    
3696

    
3697
def _InstanceQuery(*args): # pylint: disable-msg=W0613
3698
  """Dummy until instance queries have been converted to query2.
3699

3700
  """
3701
  raise NotImplementedError
3702

    
3703

    
3704
#: Query type implementations
3705
_QUERY_IMPL = {
3706
  constants.QR_INSTANCE: _InstanceQuery,
3707
  constants.QR_NODE: _NodeQuery,
3708
  }
3709

    
3710

    
3711
def _GetQueryImplementation(name):
3712
  """Returns the implemtnation for a query type.
3713

3714
  @param name: Query type, must be one of L{constants.QR_OP_QUERY}
3715

3716
  """
3717
  try:
3718
    return _QUERY_IMPL[name]
3719
  except KeyError:
3720
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
3721
                               errors.ECODE_INVAL)
3722

    
3723

    
3724
class LUQuery(NoHooksLU):
3725
  """Query for resources/items of a certain kind.
3726

3727
  """
3728
  # pylint: disable-msg=W0142
3729
  _OP_PARAMS = [
3730
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY)),
3731
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3732
    ("filter", None, ht.TOr(ht.TNone,
3733
                            ht.TListOf(ht.TOr(ht.TNonEmptyString, ht.TList)))),
3734
    ]
3735
  REQ_BGL = False
3736

    
3737
  def CheckArguments(self):
3738
    qcls = _GetQueryImplementation(self.op.what)
3739
    names = qlang.ReadSimpleFilter("name", self.op.filter)
3740

    
3741
    self.impl = qcls(names, self.op.fields, False)
3742

    
3743
  def ExpandNames(self):
3744
    self.impl.ExpandNames(self)
3745

    
3746
  def DeclareLocks(self, level):
3747
    self.impl.DeclareLocks(self, level)
3748

    
3749
  def Exec(self, feedback_fn):
3750
    return self.impl.NewStyleQuery(self)
3751

    
3752

    
3753
class LUQueryFields(NoHooksLU):
3754
  """Query for resources/items of a certain kind.
3755

3756
  """
3757
  # pylint: disable-msg=W0142
3758
  _OP_PARAMS = [
3759
    ("what", ht.NoDefault, ht.TElemOf(constants.QR_OP_QUERY)),
3760
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
3761
    ]
3762
  REQ_BGL = False
3763

    
3764
  def CheckArguments(self):
3765
    self.qcls = _GetQueryImplementation(self.op.what)
3766

    
3767
  def ExpandNames(self):
3768
    self.needed_locks = {}
3769

    
3770
  def Exec(self, feedback_fn):
3771
    return self.qcls.FieldsQuery(self.op.fields)
3772

    
3773

    
3774
class LUModifyNodeStorage(NoHooksLU):
3775
  """Logical unit for modifying a storage volume on a node.
3776

3777
  """
3778
  _OP_PARAMS = [
3779
    _PNodeName,
3780
    ("storage_type", ht.NoDefault, _CheckStorageType),
3781
    ("name", ht.NoDefault, ht.TNonEmptyString),
3782
    ("changes", ht.NoDefault, ht.TDict),
3783
    ]
3784
  REQ_BGL = False
3785

    
3786
  def CheckArguments(self):
3787
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3788

    
3789
    storage_type = self.op.storage_type
3790

    
3791
    try:
3792
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3793
    except KeyError:
3794
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3795
                                 " modified" % storage_type,
3796
                                 errors.ECODE_INVAL)
3797

    
3798
    diff = set(self.op.changes.keys()) - modifiable
3799
    if diff:
3800
      raise errors.OpPrereqError("The following fields can not be modified for"
3801
                                 " storage units of type '%s': %r" %
3802
                                 (storage_type, list(diff)),
3803
                                 errors.ECODE_INVAL)
3804

    
3805
  def ExpandNames(self):
3806
    self.needed_locks = {
3807
      locking.LEVEL_NODE: self.op.node_name,
3808
      }
3809

    
3810
  def Exec(self, feedback_fn):
3811
    """Computes the list of nodes and their attributes.
3812

3813
    """
3814
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3815
    result = self.rpc.call_storage_modify(self.op.node_name,
3816
                                          self.op.storage_type, st_args,
3817
                                          self.op.name, self.op.changes)
3818
    result.Raise("Failed to modify storage unit '%s' on %s" %
3819
                 (self.op.name, self.op.node_name))
3820

    
3821

    
3822
class LUAddNode(LogicalUnit):
3823
  """Logical unit for adding node to the cluster.
3824

3825
  """
3826
  HPATH = "node-add"
3827
  HTYPE = constants.HTYPE_NODE
3828
  _OP_PARAMS = [
3829
    _PNodeName,
3830
    ("primary_ip", None, ht.NoType),
3831
    ("secondary_ip", None, ht.TMaybeString),
3832
    ("readd", False, ht.TBool),
3833
    ("group", None, ht.TMaybeString),
3834
    ("master_capable", None, ht.TMaybeBool),
3835
    ("vm_capable", None, ht.TMaybeBool),
3836
    ("ndparams", None, ht.TOr(ht.TDict, ht.TNone)),
3837
    ]
3838
  _NFLAGS = ["master_capable", "vm_capable"]
3839

    
3840
  def CheckArguments(self):
3841
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3842
    # validate/normalize the node name
3843
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3844
                                         family=self.primary_ip_family)
3845
    self.op.node_name = self.hostname.name
3846
    if self.op.readd and self.op.group:
3847
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3848
                                 " being readded", errors.ECODE_INVAL)
3849

    
3850
  def BuildHooksEnv(self):
3851
    """Build hooks env.
3852

3853
    This will run on all nodes before, and on all nodes + the new node after.
3854

3855
    """
3856
    env = {
3857
      "OP_TARGET": self.op.node_name,
3858
      "NODE_NAME": self.op.node_name,
3859
      "NODE_PIP": self.op.primary_ip,
3860
      "NODE_SIP": self.op.secondary_ip,
3861
      "MASTER_CAPABLE": str(self.op.master_capable),
3862
      "VM_CAPABLE": str(self.op.vm_capable),
3863
      }
3864
    nodes_0 = self.cfg.GetNodeList()
3865
    nodes_1 = nodes_0 + [self.op.node_name, ]
3866
    return env, nodes_0, nodes_1
3867

    
3868
  def CheckPrereq(self):
3869
    """Check prerequisites.
3870

3871
    This checks:
3872
     - the new node is not already in the config
3873
     - it is resolvable
3874
     - its parameters (single/dual homed) matches the cluster
3875

3876
    Any errors are signaled by raising errors.OpPrereqError.
3877

3878
    """
3879
    cfg = self.cfg
3880
    hostname = self.hostname
3881
    node = hostname.name
3882
    primary_ip = self.op.primary_ip = hostname.ip
3883
    if self.op.secondary_ip is None:
3884
      if self.primary_ip_family == netutils.IP6Address.family:
3885
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3886
                                   " IPv4 address must be given as secondary",
3887
                                   errors.ECODE_INVAL)
3888
      self.op.secondary_ip = primary_ip
3889

    
3890
    secondary_ip = self.op.secondary_ip
3891
    if not netutils.IP4Address.IsValid(secondary_ip):
3892
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3893
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3894

    
3895
    node_list = cfg.GetNodeList()
3896
    if not self.op.readd and node in node_list:
3897
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3898
                                 node, errors.ECODE_EXISTS)
3899
    elif self.op.readd and node not in node_list:
3900
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3901
                                 errors.ECODE_NOENT)
3902

    
3903
    self.changed_primary_ip = False
3904

    
3905
    for existing_node_name in node_list:
3906
      existing_node = cfg.GetNodeInfo(existing_node_name)
3907

    
3908
      if self.op.readd and node == existing_node_name:
3909
        if existing_node.secondary_ip != secondary_ip:
3910
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3911
                                     " address configuration as before",
3912
                                     errors.ECODE_INVAL)
3913
        if existing_node.primary_ip != primary_ip:
3914
          self.changed_primary_ip = True
3915

    
3916
        continue
3917

    
3918
      if (existing_node.primary_ip == primary_ip or
3919
          existing_node.secondary_ip == primary_ip or
3920
          existing_node.primary_ip == secondary_ip or
3921
          existing_node.secondary_ip == secondary_ip):
3922
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3923
                                   " existing node %s" % existing_node.name,
3924
                                   errors.ECODE_NOTUNIQUE)
3925

    
3926
    # After this 'if' block, None is no longer a valid value for the
3927
    # _capable op attributes
3928
    if self.op.readd:
3929
      old_node = self.cfg.GetNodeInfo(node)
3930
      assert old_node is not None, "Can't retrieve locked node %s" % node
3931
      for attr in self._NFLAGS:
3932
        if getattr(self.op, attr) is None:
3933
          setattr(self.op, attr, getattr(old_node, attr))
3934
    else:
3935
      for attr in self._NFLAGS:
3936
        if getattr(self.op, attr) is None:
3937
          setattr(self.op, attr, True)
3938

    
3939
    if self.op.readd and not self.op.vm_capable:
3940
      pri, sec = cfg.GetNodeInstances(node)
3941
      if pri or sec:
3942
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
3943
                                   " flag set to false, but it already holds"
3944
                                   " instances" % node,
3945
                                   errors.ECODE_STATE)
3946

    
3947
    # check that the type of the node (single versus dual homed) is the
3948
    # same as for the master
3949
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3950
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3951
    newbie_singlehomed = secondary_ip == primary_ip
3952
    if master_singlehomed != newbie_singlehomed:
3953
      if master_singlehomed:
3954
        raise errors.OpPrereqError("The master has no secondary ip but the"
3955
                                   " new node has one",
3956
                                   errors.ECODE_INVAL)
3957
      else:
3958
        raise errors.OpPrereqError("The master has a secondary ip but the"
3959
                                   " new node doesn't have one",
3960
                                   errors.ECODE_INVAL)
3961

    
3962
    # checks reachability
3963
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3964
      raise errors.OpPrereqError("Node not reachable by ping",
3965
                                 errors.ECODE_ENVIRON)
3966

    
3967
    if not newbie_singlehomed:
3968
      # check reachability from my secondary ip to newbie's secondary ip
3969
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3970
                           source=myself.secondary_ip):
3971
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3972
                                   " based ping to node daemon port",
3973
                                   errors.ECODE_ENVIRON)
3974

    
3975
    if self.op.readd:
3976
      exceptions = [node]
3977
    else:
3978
      exceptions = []
3979

    
3980
    if self.op.master_capable:
3981
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3982
    else:
3983
      self.master_candidate = False
3984

    
3985
    if self.op.readd:
3986
      self.new_node = old_node
3987
    else:
3988
      node_group = cfg.LookupNodeGroup(self.op.group)
3989
      self.new_node = objects.Node(name=node,
3990
                                   primary_ip=primary_ip,
3991
                                   secondary_ip=secondary_ip,
3992
                                   master_candidate=self.master_candidate,
3993
                                   offline=False, drained=False,
3994
                                   group=node_group)
3995

    
3996
    if self.op.ndparams:
3997
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3998

    
3999
  def Exec(self, feedback_fn):
4000
    """Adds the new node to the cluster.
4001

4002
    """
4003
    new_node = self.new_node
4004
    node = new_node.name
4005

    
4006
    # for re-adds, reset the offline/drained/master-candidate flags;
4007
    # we need to reset here, otherwise offline would prevent RPC calls
4008
    # later in the procedure; this also means that if the re-add
4009
    # fails, we are left with a non-offlined, broken node
4010
    if self.op.readd:
4011
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4012
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4013
      # if we demote the node, we do cleanup later in the procedure
4014
      new_node.master_candidate = self.master_candidate
4015
      if self.changed_primary_ip:
4016
        new_node.primary_ip = self.op.primary_ip
4017

    
4018
    # copy the master/vm_capable flags
4019
    for attr in self._NFLAGS:
4020
      setattr(new_node, attr, getattr(self.op, attr))
4021

    
4022
    # notify the user about any possible mc promotion
4023
    if new_node.master_candidate:
4024
      self.LogInfo("Node will be a master candidate")
4025

    
4026
    if self.op.ndparams:
4027
      new_node.ndparams = self.op.ndparams
4028

    
4029
    # check connectivity
4030
    result = self.rpc.call_version([node])[node]
4031
    result.Raise("Can't get version information from node %s" % node)
4032
    if constants.PROTOCOL_VERSION == result.payload:
4033
      logging.info("Communication to node %s fine, sw version %s match",
4034
                   node, result.payload)
4035
    else:
4036
      raise errors.OpExecError("Version mismatch master version %s,"
4037
                               " node version %s" %
4038
                               (constants.PROTOCOL_VERSION, result.payload))
4039

    
4040
    # Add node to our /etc/hosts, and add key to known_hosts
4041
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4042
      master_node = self.cfg.GetMasterNode()
4043
      result = self.rpc.call_etc_hosts_modify(master_node,
4044
                                              constants.ETC_HOSTS_ADD,
4045
                                              self.hostname.name,
4046
                                              self.hostname.ip)
4047
      result.Raise("Can't update hosts file with new host data")
4048

    
4049
    if new_node.secondary_ip != new_node.primary_ip:
4050
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4051
                               False)
4052

    
4053
    node_verify_list = [self.cfg.GetMasterNode()]
4054
    node_verify_param = {
4055
      constants.NV_NODELIST: [node],
4056
      # TODO: do a node-net-test as well?
4057
    }
4058

    
4059
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4060
                                       self.cfg.GetClusterName())
4061
    for verifier in node_verify_list:
4062
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4063
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4064
      if nl_payload:
4065
        for failed in nl_payload:
4066
          feedback_fn("ssh/hostname verification failed"
4067
                      " (checking from %s): %s" %
4068
                      (verifier, nl_payload[failed]))
4069
        raise errors.OpExecError("ssh/hostname verification failed.")
4070

    
4071
    if self.op.readd:
4072
      _RedistributeAncillaryFiles(self)
4073
      self.context.ReaddNode(new_node)
4074
      # make sure we redistribute the config
4075
      self.cfg.Update(new_node, feedback_fn)
4076
      # and make sure the new node will not have old files around
4077
      if not new_node.master_candidate:
4078
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4079
        msg = result.fail_msg
4080
        if msg:
4081
          self.LogWarning("Node failed to demote itself from master"
4082
                          " candidate status: %s" % msg)
4083
    else:
4084
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4085
                                  additional_vm=self.op.vm_capable)
4086
      self.context.AddNode(new_node, self.proc.GetECId())
4087

    
4088

    
4089
class LUSetNodeParams(LogicalUnit):
4090
  """Modifies the parameters of a node.
4091

4092
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4093
      to the node role (as _ROLE_*)
4094
  @cvar _R2F: a dictionary from node role to tuples of flags
4095
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4096

4097
  """
4098
  HPATH = "node-modify"
4099
  HTYPE = constants.HTYPE_NODE
4100
  _OP_PARAMS = [
4101
    _PNodeName,
4102
    ("master_candidate", None, ht.TMaybeBool),
4103
    ("offline", None, ht.TMaybeBool),
4104
    ("drained", None, ht.TMaybeBool),
4105
    ("auto_promote", False, ht.TBool),
4106
    ("master_capable", None, ht.TMaybeBool),
4107
    ("vm_capable", None, ht.TMaybeBool),
4108
    ("secondary_ip", None, ht.TMaybeString),
4109
    ("ndparams", None, ht.TOr(ht.TDict, ht.TNone)),
4110
    _PForce,
4111
    ]
4112
  REQ_BGL = False
4113
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4114
  _F2R = {
4115
    (True, False, False): _ROLE_CANDIDATE,
4116
    (False, True, False): _ROLE_DRAINED,
4117
    (False, False, True): _ROLE_OFFLINE,
4118
    (False, False, False): _ROLE_REGULAR,
4119
    }
4120
  _R2F = dict((v, k) for k, v in _F2R.items())
4121
  _FLAGS = ["master_candidate", "drained", "offline"]
4122

    
4123
  def CheckArguments(self):
4124
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4125
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4126
                self.op.master_capable, self.op.vm_capable,
4127
                self.op.secondary_ip, self.op.ndparams]
4128
    if all_mods.count(None) == len(all_mods):
4129
      raise errors.OpPrereqError("Please pass at least one modification",
4130
                                 errors.ECODE_INVAL)
4131
    if all_mods.count(True) > 1:
4132
      raise errors.OpPrereqError("Can't set the node into more than one"
4133
                                 " state at the same time",
4134
                                 errors.ECODE_INVAL)
4135

    
4136
    # Boolean value that tells us whether we might be demoting from MC
4137
    self.might_demote = (self.op.master_candidate == False or
4138
                         self.op.offline == True or
4139
                         self.op.drained == True or
4140
                         self.op.master_capable == False)
4141

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

    
4148
    self.lock_all = self.op.auto_promote and self.might_demote
4149
    self.lock_instances = self.op.secondary_ip is not None
4150

    
4151
  def ExpandNames(self):
4152
    if self.lock_all:
4153
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4154
    else:
4155
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4156

    
4157
    if self.lock_instances:
4158
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4159

    
4160
  def DeclareLocks(self, level):
4161
    # If we have locked all instances, before waiting to lock nodes, release
4162
    # all the ones living on nodes unrelated to the current operation.
4163
    if level == locking.LEVEL_NODE and self.lock_instances:
4164
      instances_release = []
4165
      instances_keep = []
4166
      self.affected_instances = []
4167
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4168
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4169
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4170
          i_mirrored = instance.disk_template in constants.DTS_NET_MIRROR
4171
          if i_mirrored and self.op.node_name in instance.all_nodes:
4172
            instances_keep.append(instance_name)
4173
            self.affected_instances.append(instance)
4174
          else:
4175
            instances_release.append(instance_name)
4176
        if instances_release:
4177
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4178
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4179

    
4180
  def BuildHooksEnv(self):
4181
    """Build hooks env.
4182

4183
    This runs on the master node.
4184

4185
    """
4186
    env = {
4187
      "OP_TARGET": self.op.node_name,
4188
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4189
      "OFFLINE": str(self.op.offline),
4190
      "DRAINED": str(self.op.drained),
4191
      "MASTER_CAPABLE": str(self.op.master_capable),
4192
      "VM_CAPABLE": str(self.op.vm_capable),
4193
      }
4194
    nl = [self.cfg.GetMasterNode(),
4195
          self.op.node_name]
4196
    return env, nl, nl
4197

    
4198
  def CheckPrereq(self):
4199
    """Check prerequisites.
4200

4201
    This only checks the instance list against the existing names.
4202

4203
    """
4204
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4205

    
4206
    if (self.op.master_candidate is not None or
4207
        self.op.drained is not None or
4208
        self.op.offline is not None):
4209
      # we can't change the master's node flags
4210
      if self.op.node_name == self.cfg.GetMasterNode():
4211
        raise errors.OpPrereqError("The master role can be changed"
4212
                                   " only via master-failover",
4213
                                   errors.ECODE_INVAL)
4214

    
4215
    if self.op.master_candidate and not node.master_capable:
4216
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4217
                                 " it a master candidate" % node.name,
4218
                                 errors.ECODE_STATE)
4219

    
4220
    if self.op.vm_capable == False:
4221
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4222
      if ipri or isec:
4223
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4224
                                   " the vm_capable flag" % node.name,
4225
                                   errors.ECODE_STATE)
4226

    
4227
    if node.master_candidate and self.might_demote and not self.lock_all:
4228
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4229
      # check if after removing the current node, we're missing master
4230
      # candidates
4231
      (mc_remaining, mc_should, _) = \
4232
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4233
      if mc_remaining < mc_should:
4234
        raise errors.OpPrereqError("Not enough master candidates, please"
4235
                                   " pass auto_promote to allow promotion",
4236
                                   errors.ECODE_STATE)
4237

    
4238
    self.old_flags = old_flags = (node.master_candidate,
4239
                                  node.drained, node.offline)
4240
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4241
    self.old_role = old_role = self._F2R[old_flags]
4242

    
4243
    # Check for ineffective changes
4244
    for attr in self._FLAGS:
4245
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4246
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4247
        setattr(self.op, attr, None)
4248

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

    
4252
    # If we're being deofflined/drained, we'll MC ourself if needed
4253
    if (self.op.drained == False or self.op.offline == False or
4254
        (self.op.master_capable and not node.master_capable)):
4255
      if _DecideSelfPromotion(self):
4256
        self.op.master_candidate = True
4257
        self.LogInfo("Auto-promoting node to master candidate")
4258

    
4259
    # If we're no longer master capable, we'll demote ourselves from MC
4260
    if self.op.master_capable == False and node.master_candidate:
4261
      self.LogInfo("Demoting from master candidate")
4262
      self.op.master_candidate = False
4263

    
4264
    # Compute new role
4265
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4266
    if self.op.master_candidate:
4267
      new_role = self._ROLE_CANDIDATE
4268
    elif self.op.drained:
4269
      new_role = self._ROLE_DRAINED
4270
    elif self.op.offline:
4271
      new_role = self._ROLE_OFFLINE
4272
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4273
      # False is still in new flags, which means we're un-setting (the
4274
      # only) True flag
4275
      new_role = self._ROLE_REGULAR
4276
    else: # no new flags, nothing, keep old role
4277
      new_role = old_role
4278

    
4279
    self.new_role = new_role
4280

    
4281
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4282
      # Trying to transition out of offline status
4283
      result = self.rpc.call_version([node.name])[node.name]
4284
      if result.fail_msg:
4285
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4286
                                   " to report its version: %s" %
4287
                                   (node.name, result.fail_msg),
4288
                                   errors.ECODE_STATE)
4289
      else:
4290
        self.LogWarning("Transitioning node from offline to online state"
4291
                        " without using re-add. Please make sure the node"
4292
                        " is healthy!")
4293

    
4294
    if self.op.secondary_ip:
4295
      # Ok even without locking, because this can't be changed by any LU
4296
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4297
      master_singlehomed = master.secondary_ip == master.primary_ip
4298
      if master_singlehomed and self.op.secondary_ip:
4299
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4300
                                   " homed cluster", errors.ECODE_INVAL)
4301

    
4302
      if node.offline:
4303
        if self.affected_instances:
4304
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4305
                                     " node has instances (%s) configured"
4306
                                     " to use it" % self.affected_instances)
4307
      else:
4308
        # On online nodes, check that no instances are running, and that
4309
        # the node has the new ip and we can reach it.
4310
        for instance in self.affected_instances:
4311
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4312

    
4313
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4314
        if master.name != node.name:
4315
          # check reachability from master secondary ip to new secondary ip
4316
          if not netutils.TcpPing(self.op.secondary_ip,
4317
                                  constants.DEFAULT_NODED_PORT,
4318
                                  source=master.secondary_ip):
4319
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4320
                                       " based ping to node daemon port",
4321
                                       errors.ECODE_ENVIRON)
4322

    
4323
    if self.op.ndparams:
4324
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4325
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4326
      self.new_ndparams = new_ndparams
4327

    
4328
  def Exec(self, feedback_fn):
4329
    """Modifies a node.
4330

4331
    """
4332
    node = self.node
4333
    old_role = self.old_role
4334
    new_role = self.new_role
4335

    
4336
    result = []
4337

    
4338
    if self.op.ndparams:
4339
      node.ndparams = self.new_ndparams
4340

    
4341
    for attr in ["master_capable", "vm_capable"]:
4342
      val = getattr(self.op, attr)
4343
      if val is not None:
4344
        setattr(node, attr, val)
4345
        result.append((attr, str(val)))
4346

    
4347
    if new_role != old_role:
4348
      # Tell the node to demote itself, if no longer MC and not offline
4349
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4350
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4351
        if msg:
4352
          self.LogWarning("Node failed to demote itself: %s", msg)
4353

    
4354
      new_flags = self._R2F[new_role]
4355
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4356
        if of != nf:
4357
          result.append((desc, str(nf)))
4358
      (node.master_candidate, node.drained, node.offline) = new_flags
4359

    
4360
      # we locked all nodes, we adjust the CP before updating this node
4361
      if self.lock_all:
4362
        _AdjustCandidatePool(self, [node.name])
4363

    
4364
    if self.op.secondary_ip:
4365
      node.secondary_ip = self.op.secondary_ip
4366
      result.append(("secondary_ip", self.op.secondary_ip))
4367

    
4368
    # this will trigger configuration file update, if needed
4369
    self.cfg.Update(node, feedback_fn)
4370

    
4371
    # this will trigger job queue propagation or cleanup if the mc
4372
    # flag changed
4373
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4374
      self.context.ReaddNode(node)
4375

    
4376
    return result
4377

    
4378

    
4379
class LUPowercycleNode(NoHooksLU):
4380
  """Powercycles a node.
4381

4382
  """
4383
  _OP_PARAMS = [
4384
    _PNodeName,
4385
    _PForce,
4386
    ]
4387
  REQ_BGL = False
4388

    
4389
  def CheckArguments(self):
4390
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4391
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4392
      raise errors.OpPrereqError("The node is the master and the force"
4393
                                 " parameter was not set",
4394
                                 errors.ECODE_INVAL)
4395

    
4396
  def ExpandNames(self):
4397
    """Locking for PowercycleNode.
4398

4399
    This is a last-resort option and shouldn't block on other
4400
    jobs. Therefore, we grab no locks.
4401

4402
    """
4403
    self.needed_locks = {}
4404

    
4405
  def Exec(self, feedback_fn):
4406
    """Reboots a node.
4407

4408
    """
4409
    result = self.rpc.call_node_powercycle(self.op.node_name,
4410
                                           self.cfg.GetHypervisorType())
4411
    result.Raise("Failed to schedule the reboot")
4412
    return result.payload
4413

    
4414

    
4415
class LUQueryClusterInfo(NoHooksLU):
4416
  """Query cluster configuration.
4417

4418
  """
4419
  REQ_BGL = False
4420

    
4421
  def ExpandNames(self):
4422
    self.needed_locks = {}
4423

    
4424
  def Exec(self, feedback_fn):
4425
    """Return cluster config.
4426

4427
    """
4428
    cluster = self.cfg.GetClusterInfo()
4429
    os_hvp = {}
4430

    
4431
    # Filter just for enabled hypervisors
4432
    for os_name, hv_dict in cluster.os_hvp.items():
4433
      os_hvp[os_name] = {}
4434
      for hv_name, hv_params in hv_dict.items():
4435
        if hv_name in cluster.enabled_hypervisors:
4436
          os_hvp[os_name][hv_name] = hv_params
4437

    
4438
    # Convert ip_family to ip_version
4439
    primary_ip_version = constants.IP4_VERSION
4440
    if cluster.primary_ip_family == netutils.IP6Address.family:
4441
      primary_ip_version = constants.IP6_VERSION
4442

    
4443
    result = {
4444
      "software_version": constants.RELEASE_VERSION,
4445
      "protocol_version": constants.PROTOCOL_VERSION,
4446
      "config_version": constants.CONFIG_VERSION,
4447
      "os_api_version": max(constants.OS_API_VERSIONS),
4448
      "export_version": constants.EXPORT_VERSION,
4449
      "architecture": (platform.architecture()[0], platform.machine()),
4450
      "name": cluster.cluster_name,
4451
      "master": cluster.master_node,
4452
      "default_hypervisor": cluster.enabled_hypervisors[0],
4453
      "enabled_hypervisors": cluster.enabled_hypervisors,
4454
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4455
                        for hypervisor_name in cluster.enabled_hypervisors]),
4456
      "os_hvp": os_hvp,
4457
      "beparams": cluster.beparams,
4458
      "osparams": cluster.osparams,
4459
      "nicparams": cluster.nicparams,
4460
      "candidate_pool_size": cluster.candidate_pool_size,
4461
      "master_netdev": cluster.master_netdev,
4462
      "volume_group_name": cluster.volume_group_name,
4463
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4464
      "file_storage_dir": cluster.file_storage_dir,
4465
      "maintain_node_health": cluster.maintain_node_health,
4466
      "ctime": cluster.ctime,
4467
      "mtime": cluster.mtime,
4468
      "uuid": cluster.uuid,
4469
      "tags": list(cluster.GetTags()),
4470
      "uid_pool": cluster.uid_pool,
4471
      "default_iallocator": cluster.default_iallocator,
4472
      "reserved_lvs": cluster.reserved_lvs,
4473
      "primary_ip_version": primary_ip_version,
4474
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4475
      }
4476

    
4477
    return result
4478

    
4479

    
4480
class LUQueryConfigValues(NoHooksLU):
4481
  """Return configuration values.
4482

4483
  """
4484
  _OP_PARAMS = [_POutputFields]
4485
  REQ_BGL = False
4486
  _FIELDS_DYNAMIC = utils.FieldSet()
4487
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4488
                                  "watcher_pause", "volume_group_name")
4489

    
4490
  def CheckArguments(self):
4491
    _CheckOutputFields(static=self._FIELDS_STATIC,
4492
                       dynamic=self._FIELDS_DYNAMIC,
4493
                       selected=self.op.output_fields)
4494

    
4495
  def ExpandNames(self):
4496
    self.needed_locks = {}
4497

    
4498
  def Exec(self, feedback_fn):
4499
    """Dump a representation of the cluster config to the standard output.
4500

4501
    """
4502
    values = []
4503
    for field in self.op.output_fields:
4504
      if field == "cluster_name":
4505
        entry = self.cfg.GetClusterName()
4506
      elif field == "master_node":
4507
        entry = self.cfg.GetMasterNode()
4508
      elif field == "drain_flag":
4509
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4510
      elif field == "watcher_pause":
4511
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4512
      elif field == "volume_group_name":
4513
        entry = self.cfg.GetVGName()
4514
      else:
4515
        raise errors.ParameterError(field)
4516
      values.append(entry)
4517
    return values
4518

    
4519

    
4520
class LUActivateInstanceDisks(NoHooksLU):
4521
  """Bring up an instance's disks.
4522

4523
  """
4524
  _OP_PARAMS = [
4525
    _PInstanceName,
4526
    ("ignore_size", False, ht.TBool),
4527
    ]
4528
  REQ_BGL = False
4529

    
4530
  def ExpandNames(self):
4531
    self._ExpandAndLockInstance()
4532
    self.needed_locks[locking.LEVEL_NODE] = []
4533
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4534

    
4535
  def DeclareLocks(self, level):
4536
    if level == locking.LEVEL_NODE:
4537
      self._LockInstancesNodes()
4538

    
4539
  def CheckPrereq(self):
4540
    """Check prerequisites.
4541

4542
    This checks that the instance is in the cluster.
4543

4544
    """
4545
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4546
    assert self.instance is not None, \
4547
      "Cannot retrieve locked instance %s" % self.op.instance_name
4548
    _CheckNodeOnline(self, self.instance.primary_node)
4549

    
4550
  def Exec(self, feedback_fn):
4551
    """Activate the disks.
4552

4553
    """
4554
    disks_ok, disks_info = \
4555
              _AssembleInstanceDisks(self, self.instance,
4556
                                     ignore_size=self.op.ignore_size)
4557
    if not disks_ok:
4558
      raise errors.OpExecError("Cannot activate block devices")
4559

    
4560
    return disks_info
4561

    
4562

    
4563
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4564
                           ignore_size=False):
4565
  """Prepare the block devices for an instance.
4566

4567
  This sets up the block devices on all nodes.
4568

4569
  @type lu: L{LogicalUnit}
4570
  @param lu: the logical unit on whose behalf we execute
4571
  @type instance: L{objects.Instance}
4572
  @param instance: the instance for whose disks we assemble
4573
  @type disks: list of L{objects.Disk} or None
4574
  @param disks: which disks to assemble (or all, if None)
4575
  @type ignore_secondaries: boolean
4576
  @param ignore_secondaries: if true, errors on secondary nodes
4577
      won't result in an error return from the function
4578
  @type ignore_size: boolean
4579
  @param ignore_size: if true, the current known size of the disk
4580
      will not be used during the disk activation, useful for cases
4581
      when the size is wrong
4582
  @return: False if the operation failed, otherwise a list of
4583
      (host, instance_visible_name, node_visible_name)
4584
      with the mapping from node devices to instance devices
4585

4586
  """
4587
  device_info = []
4588
  disks_ok = True
4589
  iname = instance.name
4590
  disks = _ExpandCheckDisks(instance, disks)
4591

    
4592
  # With the two passes mechanism we try to reduce the window of
4593
  # opportunity for the race condition of switching DRBD to primary
4594
  # before handshaking occured, but we do not eliminate it
4595

    
4596
  # The proper fix would be to wait (with some limits) until the
4597
  # connection has been made and drbd transitions from WFConnection
4598
  # into any other network-connected state (Connected, SyncTarget,
4599
  # SyncSource, etc.)
4600

    
4601
  # 1st pass, assemble on all nodes in secondary mode
4602
  for inst_disk in disks:
4603
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4604
      if ignore_size:
4605
        node_disk = node_disk.Copy()
4606
        node_disk.UnsetSize()
4607
      lu.cfg.SetDiskID(node_disk, node)
4608
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4609
      msg = result.fail_msg
4610
      if msg:
4611
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4612
                           " (is_primary=False, pass=1): %s",
4613
                           inst_disk.iv_name, node, msg)
4614
        if not ignore_secondaries:
4615
          disks_ok = False
4616

    
4617
  # FIXME: race condition on drbd migration to primary
4618

    
4619
  # 2nd pass, do only the primary node
4620
  for inst_disk in disks:
4621
    dev_path = None
4622

    
4623
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4624
      if node != instance.primary_node:
4625
        continue
4626
      if ignore_size:
4627
        node_disk = node_disk.Copy()
4628
        node_disk.UnsetSize()
4629
      lu.cfg.SetDiskID(node_disk, node)
4630
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4631
      msg = result.fail_msg
4632
      if msg:
4633
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4634
                           " (is_primary=True, pass=2): %s",
4635
                           inst_disk.iv_name, node, msg)
4636
        disks_ok = False
4637
      else:
4638
        dev_path = result.payload
4639

    
4640
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4641

    
4642
  # leave the disks configured for the primary node
4643
  # this is a workaround that would be fixed better by
4644
  # improving the logical/physical id handling
4645
  for disk in disks:
4646
    lu.cfg.SetDiskID(disk, instance.primary_node)
4647

    
4648
  return disks_ok, device_info
4649

    
4650

    
4651
def _StartInstanceDisks(lu, instance, force):
4652
  """Start the disks of an instance.
4653

4654
  """
4655
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4656
                                           ignore_secondaries=force)
4657
  if not disks_ok:
4658
    _ShutdownInstanceDisks(lu, instance)
4659
    if force is not None and not force:
4660
      lu.proc.LogWarning("", hint="If the message above refers to a"
4661
                         " secondary node,"
4662
                         " you can retry the operation using '--force'.")
4663
    raise errors.OpExecError("Disk consistency error")
4664

    
4665

    
4666
class LUDeactivateInstanceDisks(NoHooksLU):
4667
  """Shutdown an instance's disks.
4668

4669
  """
4670
  _OP_PARAMS = [
4671
    _PInstanceName,
4672
    ]
4673
  REQ_BGL = False
4674

    
4675
  def ExpandNames(self):
4676
    self._ExpandAndLockInstance()
4677
    self.needed_locks[locking.LEVEL_NODE] = []
4678
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4679

    
4680
  def DeclareLocks(self, level):
4681
    if level == locking.LEVEL_NODE:
4682
      self._LockInstancesNodes()
4683

    
4684
  def CheckPrereq(self):
4685
    """Check prerequisites.
4686

4687
    This checks that the instance is in the cluster.
4688

4689
    """
4690
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4691
    assert self.instance is not None, \
4692
      "Cannot retrieve locked instance %s" % self.op.instance_name
4693

    
4694
  def Exec(self, feedback_fn):
4695
    """Deactivate the disks
4696

4697
    """
4698
    instance = self.instance
4699
    _SafeShutdownInstanceDisks(self, instance)
4700

    
4701

    
4702
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4703
  """Shutdown block devices of an instance.
4704

4705
  This function checks if an instance is running, before calling
4706
  _ShutdownInstanceDisks.
4707

4708
  """
4709
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4710
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4711

    
4712

    
4713
def _ExpandCheckDisks(instance, disks):
4714
  """Return the instance disks selected by the disks list
4715

4716
  @type disks: list of L{objects.Disk} or None
4717
  @param disks: selected disks
4718
  @rtype: list of L{objects.Disk}
4719
  @return: selected instance disks to act on
4720

4721
  """
4722
  if disks is None:
4723
    return instance.disks
4724
  else:
4725
    if not set(disks).issubset(instance.disks):
4726
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4727
                                   " target instance")
4728
    return disks
4729

    
4730

    
4731
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4732
  """Shutdown block devices of an instance.
4733

4734
  This does the shutdown on all nodes of the instance.
4735

4736
  If the ignore_primary is false, errors on the primary node are
4737
  ignored.
4738

4739
  """
4740
  all_result = True
4741
  disks = _ExpandCheckDisks(instance, disks)
4742

    
4743
  for disk in disks:
4744
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4745
      lu.cfg.SetDiskID(top_disk, node)
4746
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4747
      msg = result.fail_msg
4748
      if msg:
4749
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4750
                      disk.iv_name, node, msg)
4751
        if not ignore_primary or node != instance.primary_node:
4752
          all_result = False
4753
  return all_result
4754

    
4755

    
4756
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4757
  """Checks if a node has enough free memory.
4758

4759
  This function check if a given node has the needed amount of free
4760
  memory. In case the node has less memory or we cannot get the
4761
  information from the node, this function raise an OpPrereqError
4762
  exception.
4763

4764
  @type lu: C{LogicalUnit}
4765
  @param lu: a logical unit from which we get configuration data
4766
  @type node: C{str}
4767
  @param node: the node to check
4768
  @type reason: C{str}
4769
  @param reason: string to use in the error message
4770
  @type requested: C{int}
4771
  @param requested: the amount of memory in MiB to check for
4772
  @type hypervisor_name: C{str}
4773
  @param hypervisor_name: the hypervisor to ask for memory stats
4774
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4775
      we cannot check the node
4776

4777
  """
4778
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
4779
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4780
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4781
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4782
  if not isinstance(free_mem, int):
4783
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4784
                               " was '%s'" % (node, free_mem),
4785
                               errors.ECODE_ENVIRON)
4786
  if requested > free_mem:
4787
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4788
                               " needed %s MiB, available %s MiB" %
4789
                               (node, reason, requested, free_mem),
4790
                               errors.ECODE_NORES)
4791

    
4792

    
4793
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
4794
  """Checks if nodes have enough free disk space in the all VGs.
4795

4796
  This function check if all given nodes have the needed amount of
4797
  free disk. In case any node has less disk or we cannot get the
4798
  information from the node, this function raise an OpPrereqError
4799
  exception.
4800

4801
  @type lu: C{LogicalUnit}
4802
  @param lu: a logical unit from which we get configuration data
4803
  @type nodenames: C{list}
4804
  @param nodenames: the list of node names to check
4805
  @type req_sizes: C{dict}
4806
  @param req_sizes: the hash of vg and corresponding amount of disk in
4807
      MiB to check for
4808
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
4809
      or we cannot check the node
4810

4811
  """
4812
  if req_sizes is not None:
4813
    for vg, req_size in req_sizes.iteritems():
4814
      _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
4815

    
4816

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

4820
  This function check if all given nodes have the needed amount of
4821
  free disk. In case any node has less disk or we cannot get the
4822
  information from the node, this function raise an OpPrereqError
4823
  exception.
4824

4825
  @type lu: C{LogicalUnit}
4826
  @param lu: a logical unit from which we get configuration data
4827
  @type nodenames: C{list}
4828
  @param nodenames: the list of node names to check
4829
  @type vg: C{str}
4830
  @param vg: the volume group to check
4831
  @type requested: C{int}
4832
  @param requested: the amount of disk in MiB to check for
4833
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
4834
      or we cannot check the node
4835

4836
  """
4837
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
4838
  for node in nodenames:
4839
    info = nodeinfo[node]
4840
    info.Raise("Cannot get current information from node %s" % node,
4841
               prereq=True, ecode=errors.ECODE_ENVIRON)
4842
    vg_free = info.payload.get("vg_free", None)
4843
    if not isinstance(vg_free, int):
4844
      raise errors.OpPrereqError("Can't compute free disk space on node"
4845
                                 " %s for vg %s, result was '%s'" %
4846
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
4847
    if requested > vg_free:
4848
      raise errors.OpPrereqError("Not enough disk space on target node %s"
4849
                                 " vg %s: required %d MiB, available %d MiB" %
4850
                                 (node, vg, requested, vg_free),
4851
                                 errors.ECODE_NORES)
4852

    
4853

    
4854
class LUStartupInstance(LogicalUnit):
4855
  """Starts an instance.
4856

4857
  """
4858
  HPATH = "instance-start"
4859
  HTYPE = constants.HTYPE_INSTANCE
4860
  _OP_PARAMS = [
4861
    _PInstanceName,
4862
    _PForce,
4863
    _PIgnoreOfflineNodes,
4864
    ("hvparams", ht.EmptyDict, ht.TDict),
4865
    ("beparams", ht.EmptyDict, ht.TDict),
4866
    ]
4867
  REQ_BGL = False
4868

    
4869
  def CheckArguments(self):
4870
    # extra beparams
4871
    if self.op.beparams:
4872
      # fill the beparams dict
4873
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4874

    
4875
  def ExpandNames(self):
4876
    self._ExpandAndLockInstance()
4877

    
4878
  def BuildHooksEnv(self):
4879
    """Build hooks env.
4880

4881
    This runs on master, primary and secondary nodes of the instance.
4882

4883
    """
4884
    env = {
4885
      "FORCE": self.op.force,
4886
      }
4887
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4888
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4889
    return env, nl, nl
4890

    
4891
  def CheckPrereq(self):
4892
    """Check prerequisites.
4893

4894
    This checks that the instance is in the cluster.
4895

4896
    """
4897
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4898
    assert self.instance is not None, \
4899
      "Cannot retrieve locked instance %s" % self.op.instance_name
4900

    
4901
    # extra hvparams
4902
    if self.op.hvparams:
4903
      # check hypervisor parameter syntax (locally)
4904
      cluster = self.cfg.GetClusterInfo()
4905
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4906
      filled_hvp = cluster.FillHV(instance)
4907
      filled_hvp.update(self.op.hvparams)
4908
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4909
      hv_type.CheckParameterSyntax(filled_hvp)
4910
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4911

    
4912
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
4913

    
4914
    if self.primary_offline and self.op.ignore_offline_nodes:
4915
      self.proc.LogWarning("Ignoring offline primary node")
4916

    
4917
      if self.op.hvparams or self.op.beparams:
4918
        self.proc.LogWarning("Overridden parameters are ignored")
4919
    else:
4920
      _CheckNodeOnline(self, instance.primary_node)
4921

    
4922
      bep = self.cfg.GetClusterInfo().FillBE(instance)
4923

    
4924
      # check bridges existence
4925
      _CheckInstanceBridgesExist(self, instance)
4926

    
4927
      remote_info = self.rpc.call_instance_info(instance.primary_node,
4928
                                                instance.name,
4929
                                                instance.hypervisor)
4930
      remote_info.Raise("Error checking node %s" % instance.primary_node,
4931
                        prereq=True, ecode=errors.ECODE_ENVIRON)
4932
      if not remote_info.payload: # not running already
4933
        _CheckNodeFreeMemory(self, instance.primary_node,
4934
                             "starting instance %s" % instance.name,
4935
                             bep[constants.BE_MEMORY], instance.hypervisor)
4936

    
4937
  def Exec(self, feedback_fn):
4938
    """Start the instance.
4939

4940
    """
4941
    instance = self.instance
4942
    force = self.op.force
4943

    
4944
    self.cfg.MarkInstanceUp(instance.name)
4945

    
4946
    if self.primary_offline:
4947
      assert self.op.ignore_offline_nodes
4948
      self.proc.LogInfo("Primary node offline, marked instance as started")
4949
    else:
4950
      node_current = instance.primary_node
4951

    
4952
      _StartInstanceDisks(self, instance, force)
4953

    
4954
      result = self.rpc.call_instance_start(node_current, instance,
4955
                                            self.op.hvparams, self.op.beparams)
4956
      msg = result.fail_msg
4957
      if msg:
4958
        _ShutdownInstanceDisks(self, instance)
4959
        raise errors.OpExecError("Could not start instance: %s" % msg)
4960

    
4961

    
4962
class LURebootInstance(LogicalUnit):
4963
  """Reboot an instance.
4964

4965
  """
4966
  HPATH = "instance-reboot"
4967
  HTYPE = constants.HTYPE_INSTANCE
4968
  _OP_PARAMS = [
4969
    _PInstanceName,
4970
    ("ignore_secondaries", False, ht.TBool),
4971
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES)),
4972
    _PShutdownTimeout,
4973
    ]
4974
  REQ_BGL = False
4975

    
4976
  def ExpandNames(self):
4977
    self._ExpandAndLockInstance()
4978

    
4979
  def BuildHooksEnv(self):
4980
    """Build hooks env.
4981

4982
    This runs on master, primary and secondary nodes of the instance.
4983

4984
    """
4985
    env = {
4986
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4987
      "REBOOT_TYPE": self.op.reboot_type,
4988
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4989
      }
4990
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4991
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4992
    return env, nl, nl
4993

    
4994
  def CheckPrereq(self):
4995
    """Check prerequisites.
4996

4997
    This checks that the instance is in the cluster.
4998

4999
    """
5000
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5001
    assert self.instance is not None, \
5002
      "Cannot retrieve locked instance %s" % self.op.instance_name
5003

    
5004
    _CheckNodeOnline(self, instance.primary_node)
5005

    
5006
    # check bridges existence
5007
    _CheckInstanceBridgesExist(self, instance)
5008

    
5009
  def Exec(self, feedback_fn):
5010
    """Reboot the instance.
5011

5012
    """
5013
    instance = self.instance
5014
    ignore_secondaries = self.op.ignore_secondaries
5015
    reboot_type = self.op.reboot_type
5016

    
5017
    node_current = instance.primary_node
5018

    
5019
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5020
                       constants.INSTANCE_REBOOT_HARD]:
5021
      for disk in instance.disks:
5022
        self.cfg.SetDiskID(disk, node_current)
5023
      result = self.rpc.call_instance_reboot(node_current, instance,
5024
                                             reboot_type,
5025
                                             self.op.shutdown_timeout)
5026
      result.Raise("Could not reboot instance")
5027
    else:
5028
      result = self.rpc.call_instance_shutdown(node_current, instance,
5029
                                               self.op.shutdown_timeout)
5030
      result.Raise("Could not shutdown instance for full reboot")
5031
      _ShutdownInstanceDisks(self, instance)
5032
      _StartInstanceDisks(self, instance, ignore_secondaries)
5033
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5034
      msg = result.fail_msg
5035
      if msg:
5036
        _ShutdownInstanceDisks(self, instance)
5037
        raise errors.OpExecError("Could not start instance for"
5038
                                 " full reboot: %s" % msg)
5039

    
5040
    self.cfg.MarkInstanceUp(instance.name)
5041

    
5042

    
5043
class LUShutdownInstance(LogicalUnit):
5044
  """Shutdown an instance.
5045

5046
  """
5047
  HPATH = "instance-stop"
5048
  HTYPE = constants.HTYPE_INSTANCE
5049
  _OP_PARAMS = [
5050
    _PInstanceName,
5051
    _PIgnoreOfflineNodes,
5052
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt),
5053
    ]
5054
  REQ_BGL = False
5055

    
5056
  def ExpandNames(self):
5057
    self._ExpandAndLockInstance()
5058

    
5059
  def BuildHooksEnv(self):
5060
    """Build hooks env.
5061

5062
    This runs on master, primary and secondary nodes of the instance.
5063

5064
    """
5065
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5066
    env["TIMEOUT"] = self.op.timeout
5067
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5068
    return env, nl, nl
5069

    
5070
  def CheckPrereq(self):
5071
    """Check prerequisites.
5072

5073
    This checks that the instance is in the cluster.
5074

5075
    """
5076
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5077
    assert self.instance is not None, \
5078
      "Cannot retrieve locked instance %s" % self.op.instance_name
5079

    
5080
    self.primary_offline = \
5081
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5082

    
5083
    if self.primary_offline and self.op.ignore_offline_nodes:
5084
      self.proc.LogWarning("Ignoring offline primary node")
5085
    else:
5086
      _CheckNodeOnline(self, self.instance.primary_node)
5087

    
5088
  def Exec(self, feedback_fn):
5089
    """Shutdown the instance.
5090

5091
    """
5092
    instance = self.instance
5093
    node_current = instance.primary_node
5094
    timeout = self.op.timeout
5095

    
5096
    self.cfg.MarkInstanceDown(instance.name)
5097

    
5098
    if self.primary_offline:
5099
      assert self.op.ignore_offline_nodes
5100
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5101
    else:
5102
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5103
      msg = result.fail_msg
5104
      if msg:
5105
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5106

    
5107
      _ShutdownInstanceDisks(self, instance)
5108

    
5109

    
5110
class LUReinstallInstance(LogicalUnit):
5111
  """Reinstall an instance.
5112

5113
  """
5114
  HPATH = "instance-reinstall"
5115
  HTYPE = constants.HTYPE_INSTANCE
5116
  _OP_PARAMS = [
5117
    _PInstanceName,
5118
    ("os_type", None, ht.TMaybeString),
5119
    ("force_variant", False, ht.TBool),
5120
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
5121
    ]
5122
  REQ_BGL = False
5123

    
5124
  def ExpandNames(self):
5125
    self._ExpandAndLockInstance()
5126

    
5127
  def BuildHooksEnv(self):
5128
    """Build hooks env.
5129

5130
    This runs on master, primary and secondary nodes of the instance.
5131

5132
    """
5133
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5134
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5135
    return env, nl, nl
5136

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

5140
    This checks that the instance is in the cluster and is not running.
5141

5142
    """
5143
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5144
    assert instance is not None, \
5145
      "Cannot retrieve locked instance %s" % self.op.instance_name
5146
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5147
                     " offline, cannot reinstall")
5148
    for node in instance.secondary_nodes:
5149
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5150
                       " cannot reinstall")
5151

    
5152
    if instance.disk_template == constants.DT_DISKLESS:
5153
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5154
                                 self.op.instance_name,
5155
                                 errors.ECODE_INVAL)
5156
    _CheckInstanceDown(self, instance, "cannot reinstall")
5157

    
5158
    if self.op.os_type is not None:
5159
      # OS verification
5160
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5161
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5162
      instance_os = self.op.os_type
5163
    else:
5164
      instance_os = instance.os
5165

    
5166
    nodelist = list(instance.all_nodes)
5167

    
5168
    if self.op.osparams:
5169
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5170
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5171
      self.os_inst = i_osdict # the new dict (without defaults)
5172
    else:
5173
      self.os_inst = None
5174

    
5175
    self.instance = instance
5176

    
5177
  def Exec(self, feedback_fn):
5178
    """Reinstall the instance.
5179

5180
    """
5181
    inst = self.instance
5182

    
5183
    if self.op.os_type is not None:
5184
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5185
      inst.os = self.op.os_type
5186
      # Write to configuration
5187
      self.cfg.Update(inst, feedback_fn)
5188

    
5189
    _StartInstanceDisks(self, inst, None)
5190
    try:
5191
      feedback_fn("Running the instance OS create scripts...")
5192
      # FIXME: pass debug option from opcode to backend
5193
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5194
                                             self.op.debug_level,
5195
                                             osparams=self.os_inst)
5196
      result.Raise("Could not install OS for instance %s on node %s" %
5197
                   (inst.name, inst.primary_node))
5198
    finally:
5199
      _ShutdownInstanceDisks(self, inst)
5200

    
5201

    
5202
class LURecreateInstanceDisks(LogicalUnit):
5203
  """Recreate an instance's missing disks.
5204

5205
  """
5206
  HPATH = "instance-recreate-disks"
5207
  HTYPE = constants.HTYPE_INSTANCE
5208
  _OP_PARAMS = [
5209
    _PInstanceName,
5210
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
5211
    ]
5212
  REQ_BGL = False
5213

    
5214
  def ExpandNames(self):
5215
    self._ExpandAndLockInstance()
5216

    
5217
  def BuildHooksEnv(self):
5218
    """Build hooks env.
5219

5220
    This runs on master, primary and secondary nodes of the instance.
5221

5222
    """
5223
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5224
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5225
    return env, nl, nl
5226

    
5227
  def CheckPrereq(self):
5228
    """Check prerequisites.
5229

5230
    This checks that the instance is in the cluster and is not running.
5231

5232
    """
5233
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5234
    assert instance is not None, \
5235
      "Cannot retrieve locked instance %s" % self.op.instance_name
5236
    _CheckNodeOnline(self, instance.primary_node)
5237

    
5238
    if instance.disk_template == constants.DT_DISKLESS:
5239
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5240
                                 self.op.instance_name, errors.ECODE_INVAL)
5241
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5242

    
5243
    if not self.op.disks:
5244
      self.op.disks = range(len(instance.disks))
5245
    else:
5246
      for idx in self.op.disks:
5247
        if idx >= len(instance.disks):
5248
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5249
                                     errors.ECODE_INVAL)
5250

    
5251
    self.instance = instance
5252

    
5253
  def Exec(self, feedback_fn):
5254
    """Recreate the disks.
5255

5256
    """
5257
    to_skip = []
5258
    for idx, _ in enumerate(self.instance.disks):
5259
      if idx not in self.op.disks: # disk idx has not been passed in
5260
        to_skip.append(idx)
5261
        continue
5262

    
5263
    _CreateDisks(self, self.instance, to_skip=to_skip)
5264

    
5265

    
5266
class LURenameInstance(LogicalUnit):
5267
  """Rename an instance.
5268

5269
  """
5270
  HPATH = "instance-rename"
5271
  HTYPE = constants.HTYPE_INSTANCE
5272
  _OP_PARAMS = [
5273
    _PInstanceName,
5274
    ("new_name", ht.NoDefault, ht.TNonEmptyString),
5275
    ("ip_check", False, ht.TBool),
5276
    ("name_check", True, ht.TBool),
5277
    ]
5278

    
5279
  def CheckArguments(self):
5280
    """Check arguments.
5281

5282
    """
5283
    if self.op.ip_check and not self.op.name_check:
5284
      # TODO: make the ip check more flexible and not depend on the name check
5285
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5286
                                 errors.ECODE_INVAL)
5287

    
5288
  def BuildHooksEnv(self):
5289
    """Build hooks env.
5290

5291
    This runs on master, primary and secondary nodes of the instance.
5292

5293
    """
5294
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5295
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5296
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5297
    return env, nl, nl
5298

    
5299
  def CheckPrereq(self):
5300
    """Check prerequisites.
5301

5302
    This checks that the instance is in the cluster and is not running.
5303

5304
    """
5305
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5306
                                                self.op.instance_name)
5307
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5308
    assert instance is not None
5309
    _CheckNodeOnline(self, instance.primary_node)
5310
    _CheckInstanceDown(self, instance, "cannot rename")
5311
    self.instance = instance
5312

    
5313
    new_name = self.op.new_name
5314
    if self.op.name_check:
5315
      hostname = netutils.GetHostname(name=new_name)
5316
      new_name = self.op.new_name = hostname.name
5317
      if (self.op.ip_check and
5318
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5319
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5320
                                   (hostname.ip, new_name),
5321
                                   errors.ECODE_NOTUNIQUE)
5322

    
5323
    instance_list = self.cfg.GetInstanceList()
5324
    if new_name in instance_list:
5325
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5326
                                 new_name, errors.ECODE_EXISTS)
5327

    
5328
  def Exec(self, feedback_fn):
5329
    """Reinstall the instance.
5330

5331
    """
5332
    inst = self.instance
5333
    old_name = inst.name
5334

    
5335
    if inst.disk_template == constants.DT_FILE:
5336
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5337

    
5338
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5339
    # Change the instance lock. This is definitely safe while we hold the BGL
5340
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5341
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5342

    
5343
    # re-read the instance from the configuration after rename
5344
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5345

    
5346
    if inst.disk_template == constants.DT_FILE:
5347
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5348
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5349
                                                     old_file_storage_dir,
5350
                                                     new_file_storage_dir)
5351
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5352
                   " (but the instance has been renamed in Ganeti)" %
5353
                   (inst.primary_node, old_file_storage_dir,
5354
                    new_file_storage_dir))
5355

    
5356
    _StartInstanceDisks(self, inst, None)
5357
    try:
5358
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5359
                                                 old_name, self.op.debug_level)
5360
      msg = result.fail_msg
5361
      if msg:
5362
        msg = ("Could not run OS rename script for instance %s on node %s"
5363
               " (but the instance has been renamed in Ganeti): %s" %
5364
               (inst.name, inst.primary_node, msg))
5365
        self.proc.LogWarning(msg)
5366
    finally:
5367
      _ShutdownInstanceDisks(self, inst)
5368

    
5369
    return inst.name
5370

    
5371

    
5372
class LURemoveInstance(LogicalUnit):
5373
  """Remove an instance.
5374

5375
  """
5376
  HPATH = "instance-remove"
5377
  HTYPE = constants.HTYPE_INSTANCE
5378
  _OP_PARAMS = [
5379
    _PInstanceName,
5380
    ("ignore_failures", False, ht.TBool),
5381
    _PShutdownTimeout,
5382
    ]
5383
  REQ_BGL = False
5384

    
5385
  def ExpandNames(self):
5386
    self._ExpandAndLockInstance()
5387
    self.needed_locks[locking.LEVEL_NODE] = []
5388
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5389

    
5390
  def DeclareLocks(self, level):
5391
    if level == locking.LEVEL_NODE:
5392
      self._LockInstancesNodes()
5393

    
5394
  def BuildHooksEnv(self):
5395
    """Build hooks env.
5396

5397
    This runs on master, primary and secondary nodes of the instance.
5398

5399
    """
5400
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5401
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5402
    nl = [self.cfg.GetMasterNode()]
5403
    nl_post = list(self.instance.all_nodes) + nl
5404
    return env, nl, nl_post
5405

    
5406
  def CheckPrereq(self):
5407
    """Check prerequisites.
5408

5409
    This checks that the instance is in the cluster.
5410

5411
    """
5412
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5413
    assert self.instance is not None, \
5414
      "Cannot retrieve locked instance %s" % self.op.instance_name
5415

    
5416
  def Exec(self, feedback_fn):
5417
    """Remove the instance.
5418

5419
    """
5420
    instance = self.instance
5421
    logging.info("Shutting down instance %s on node %s",
5422
                 instance.name, instance.primary_node)
5423

    
5424
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5425
                                             self.op.shutdown_timeout)
5426
    msg = result.fail_msg
5427
    if msg:
5428
      if self.op.ignore_failures:
5429
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5430
      else:
5431
        raise errors.OpExecError("Could not shutdown instance %s on"
5432
                                 " node %s: %s" %
5433
                                 (instance.name, instance.primary_node, msg))
5434

    
5435
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5436

    
5437

    
5438
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5439
  """Utility function to remove an instance.
5440

5441
  """
5442
  logging.info("Removing block devices for instance %s", instance.name)
5443

    
5444
  if not _RemoveDisks(lu, instance):
5445
    if not ignore_failures:
5446
      raise errors.OpExecError("Can't remove instance's disks")
5447
    feedback_fn("Warning: can't remove instance's disks")
5448

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

    
5451
  lu.cfg.RemoveInstance(instance.name)
5452

    
5453
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5454
    "Instance lock removal conflict"
5455

    
5456
  # Remove lock for the instance
5457
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5458

    
5459

    
5460
class LUQueryInstances(NoHooksLU):
5461
  """Logical unit for querying instances.
5462

5463
  """
5464
  # pylint: disable-msg=W0142
5465
  _OP_PARAMS = [
5466
    _POutputFields,
5467
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
5468
    ("use_locking", False, ht.TBool),
5469
    ]
5470
  REQ_BGL = False
5471
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5472
                    "serial_no", "ctime", "mtime", "uuid"]
5473
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5474
                                    "admin_state",
5475
                                    "disk_template", "ip", "mac", "bridge",
5476
                                    "nic_mode", "nic_link",
5477
                                    "sda_size", "sdb_size", "vcpus", "tags",
5478
                                    "network_port", "beparams",
5479
                                    r"(disk)\.(size)/([0-9]+)",
5480
                                    r"(disk)\.(sizes)", "disk_usage",
5481
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5482
                                    r"(nic)\.(bridge)/([0-9]+)",
5483
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5484
                                    r"(disk|nic)\.(count)",
5485
                                    "hvparams", "custom_hvparams",
5486
                                    "custom_beparams", "custom_nicparams",
5487
                                    ] + _SIMPLE_FIELDS +
5488
                                  ["hv/%s" % name
5489
                                   for name in constants.HVS_PARAMETERS
5490
                                   if name not in constants.HVC_GLOBALS] +
5491
                                  ["be/%s" % name
5492
                                   for name in constants.BES_PARAMETERS])
5493
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5494
                                   "oper_ram",
5495
                                   "oper_vcpus",
5496
                                   "status")
5497

    
5498

    
5499
  def CheckArguments(self):
5500
    _CheckOutputFields(static=self._FIELDS_STATIC,
5501
                       dynamic=self._FIELDS_DYNAMIC,
5502
                       selected=self.op.output_fields)
5503

    
5504
  def ExpandNames(self):
5505
    self.needed_locks = {}
5506
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5507
    self.share_locks[locking.LEVEL_NODE] = 1
5508

    
5509
    if self.op.names:
5510
      self.wanted = _GetWantedInstances(self, self.op.names)
5511
    else:
5512
      self.wanted = locking.ALL_SET
5513

    
5514
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5515
    self.do_locking = self.do_node_query and self.op.use_locking
5516
    if self.do_locking:
5517
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5518
      self.needed_locks[locking.LEVEL_NODE] = []
5519
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5520

    
5521
  def DeclareLocks(self, level):
5522
    if level == locking.LEVEL_NODE and self.do_locking:
5523
      self._LockInstancesNodes()
5524

    
5525
  def Exec(self, feedback_fn):
5526
    """Computes the list of nodes and their attributes.
5527

5528
    """
5529
    # pylint: disable-msg=R0912
5530
    # way too many branches here
5531
    all_info = self.cfg.GetAllInstancesInfo()
5532
    if self.wanted == locking.ALL_SET:
5533
      # caller didn't specify instance names, so ordering is not important
5534
      if self.do_locking:
5535
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5536
      else:
5537
        instance_names = all_info.keys()
5538
      instance_names = utils.NiceSort(instance_names)
5539
    else:
5540
      # caller did specify names, so we must keep the ordering
5541
      if self.do_locking:
5542
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5543
      else:
5544
        tgt_set = all_info.keys()
5545
      missing = set(self.wanted).difference(tgt_set)
5546
      if missing:
5547
        raise errors.OpExecError("Some instances were removed before"
5548
                                 " retrieving their data: %s" % missing)
5549
      instance_names = self.wanted
5550

    
5551
    instance_list = [all_info[iname] for iname in instance_names]
5552

    
5553
    # begin data gathering
5554

    
5555
    nodes = frozenset([inst.primary_node for inst in instance_list])
5556
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5557

    
5558
    bad_nodes = []
5559
    off_nodes = []
5560
    if self.do_node_query:
5561
      live_data = {}
5562
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5563
      for name in nodes:
5564
        result = node_data[name]
5565
        if result.offline:
5566
          # offline nodes will be in both lists
5567
          off_nodes.append(name)
5568
        if result.fail_msg:
5569
          bad_nodes.append(name)
5570
        else:
5571
          if result.payload:
5572
            live_data.update(result.payload)
5573
          # else no instance is alive
5574
    else:
5575
      live_data = dict([(name, {}) for name in instance_names])
5576

    
5577
    # end data gathering
5578

    
5579
    HVPREFIX = "hv/"
5580
    BEPREFIX = "be/"
5581
    output = []
5582
    cluster = self.cfg.GetClusterInfo()
5583
    for instance in instance_list:
5584
      iout = []
5585
      i_hv = cluster.FillHV(instance, skip_globals=True)
5586
      i_be = cluster.FillBE(instance)
5587
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5588
      for field in self.op.output_fields:
5589
        st_match = self._FIELDS_STATIC.Matches(field)
5590
        if field in self._SIMPLE_FIELDS:
5591
          val = getattr(instance, field)
5592
        elif field == "pnode":
5593
          val = instance.primary_node
5594
        elif field == "snodes":
5595
          val = list(instance.secondary_nodes)
5596
        elif field == "admin_state":
5597
          val = instance.admin_up
5598
        elif field == "oper_state":
5599
          if instance.primary_node in bad_nodes:
5600
            val = None
5601
          else:
5602
            val = bool(live_data.get(instance.name))
5603
        elif field == "status":
5604
          if instance.primary_node in off_nodes:
5605
            val = "ERROR_nodeoffline"
5606
          elif instance.primary_node in bad_nodes:
5607
            val = "ERROR_nodedown"
5608
          else:
5609
            running = bool(live_data.get(instance.name))
5610
            if running:
5611
              if instance.admin_up:
5612
                val = "running"
5613
              else:
5614
                val = "ERROR_up"
5615
            else:
5616
              if instance.admin_up:
5617
                val = "ERROR_down"
5618
              else:
5619
                val = "ADMIN_down"
5620
        elif field == "oper_ram":
5621
          if instance.primary_node in bad_nodes:
5622
            val = None
5623
          elif instance.name in live_data:
5624
            val = live_data[instance.name].get("memory", "?")
5625
          else:
5626
            val = "-"
5627
        elif field == "oper_vcpus":
5628
          if instance.primary_node in bad_nodes:
5629
            val = None
5630
          elif instance.name in live_data:
5631
            val = live_data[instance.name].get("vcpus", "?")
5632
          else:
5633
            val = "-"
5634
        elif field == "vcpus":
5635
          val = i_be[constants.BE_VCPUS]
5636
        elif field == "disk_template":
5637
          val = instance.disk_template
5638
        elif field == "ip":
5639
          if instance.nics:
5640
            val = instance.nics[0].ip
5641
          else:
5642
            val = None
5643
        elif field == "nic_mode":
5644
          if instance.nics:
5645
            val = i_nicp[0][constants.NIC_MODE]
5646
          else:
5647
            val = None
5648
        elif field == "nic_link":
5649
          if instance.nics:
5650
            val = i_nicp[0][constants.NIC_LINK]
5651
          else:
5652
            val = None
5653
        elif field == "bridge":
5654
          if (instance.nics and
5655
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5656
            val = i_nicp[0][constants.NIC_LINK]
5657
          else:
5658
            val = None
5659
        elif field == "mac":
5660
          if instance.nics:
5661
            val = instance.nics[0].mac
5662
          else:
5663
            val = None
5664
        elif field == "custom_nicparams":
5665
          val = [nic.nicparams for nic in instance.nics]
5666
        elif field == "sda_size" or field == "sdb_size":
5667
          idx = ord(field[2]) - ord('a')
5668
          try:
5669
            val = instance.FindDisk(idx).size
5670
          except errors.OpPrereqError:
5671
            val = None
5672
        elif field == "disk_usage": # total disk usage per node
5673
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5674
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5675
        elif field == "tags":
5676
          val = list(instance.GetTags())
5677
        elif field == "custom_hvparams":
5678
          val = instance.hvparams # not filled!
5679
        elif field == "hvparams":
5680
          val = i_hv
5681
        elif (field.startswith(HVPREFIX) and
5682
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5683
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5684
          val = i_hv.get(field[len(HVPREFIX):], None)
5685
        elif field == "custom_beparams":
5686
          val = instance.beparams
5687
        elif field == "beparams":
5688
          val = i_be
5689
        elif (field.startswith(BEPREFIX) and
5690
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5691
          val = i_be.get(field[len(BEPREFIX):], None)
5692
        elif st_match and st_match.groups():
5693
          # matches a variable list
5694
          st_groups = st_match.groups()
5695
          if st_groups and st_groups[0] == "disk":
5696
            if st_groups[1] == "count":
5697
              val = len(instance.disks)
5698
            elif st_groups[1] == "sizes":
5699
              val = [disk.size for disk in instance.disks]
5700
            elif st_groups[1] == "size":
5701
              try:
5702
                val = instance.FindDisk(st_groups[2]).size
5703
              except errors.OpPrereqError:
5704
                val = None
5705
            else:
5706
              assert False, "Unhandled disk parameter"
5707
          elif st_groups[0] == "nic":
5708
            if st_groups[1] == "count":
5709
              val = len(instance.nics)
5710
            elif st_groups[1] == "macs":
5711
              val = [nic.mac for nic in instance.nics]
5712
            elif st_groups[1] == "ips":
5713
              val = [nic.ip for nic in instance.nics]
5714
            elif st_groups[1] == "modes":
5715
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5716
            elif st_groups[1] == "links":
5717
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5718
            elif st_groups[1] == "bridges":
5719
              val = []
5720
              for nicp in i_nicp:
5721
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5722
                  val.append(nicp[constants.NIC_LINK])
5723
                else:
5724
                  val.append(None)
5725
            else:
5726
              # index-based item
5727
              nic_idx = int(st_groups[2])
5728
              if nic_idx >= len(instance.nics):
5729
                val = None
5730
              else:
5731
                if st_groups[1] == "mac":
5732
                  val = instance.nics[nic_idx].mac
5733
                elif st_groups[1] == "ip":
5734
                  val = instance.nics[nic_idx].ip
5735
                elif st_groups[1] == "mode":
5736
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5737
                elif st_groups[1] == "link":
5738
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5739
                elif st_groups[1] == "bridge":
5740
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5741
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5742
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5743
                  else:
5744
                    val = None
5745
                else:
5746
                  assert False, "Unhandled NIC parameter"
5747
          else:
5748
            assert False, ("Declared but unhandled variable parameter '%s'" %
5749
                           field)
5750
        else:
5751
          assert False, "Declared but unhandled parameter '%s'" % field
5752
        iout.append(val)
5753
      output.append(iout)
5754

    
5755
    return output
5756

    
5757

    
5758
class LUFailoverInstance(LogicalUnit):
5759
  """Failover an instance.
5760

5761
  """
5762
  HPATH = "instance-failover"
5763
  HTYPE = constants.HTYPE_INSTANCE
5764
  _OP_PARAMS = [
5765
    _PInstanceName,
5766
    ("ignore_consistency", False, ht.TBool),
5767
    _PShutdownTimeout,
5768
    ]
5769
  REQ_BGL = False
5770

    
5771
  def ExpandNames(self):
5772
    self._ExpandAndLockInstance()
5773
    self.needed_locks[locking.LEVEL_NODE] = []
5774
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5775

    
5776
  def DeclareLocks(self, level):
5777
    if level == locking.LEVEL_NODE:
5778
      self._LockInstancesNodes()
5779

    
5780
  def BuildHooksEnv(self):
5781
    """Build hooks env.
5782

5783
    This runs on master, primary and secondary nodes of the instance.
5784

5785
    """
5786
    instance = self.instance
5787
    source_node = instance.primary_node
5788
    target_node = instance.secondary_nodes[0]
5789
    env = {
5790
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5791
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5792
      "OLD_PRIMARY": source_node,
5793
      "OLD_SECONDARY": target_node,
5794
      "NEW_PRIMARY": target_node,
5795
      "NEW_SECONDARY": source_node,
5796
      }
5797
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5798
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5799
    nl_post = list(nl)
5800
    nl_post.append(source_node)
5801
    return env, nl, nl_post
5802

    
5803
  def CheckPrereq(self):
5804
    """Check prerequisites.
5805

5806
    This checks that the instance is in the cluster.
5807

5808
    """
5809
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5810
    assert self.instance is not None, \
5811
      "Cannot retrieve locked instance %s" % self.op.instance_name
5812

    
5813
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5814
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5815
      raise errors.OpPrereqError("Instance's disk layout is not"
5816
                                 " network mirrored, cannot failover.",
5817
                                 errors.ECODE_STATE)
5818

    
5819
    secondary_nodes = instance.secondary_nodes
5820
    if not secondary_nodes:
5821
      raise errors.ProgrammerError("no secondary node but using "
5822
                                   "a mirrored disk template")
5823

    
5824
    target_node = secondary_nodes[0]
5825
    _CheckNodeOnline(self, target_node)
5826
    _CheckNodeNotDrained(self, target_node)
5827
    if instance.admin_up:
5828
      # check memory requirements on the secondary node
5829
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5830
                           instance.name, bep[constants.BE_MEMORY],
5831
                           instance.hypervisor)
5832
    else:
5833
      self.LogInfo("Not checking memory on the secondary node as"
5834
                   " instance will not be started")
5835

    
5836
    # check bridge existance
5837
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5838

    
5839
  def Exec(self, feedback_fn):
5840
    """Failover an instance.
5841

5842
    The failover is done by shutting it down on its present node and
5843
    starting it on the secondary.
5844

5845
    """
5846
    instance = self.instance
5847
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5848

    
5849
    source_node = instance.primary_node
5850
    target_node = instance.secondary_nodes[0]
5851

    
5852
    if instance.admin_up:
5853
      feedback_fn("* checking disk consistency between source and target")
5854
      for dev in instance.disks:
5855
        # for drbd, these are drbd over lvm
5856
        if not _CheckDiskConsistency(self, dev, target_node, False):
5857
          if not self.op.ignore_consistency:
5858
            raise errors.OpExecError("Disk %s is degraded on target node,"
5859
                                     " aborting failover." % dev.iv_name)
5860
    else:
5861
      feedback_fn("* not checking disk consistency as instance is not running")
5862

    
5863
    feedback_fn("* shutting down instance on source node")
5864
    logging.info("Shutting down instance %s on node %s",
5865
                 instance.name, source_node)
5866

    
5867
    result = self.rpc.call_instance_shutdown(source_node, instance,
5868
                                             self.op.shutdown_timeout)
5869
    msg = result.fail_msg
5870
    if msg:
5871
      if self.op.ignore_consistency or primary_node.offline:
5872
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5873
                             " Proceeding anyway. Please make sure node"
5874
                             " %s is down. Error details: %s",
5875
                             instance.name, source_node, source_node, msg)
5876
      else:
5877
        raise errors.OpExecError("Could not shutdown instance %s on"
5878
                                 " node %s: %s" %
5879
                                 (instance.name, source_node, msg))
5880

    
5881
    feedback_fn("* deactivating the instance's disks on source node")
5882
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5883
      raise errors.OpExecError("Can't shut down the instance's disks.")
5884

    
5885
    instance.primary_node = target_node
5886
    # distribute new instance config to the other nodes
5887
    self.cfg.Update(instance, feedback_fn)
5888

    
5889
    # Only start the instance if it's marked as up
5890
    if instance.admin_up:
5891
      feedback_fn("* activating the instance's disks on target node")
5892
      logging.info("Starting instance %s on node %s",
5893
                   instance.name, target_node)
5894

    
5895
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5896
                                           ignore_secondaries=True)
5897
      if not disks_ok:
5898
        _ShutdownInstanceDisks(self, instance)
5899
        raise errors.OpExecError("Can't activate the instance's disks")
5900

    
5901
      feedback_fn("* starting the instance on the target node")
5902
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5903
      msg = result.fail_msg
5904
      if msg:
5905
        _ShutdownInstanceDisks(self, instance)
5906
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5907
                                 (instance.name, target_node, msg))
5908

    
5909

    
5910
class LUMigrateInstance(LogicalUnit):
5911
  """Migrate an instance.
5912

5913
  This is migration without shutting down, compared to the failover,
5914
  which is done with shutdown.
5915

5916
  """
5917
  HPATH = "instance-migrate"
5918
  HTYPE = constants.HTYPE_INSTANCE
5919
  _OP_PARAMS = [
5920
    _PInstanceName,
5921
    _PMigrationMode,
5922
    _PMigrationLive,
5923
    ("cleanup", False, ht.TBool),
5924
    ]
5925

    
5926
  REQ_BGL = False
5927

    
5928
  def ExpandNames(self):
5929
    self._ExpandAndLockInstance()
5930

    
5931
    self.needed_locks[locking.LEVEL_NODE] = []
5932
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5933

    
5934
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5935
                                       self.op.cleanup)
5936
    self.tasklets = [self._migrater]
5937

    
5938
  def DeclareLocks(self, level):
5939
    if level == locking.LEVEL_NODE:
5940
      self._LockInstancesNodes()
5941

    
5942
  def BuildHooksEnv(self):
5943
    """Build hooks env.
5944

5945
    This runs on master, primary and secondary nodes of the instance.
5946

5947
    """
5948
    instance = self._migrater.instance
5949
    source_node = instance.primary_node
5950
    target_node = instance.secondary_nodes[0]
5951
    env = _BuildInstanceHookEnvByObject(self, instance)
5952
    env["MIGRATE_LIVE"] = self._migrater.live
5953
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5954
    env.update({
5955
        "OLD_PRIMARY": source_node,
5956
        "OLD_SECONDARY": target_node,
5957
        "NEW_PRIMARY": target_node,
5958
        "NEW_SECONDARY": source_node,
5959
        })
5960
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5961
    nl_post = list(nl)
5962
    nl_post.append(source_node)
5963
    return env, nl, nl_post
5964

    
5965

    
5966
class LUMoveInstance(LogicalUnit):
5967
  """Move an instance by data-copying.
5968

5969
  """
5970
  HPATH = "instance-move"
5971
  HTYPE = constants.HTYPE_INSTANCE
5972
  _OP_PARAMS = [
5973
    _PInstanceName,
5974
    ("target_node", ht.NoDefault, ht.TNonEmptyString),
5975
    _PShutdownTimeout,
5976
    ]
5977
  REQ_BGL = False
5978

    
5979
  def ExpandNames(self):
5980
    self._ExpandAndLockInstance()
5981
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5982
    self.op.target_node = target_node
5983
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5984
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5985

    
5986
  def DeclareLocks(self, level):
5987
    if level == locking.LEVEL_NODE:
5988
      self._LockInstancesNodes(primary_only=True)
5989

    
5990
  def BuildHooksEnv(self):
5991
    """Build hooks env.
5992

5993
    This runs on master, primary and secondary nodes of the instance.
5994

5995
    """
5996
    env = {
5997
      "TARGET_NODE": self.op.target_node,
5998
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5999
      }
6000
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6001
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
6002
                                       self.op.target_node]
6003
    return env, nl, nl
6004

    
6005
  def CheckPrereq(self):
6006
    """Check prerequisites.
6007

6008
    This checks that the instance is in the cluster.
6009

6010
    """
6011
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6012
    assert self.instance is not None, \
6013
      "Cannot retrieve locked instance %s" % self.op.instance_name
6014

    
6015
    node = self.cfg.GetNodeInfo(self.op.target_node)
6016
    assert node is not None, \
6017
      "Cannot retrieve locked node %s" % self.op.target_node
6018

    
6019
    self.target_node = target_node = node.name
6020

    
6021
    if target_node == instance.primary_node:
6022
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6023
                                 (instance.name, target_node),
6024
                                 errors.ECODE_STATE)
6025

    
6026
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6027

    
6028
    for idx, dsk in enumerate(instance.disks):
6029
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6030
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6031
                                   " cannot copy" % idx, errors.ECODE_STATE)
6032

    
6033
    _CheckNodeOnline(self, target_node)
6034
    _CheckNodeNotDrained(self, target_node)
6035
    _CheckNodeVmCapable(self, target_node)
6036

    
6037
    if instance.admin_up:
6038
      # check memory requirements on the secondary node
6039
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6040
                           instance.name, bep[constants.BE_MEMORY],
6041
                           instance.hypervisor)
6042
    else:
6043
      self.LogInfo("Not checking memory on the secondary node as"
6044
                   " instance will not be started")
6045

    
6046
    # check bridge existance
6047
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6048

    
6049
  def Exec(self, feedback_fn):
6050
    """Move an instance.
6051

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

6055
    """
6056
    instance = self.instance
6057

    
6058
    source_node = instance.primary_node
6059
    target_node = self.target_node
6060

    
6061
    self.LogInfo("Shutting down instance %s on source node %s",
6062
                 instance.name, source_node)
6063

    
6064
    result = self.rpc.call_instance_shutdown(source_node, instance,
6065
                                             self.op.shutdown_timeout)
6066
    msg = result.fail_msg
6067
    if msg:
6068
      if self.op.ignore_consistency:
6069
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6070
                             " Proceeding anyway. Please make sure node"
6071
                             " %s is down. Error details: %s",
6072
                             instance.name, source_node, source_node, msg)
6073
      else:
6074
        raise errors.OpExecError("Could not shutdown instance %s on"
6075
                                 " node %s: %s" %
6076
                                 (instance.name, source_node, msg))
6077

    
6078
    # create the target disks
6079
    try:
6080
      _CreateDisks(self, instance, target_node=target_node)
6081
    except errors.OpExecError:
6082
      self.LogWarning("Device creation failed, reverting...")
6083
      try:
6084
        _RemoveDisks(self, instance, target_node=target_node)
6085
      finally:
6086
        self.cfg.ReleaseDRBDMinors(instance.name)
6087
        raise
6088

    
6089
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6090

    
6091
    errs = []
6092
    # activate, get path, copy the data over
6093
    for idx, disk in enumerate(instance.disks):
6094
      self.LogInfo("Copying data for disk %d", idx)
6095
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6096
                                               instance.name, True)
6097
      if result.fail_msg:
6098
        self.LogWarning("Can't assemble newly created disk %d: %s",
6099
                        idx, result.fail_msg)
6100
        errs.append(result.fail_msg)
6101
        break
6102
      dev_path = result.payload
6103
      result = self.rpc.call_blockdev_export(source_node, disk,
6104
                                             target_node, dev_path,
6105
                                             cluster_name)
6106
      if result.fail_msg:
6107
        self.LogWarning("Can't copy data over for disk %d: %s",
6108
                        idx, result.fail_msg)
6109
        errs.append(result.fail_msg)
6110
        break
6111

    
6112
    if errs:
6113
      self.LogWarning("Some disks failed to copy, aborting")
6114
      try:
6115
        _RemoveDisks(self, instance, target_node=target_node)
6116
      finally:
6117
        self.cfg.ReleaseDRBDMinors(instance.name)
6118
        raise errors.OpExecError("Errors during disk copy: %s" %
6119
                                 (",".join(errs),))
6120

    
6121
    instance.primary_node = target_node
6122
    self.cfg.Update(instance, feedback_fn)
6123

    
6124
    self.LogInfo("Removing the disks on the original node")
6125
    _RemoveDisks(self, instance, target_node=source_node)
6126

    
6127
    # Only start the instance if it's marked as up
6128
    if instance.admin_up:
6129
      self.LogInfo("Starting instance %s on node %s",
6130
                   instance.name, target_node)
6131

    
6132
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6133
                                           ignore_secondaries=True)
6134
      if not disks_ok:
6135
        _ShutdownInstanceDisks(self, instance)
6136
        raise errors.OpExecError("Can't activate the instance's disks")
6137

    
6138
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6139
      msg = result.fail_msg
6140
      if msg:
6141
        _ShutdownInstanceDisks(self, instance)
6142
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6143
                                 (instance.name, target_node, msg))
6144

    
6145

    
6146
class LUMigrateNode(LogicalUnit):
6147
  """Migrate all instances from a node.
6148

6149
  """
6150
  HPATH = "node-migrate"
6151
  HTYPE = constants.HTYPE_NODE
6152
  _OP_PARAMS = [
6153
    _PNodeName,
6154
    _PMigrationMode,
6155
    _PMigrationLive,
6156
    ]
6157
  REQ_BGL = False
6158

    
6159
  def ExpandNames(self):
6160
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6161

    
6162
    self.needed_locks = {
6163
      locking.LEVEL_NODE: [self.op.node_name],
6164
      }
6165

    
6166
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6167

    
6168
    # Create tasklets for migrating instances for all instances on this node
6169
    names = []
6170
    tasklets = []
6171

    
6172
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6173
      logging.debug("Migrating instance %s", inst.name)
6174
      names.append(inst.name)
6175

    
6176
      tasklets.append(TLMigrateInstance(self, inst.name, False))
6177

    
6178
    self.tasklets = tasklets
6179

    
6180
    # Declare instance locks
6181
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6182

    
6183
  def DeclareLocks(self, level):
6184
    if level == locking.LEVEL_NODE:
6185
      self._LockInstancesNodes()
6186

    
6187
  def BuildHooksEnv(self):
6188
    """Build hooks env.
6189

6190
    This runs on the master, the primary and all the secondaries.
6191

6192
    """
6193
    env = {
6194
      "NODE_NAME": self.op.node_name,
6195
      }
6196

    
6197
    nl = [self.cfg.GetMasterNode()]
6198

    
6199
    return (env, nl, nl)
6200

    
6201

    
6202
class TLMigrateInstance(Tasklet):
6203
  """Tasklet class for instance migration.
6204

6205
  @type live: boolean
6206
  @ivar live: whether the migration will be done live or non-live;
6207
      this variable is initalized only after CheckPrereq has run
6208

6209
  """
6210
  def __init__(self, lu, instance_name, cleanup):
6211
    """Initializes this class.
6212

6213
    """
6214
    Tasklet.__init__(self, lu)
6215

    
6216
    # Parameters
6217
    self.instance_name = instance_name
6218
    self.cleanup = cleanup
6219
    self.live = False # will be overridden later
6220

    
6221
  def CheckPrereq(self):
6222
    """Check prerequisites.
6223

6224
    This checks that the instance is in the cluster.
6225

6226
    """
6227
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6228
    instance = self.cfg.GetInstanceInfo(instance_name)
6229
    assert instance is not None
6230

    
6231
    if instance.disk_template != constants.DT_DRBD8:
6232
      raise errors.OpPrereqError("Instance's disk layout is not"
6233
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6234

    
6235
    secondary_nodes = instance.secondary_nodes
6236
    if not secondary_nodes:
6237
      raise errors.ConfigurationError("No secondary node but using"
6238
                                      " drbd8 disk template")
6239

    
6240
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6241

    
6242
    target_node = secondary_nodes[0]
6243
    # check memory requirements on the secondary node
6244
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6245
                         instance.name, i_be[constants.BE_MEMORY],
6246
                         instance.hypervisor)
6247

    
6248
    # check bridge existance
6249
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6250

    
6251
    if not self.cleanup:
6252
      _CheckNodeNotDrained(self.lu, target_node)
6253
      result = self.rpc.call_instance_migratable(instance.primary_node,
6254
                                                 instance)
6255
      result.Raise("Can't migrate, please use failover",
6256
                   prereq=True, ecode=errors.ECODE_STATE)
6257

    
6258
    self.instance = instance
6259

    
6260
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6261
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6262
                                 " parameters are accepted",
6263
                                 errors.ECODE_INVAL)
6264
    if self.lu.op.live is not None:
6265
      if self.lu.op.live:
6266
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6267
      else:
6268
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6269
      # reset the 'live' parameter to None so that repeated
6270
      # invocations of CheckPrereq do not raise an exception
6271
      self.lu.op.live = None
6272
    elif self.lu.op.mode is None:
6273
      # read the default value from the hypervisor
6274
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6275
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6276

    
6277
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6278

    
6279
  def _WaitUntilSync(self):
6280
    """Poll with custom rpc for disk sync.
6281

6282
    This uses our own step-based rpc call.
6283

6284
    """
6285
    self.feedback_fn("* wait until resync is done")
6286
    all_done = False
6287
    while not all_done:
6288
      all_done = True
6289
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6290
                                            self.nodes_ip,
6291
                                            self.instance.disks)
6292
      min_percent = 100
6293
      for node, nres in result.items():
6294
        nres.Raise("Cannot resync disks on node %s" % node)
6295
        node_done, node_percent = nres.payload
6296
        all_done = all_done and node_done
6297
        if node_percent is not None:
6298
          min_percent = min(min_percent, node_percent)
6299
      if not all_done:
6300
        if min_percent < 100:
6301
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6302
        time.sleep(2)
6303

    
6304
  def _EnsureSecondary(self, node):
6305
    """Demote a node to secondary.
6306

6307
    """
6308
    self.feedback_fn("* switching node %s to secondary mode" % node)
6309

    
6310
    for dev in self.instance.disks:
6311
      self.cfg.SetDiskID(dev, node)
6312

    
6313
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6314
                                          self.instance.disks)
6315
    result.Raise("Cannot change disk to secondary on node %s" % node)
6316

    
6317
  def _GoStandalone(self):
6318
    """Disconnect from the network.
6319

6320
    """
6321
    self.feedback_fn("* changing into standalone mode")
6322
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6323
                                               self.instance.disks)
6324
    for node, nres in result.items():
6325
      nres.Raise("Cannot disconnect disks node %s" % node)
6326

    
6327
  def _GoReconnect(self, multimaster):
6328
    """Reconnect to the network.
6329

6330
    """
6331
    if multimaster:
6332
      msg = "dual-master"
6333
    else:
6334
      msg = "single-master"
6335
    self.feedback_fn("* changing disks into %s mode" % msg)
6336
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6337
                                           self.instance.disks,
6338
                                           self.instance.name, multimaster)
6339
    for node, nres in result.items():
6340
      nres.Raise("Cannot change disks config on node %s" % node)
6341

    
6342
  def _ExecCleanup(self):
6343
    """Try to cleanup after a failed migration.
6344

6345
    The cleanup is done by:
6346
      - check that the instance is running only on one node
6347
        (and update the config if needed)
6348
      - change disks on its secondary node to secondary
6349
      - wait until disks are fully synchronized
6350
      - disconnect from the network
6351
      - change disks into single-master mode
6352
      - wait again until disks are fully synchronized
6353

6354
    """
6355
    instance = self.instance
6356
    target_node = self.target_node
6357
    source_node = self.source_node
6358

    
6359
    # check running on only one node
6360
    self.feedback_fn("* checking where the instance actually runs"
6361
                     " (if this hangs, the hypervisor might be in"
6362
                     " a bad state)")
6363
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6364
    for node, result in ins_l.items():
6365
      result.Raise("Can't contact node %s" % node)
6366

    
6367
    runningon_source = instance.name in ins_l[source_node].payload
6368
    runningon_target = instance.name in ins_l[target_node].payload
6369

    
6370
    if runningon_source and runningon_target:
6371
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6372
                               " or the hypervisor is confused. You will have"
6373
                               " to ensure manually that it runs only on one"
6374
                               " and restart this operation.")
6375

    
6376
    if not (runningon_source or runningon_target):
6377
      raise errors.OpExecError("Instance does not seem to be running at all."
6378
                               " In this case, it's safer to repair by"
6379
                               " running 'gnt-instance stop' to ensure disk"
6380
                               " shutdown, and then restarting it.")
6381

    
6382
    if runningon_target:
6383
      # the migration has actually succeeded, we need to update the config
6384
      self.feedback_fn("* instance running on secondary node (%s),"
6385
                       " updating config" % target_node)
6386
      instance.primary_node = target_node
6387
      self.cfg.Update(instance, self.feedback_fn)
6388
      demoted_node = source_node
6389
    else:
6390
      self.feedback_fn("* instance confirmed to be running on its"
6391
                       " primary node (%s)" % source_node)
6392
      demoted_node = target_node
6393

    
6394
    self._EnsureSecondary(demoted_node)
6395
    try:
6396
      self._WaitUntilSync()
6397
    except errors.OpExecError:
6398
      # we ignore here errors, since if the device is standalone, it
6399
      # won't be able to sync
6400
      pass
6401
    self._GoStandalone()
6402
    self._GoReconnect(False)
6403
    self._WaitUntilSync()
6404

    
6405
    self.feedback_fn("* done")
6406

    
6407
  def _RevertDiskStatus(self):
6408
    """Try to revert the disk status after a failed migration.
6409

6410
    """
6411
    target_node = self.target_node
6412
    try:
6413
      self._EnsureSecondary(target_node)
6414
      self._GoStandalone()
6415
      self._GoReconnect(False)
6416
      self._WaitUntilSync()
6417
    except errors.OpExecError, err:
6418
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6419
                         " drives: error '%s'\n"
6420
                         "Please look and recover the instance status" %
6421
                         str(err))
6422

    
6423
  def _AbortMigration(self):
6424
    """Call the hypervisor code to abort a started migration.
6425

6426
    """
6427
    instance = self.instance
6428
    target_node = self.target_node
6429
    migration_info = self.migration_info
6430

    
6431
    abort_result = self.rpc.call_finalize_migration(target_node,
6432
                                                    instance,
6433
                                                    migration_info,
6434
                                                    False)
6435
    abort_msg = abort_result.fail_msg
6436
    if abort_msg:
6437
      logging.error("Aborting migration failed on target node %s: %s",
6438
                    target_node, abort_msg)
6439
      # Don't raise an exception here, as we stil have to try to revert the
6440
      # disk status, even if this step failed.
6441

    
6442
  def _ExecMigration(self):
6443
    """Migrate an instance.
6444

6445
    The migrate is done by:
6446
      - change the disks into dual-master mode
6447
      - wait until disks are fully synchronized again
6448
      - migrate the instance
6449
      - change disks on the new secondary node (the old primary) to secondary
6450
      - wait until disks are fully synchronized
6451
      - change disks into single-master mode
6452

6453
    """
6454
    instance = self.instance
6455
    target_node = self.target_node
6456
    source_node = self.source_node
6457

    
6458
    self.feedback_fn("* checking disk consistency between source and target")
6459
    for dev in instance.disks:
6460
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6461
        raise errors.OpExecError("Disk %s is degraded or not fully"
6462
                                 " synchronized on target node,"
6463
                                 " aborting migrate." % dev.iv_name)
6464

    
6465
    # First get the migration information from the remote node
6466
    result = self.rpc.call_migration_info(source_node, instance)
6467
    msg = result.fail_msg
6468
    if msg:
6469
      log_err = ("Failed fetching source migration information from %s: %s" %
6470
                 (source_node, msg))
6471
      logging.error(log_err)
6472
      raise errors.OpExecError(log_err)
6473

    
6474
    self.migration_info = migration_info = result.payload
6475

    
6476
    # Then switch the disks to master/master mode
6477
    self._EnsureSecondary(target_node)
6478
    self._GoStandalone()
6479
    self._GoReconnect(True)
6480
    self._WaitUntilSync()
6481

    
6482
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6483
    result = self.rpc.call_accept_instance(target_node,
6484
                                           instance,
6485
                                           migration_info,
6486
                                           self.nodes_ip[target_node])
6487

    
6488
    msg = result.fail_msg
6489
    if msg:
6490
      logging.error("Instance pre-migration failed, trying to revert"
6491
                    " disk status: %s", msg)
6492
      self.feedback_fn("Pre-migration failed, aborting")
6493
      self._AbortMigration()
6494
      self._RevertDiskStatus()
6495
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6496
                               (instance.name, msg))
6497

    
6498
    self.feedback_fn("* migrating instance to %s" % target_node)
6499
    time.sleep(10)
6500
    result = self.rpc.call_instance_migrate(source_node, instance,
6501
                                            self.nodes_ip[target_node],
6502
                                            self.live)
6503
    msg = result.fail_msg
6504
    if msg:
6505
      logging.error("Instance migration failed, trying to revert"
6506
                    " disk status: %s", msg)
6507
      self.feedback_fn("Migration failed, aborting")
6508
      self._AbortMigration()
6509
      self._RevertDiskStatus()
6510
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6511
                               (instance.name, msg))
6512
    time.sleep(10)
6513

    
6514
    instance.primary_node = target_node
6515
    # distribute new instance config to the other nodes
6516
    self.cfg.Update(instance, self.feedback_fn)
6517

    
6518
    result = self.rpc.call_finalize_migration(target_node,
6519
                                              instance,
6520
                                              migration_info,
6521
                                              True)
6522
    msg = result.fail_msg
6523
    if msg:
6524
      logging.error("Instance migration succeeded, but finalization failed:"
6525
                    " %s", msg)
6526
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6527
                               msg)
6528

    
6529
    self._EnsureSecondary(source_node)
6530
    self._WaitUntilSync()
6531
    self._GoStandalone()
6532
    self._GoReconnect(False)
6533
    self._WaitUntilSync()
6534

    
6535
    self.feedback_fn("* done")
6536

    
6537
  def Exec(self, feedback_fn):
6538
    """Perform the migration.
6539

6540
    """
6541
    feedback_fn("Migrating instance %s" % self.instance.name)
6542

    
6543
    self.feedback_fn = feedback_fn
6544

    
6545
    self.source_node = self.instance.primary_node
6546
    self.target_node = self.instance.secondary_nodes[0]
6547
    self.all_nodes = [self.source_node, self.target_node]
6548
    self.nodes_ip = {
6549
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6550
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6551
      }
6552

    
6553
    if self.cleanup:
6554
      return self._ExecCleanup()
6555
    else:
6556
      return self._ExecMigration()
6557

    
6558

    
6559
def _CreateBlockDev(lu, node, instance, device, force_create,
6560
                    info, force_open):
6561
  """Create a tree of block devices on a given node.
6562

6563
  If this device type has to be created on secondaries, create it and
6564
  all its children.
6565

6566
  If not, just recurse to children keeping the same 'force' value.
6567

6568
  @param lu: the lu on whose behalf we execute
6569
  @param node: the node on which to create the device
6570
  @type instance: L{objects.Instance}
6571
  @param instance: the instance which owns the device
6572
  @type device: L{objects.Disk}
6573
  @param device: the device to create
6574
  @type force_create: boolean
6575
  @param force_create: whether to force creation of this device; this
6576
      will be change to True whenever we find a device which has
6577
      CreateOnSecondary() attribute
6578
  @param info: the extra 'metadata' we should attach to the device
6579
      (this will be represented as a LVM tag)
6580
  @type force_open: boolean
6581
  @param force_open: this parameter will be passes to the
6582
      L{backend.BlockdevCreate} function where it specifies
6583
      whether we run on primary or not, and it affects both
6584
      the child assembly and the device own Open() execution
6585

6586
  """
6587
  if device.CreateOnSecondary():
6588
    force_create = True
6589

    
6590
  if device.children:
6591
    for child in device.children:
6592
      _CreateBlockDev(lu, node, instance, child, force_create,
6593
                      info, force_open)
6594

    
6595
  if not force_create:
6596
    return
6597

    
6598
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6599

    
6600

    
6601
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6602
  """Create a single block device on a given node.
6603

6604
  This will not recurse over children of the device, so they must be
6605
  created in advance.
6606

6607
  @param lu: the lu on whose behalf we execute
6608
  @param node: the node on which to create the device
6609
  @type instance: L{objects.Instance}
6610
  @param instance: the instance which owns the device
6611
  @type device: L{objects.Disk}
6612
  @param device: the device to create
6613
  @param info: the extra 'metadata' we should attach to the device
6614
      (this will be represented as a LVM tag)
6615
  @type force_open: boolean
6616
  @param force_open: this parameter will be passes to the
6617
      L{backend.BlockdevCreate} function where it specifies
6618
      whether we run on primary or not, and it affects both
6619
      the child assembly and the device own Open() execution
6620

6621
  """
6622
  lu.cfg.SetDiskID(device, node)
6623
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6624
                                       instance.name, force_open, info)
6625
  result.Raise("Can't create block device %s on"
6626
               " node %s for instance %s" % (device, node, instance.name))
6627
  if device.physical_id is None:
6628
    device.physical_id = result.payload
6629

    
6630

    
6631
def _GenerateUniqueNames(lu, exts):
6632
  """Generate a suitable LV name.
6633

6634
  This will generate a logical volume name for the given instance.
6635

6636
  """
6637
  results = []
6638
  for val in exts:
6639
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6640
    results.append("%s%s" % (new_id, val))
6641
  return results
6642

    
6643

    
6644
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6645
                         p_minor, s_minor):
6646
  """Generate a drbd8 device complete with its children.
6647

6648
  """
6649
  port = lu.cfg.AllocatePort()
6650
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6651
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6652
                          logical_id=(vgname, names[0]))
6653
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6654
                          logical_id=(vgname, names[1]))
6655
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6656
                          logical_id=(primary, secondary, port,
6657
                                      p_minor, s_minor,
6658
                                      shared_secret),
6659
                          children=[dev_data, dev_meta],
6660
                          iv_name=iv_name)
6661
  return drbd_dev
6662

    
6663

    
6664
def _GenerateDiskTemplate(lu, template_name,
6665
                          instance_name, primary_node,
6666
                          secondary_nodes, disk_info,
6667
                          file_storage_dir, file_driver,
6668
                          base_index, feedback_fn):
6669
  """Generate the entire disk layout for a given template type.
6670

6671
  """
6672
  #TODO: compute space requirements
6673

    
6674
  vgname = lu.cfg.GetVGName()
6675
  disk_count = len(disk_info)
6676
  disks = []
6677
  if template_name == constants.DT_DISKLESS:
6678
    pass
6679
  elif template_name == constants.DT_PLAIN:
6680
    if len(secondary_nodes) != 0:
6681
      raise errors.ProgrammerError("Wrong template configuration")
6682

    
6683
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6684
                                      for i in range(disk_count)])
6685
    for idx, disk in enumerate(disk_info):
6686
      disk_index = idx + base_index
6687
      vg = disk.get("vg", vgname)
6688
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6689
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6690
                              logical_id=(vg, names[idx]),
6691
                              iv_name="disk/%d" % disk_index,
6692
                              mode=disk["mode"])
6693
      disks.append(disk_dev)
6694
  elif template_name == constants.DT_DRBD8:
6695
    if len(secondary_nodes) != 1:
6696
      raise errors.ProgrammerError("Wrong template configuration")
6697
    remote_node = secondary_nodes[0]
6698
    minors = lu.cfg.AllocateDRBDMinor(
6699
      [primary_node, remote_node] * len(disk_info), instance_name)
6700

    
6701
    names = []
6702
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6703
                                               for i in range(disk_count)]):
6704
      names.append(lv_prefix + "_data")
6705
      names.append(lv_prefix + "_meta")
6706
    for idx, disk in enumerate(disk_info):
6707
      disk_index = idx + base_index
6708
      vg = disk.get("vg", vgname)
6709
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6710
                                      disk["size"], vg, names[idx*2:idx*2+2],
6711
                                      "disk/%d" % disk_index,
6712
                                      minors[idx*2], minors[idx*2+1])
6713
      disk_dev.mode = disk["mode"]
6714
      disks.append(disk_dev)
6715
  elif template_name == constants.DT_FILE:
6716
    if len(secondary_nodes) != 0:
6717
      raise errors.ProgrammerError("Wrong template configuration")
6718

    
6719
    _RequireFileStorage()
6720

    
6721
    for idx, disk in enumerate(disk_info):
6722
      disk_index = idx + base_index
6723
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6724
                              iv_name="disk/%d" % disk_index,
6725
                              logical_id=(file_driver,
6726
                                          "%s/disk%d" % (file_storage_dir,
6727
                                                         disk_index)),
6728
                              mode=disk["mode"])
6729
      disks.append(disk_dev)
6730
  else:
6731
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6732
  return disks
6733

    
6734

    
6735
def _GetInstanceInfoText(instance):
6736
  """Compute that text that should be added to the disk's metadata.
6737

6738
  """
6739
  return "originstname+%s" % instance.name
6740

    
6741

    
6742
def _CalcEta(time_taken, written, total_size):
6743
  """Calculates the ETA based on size written and total size.
6744

6745
  @param time_taken: The time taken so far
6746
  @param written: amount written so far
6747
  @param total_size: The total size of data to be written
6748
  @return: The remaining time in seconds
6749

6750
  """
6751
  avg_time = time_taken / float(written)
6752
  return (total_size - written) * avg_time
6753

    
6754

    
6755
def _WipeDisks(lu, instance):
6756
  """Wipes instance disks.
6757

6758
  @type lu: L{LogicalUnit}
6759
  @param lu: the logical unit on whose behalf we execute
6760
  @type instance: L{objects.Instance}
6761
  @param instance: the instance whose disks we should create
6762
  @return: the success of the wipe
6763

6764
  """
6765
  node = instance.primary_node
6766
  for idx, device in enumerate(instance.disks):
6767
    lu.LogInfo("* Wiping disk %d", idx)
6768
    logging.info("Wiping disk %d for instance %s", idx, instance.name)
6769

    
6770
    # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6771
    # MAX_WIPE_CHUNK at max
6772
    wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6773
                          constants.MIN_WIPE_CHUNK_PERCENT)
6774

    
6775
    offset = 0
6776
    size = device.size
6777
    last_output = 0
6778
    start_time = time.time()
6779

    
6780
    while offset < size:
6781
      wipe_size = min(wipe_chunk_size, size - offset)
6782
      result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6783
      result.Raise("Could not wipe disk %d at offset %d for size %d" %
6784
                   (idx, offset, wipe_size))
6785
      now = time.time()
6786
      offset += wipe_size
6787
      if now - last_output >= 60:
6788
        eta = _CalcEta(now - start_time, offset, size)
6789
        lu.LogInfo(" - done: %.1f%% ETA: %s" %
6790
                   (offset / float(size) * 100, utils.FormatSeconds(eta)))
6791
        last_output = now
6792

    
6793

    
6794
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6795
  """Create all disks for an instance.
6796

6797
  This abstracts away some work from AddInstance.
6798

6799
  @type lu: L{LogicalUnit}
6800
  @param lu: the logical unit on whose behalf we execute
6801
  @type instance: L{objects.Instance}
6802
  @param instance: the instance whose disks we should create
6803
  @type to_skip: list
6804
  @param to_skip: list of indices to skip
6805
  @type target_node: string
6806
  @param target_node: if passed, overrides the target node for creation
6807
  @rtype: boolean
6808
  @return: the success of the creation
6809

6810
  """
6811
  info = _GetInstanceInfoText(instance)
6812
  if target_node is None:
6813
    pnode = instance.primary_node
6814
    all_nodes = instance.all_nodes
6815
  else:
6816
    pnode = target_node
6817
    all_nodes = [pnode]
6818

    
6819
  if instance.disk_template == constants.DT_FILE:
6820
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6821
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6822

    
6823
    result.Raise("Failed to create directory '%s' on"
6824
                 " node %s" % (file_storage_dir, pnode))
6825

    
6826
  # Note: this needs to be kept in sync with adding of disks in
6827
  # LUSetInstanceParams
6828
  for idx, device in enumerate(instance.disks):
6829
    if to_skip and idx in to_skip:
6830
      continue
6831
    logging.info("Creating volume %s for instance %s",
6832
                 device.iv_name, instance.name)
6833
    #HARDCODE
6834
    for node in all_nodes:
6835
      f_create = node == pnode
6836
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6837

    
6838

    
6839
def _RemoveDisks(lu, instance, target_node=None):
6840
  """Remove all disks for an instance.
6841

6842
  This abstracts away some work from `AddInstance()` and
6843
  `RemoveInstance()`. Note that in case some of the devices couldn't
6844
  be removed, the removal will continue with the other ones (compare
6845
  with `_CreateDisks()`).
6846

6847
  @type lu: L{LogicalUnit}
6848
  @param lu: the logical unit on whose behalf we execute
6849
  @type instance: L{objects.Instance}
6850
  @param instance: the instance whose disks we should remove
6851
  @type target_node: string
6852
  @param target_node: used to override the node on which to remove the disks
6853
  @rtype: boolean
6854
  @return: the success of the removal
6855

6856
  """
6857
  logging.info("Removing block devices for instance %s", instance.name)
6858

    
6859
  all_result = True
6860
  for device in instance.disks:
6861
    if target_node:
6862
      edata = [(target_node, device)]
6863
    else:
6864
      edata = device.ComputeNodeTree(instance.primary_node)
6865
    for node, disk in edata:
6866
      lu.cfg.SetDiskID(disk, node)
6867
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6868
      if msg:
6869
        lu.LogWarning("Could not remove block device %s on node %s,"
6870
                      " continuing anyway: %s", device.iv_name, node, msg)
6871
        all_result = False
6872

    
6873
  if instance.disk_template == constants.DT_FILE:
6874
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6875
    if target_node:
6876
      tgt = target_node
6877
    else:
6878
      tgt = instance.primary_node
6879
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6880
    if result.fail_msg:
6881
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6882
                    file_storage_dir, instance.primary_node, result.fail_msg)
6883
      all_result = False
6884

    
6885
  return all_result
6886

    
6887

    
6888
def _ComputeDiskSizePerVG(disk_template, disks):
6889
  """Compute disk size requirements in the volume group
6890

6891
  """
6892
  def _compute(disks, payload):
6893
    """Universal algorithm
6894

6895
    """
6896
    vgs = {}
6897
    for disk in disks:
6898
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
6899

    
6900
    return vgs
6901

    
6902
  # Required free disk space as a function of disk and swap space
6903
  req_size_dict = {
6904
    constants.DT_DISKLESS: None,
6905
    constants.DT_PLAIN: _compute(disks, 0),
6906
    # 128 MB are added for drbd metadata for each disk
6907
    constants.DT_DRBD8: _compute(disks, 128),
6908
    constants.DT_FILE: None,
6909
  }
6910

    
6911
  if disk_template not in req_size_dict:
6912
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6913
                                 " is unknown" %  disk_template)
6914

    
6915
  return req_size_dict[disk_template]
6916

    
6917
def _ComputeDiskSize(disk_template, disks):
6918
  """Compute disk size requirements in the volume group
6919

6920
  """
6921
  # Required free disk space as a function of disk and swap space
6922
  req_size_dict = {
6923
    constants.DT_DISKLESS: None,
6924
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6925
    # 128 MB are added for drbd metadata for each disk
6926
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6927
    constants.DT_FILE: None,
6928
  }
6929

    
6930
  if disk_template not in req_size_dict:
6931
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6932
                                 " is unknown" %  disk_template)
6933

    
6934
  return req_size_dict[disk_template]
6935

    
6936

    
6937
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6938
  """Hypervisor parameter validation.
6939

6940
  This function abstract the hypervisor parameter validation to be
6941
  used in both instance create and instance modify.
6942

6943
  @type lu: L{LogicalUnit}
6944
  @param lu: the logical unit for which we check
6945
  @type nodenames: list
6946
  @param nodenames: the list of nodes on which we should check
6947
  @type hvname: string
6948
  @param hvname: the name of the hypervisor we should use
6949
  @type hvparams: dict
6950
  @param hvparams: the parameters which we need to check
6951
  @raise errors.OpPrereqError: if the parameters are not valid
6952

6953
  """
6954
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6955
                                                  hvname,
6956
                                                  hvparams)
6957
  for node in nodenames:
6958
    info = hvinfo[node]
6959
    if info.offline:
6960
      continue
6961
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6962

    
6963

    
6964
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6965
  """OS parameters validation.
6966

6967
  @type lu: L{LogicalUnit}
6968
  @param lu: the logical unit for which we check
6969
  @type required: boolean
6970
  @param required: whether the validation should fail if the OS is not
6971
      found
6972
  @type nodenames: list
6973
  @param nodenames: the list of nodes on which we should check
6974
  @type osname: string
6975
  @param osname: the name of the hypervisor we should use
6976
  @type osparams: dict
6977
  @param osparams: the parameters which we need to check
6978
  @raise errors.OpPrereqError: if the parameters are not valid
6979

6980
  """
6981
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6982
                                   [constants.OS_VALIDATE_PARAMETERS],
6983
                                   osparams)
6984
  for node, nres in result.items():
6985
    # we don't check for offline cases since this should be run only
6986
    # against the master node and/or an instance's nodes
6987
    nres.Raise("OS Parameters validation failed on node %s" % node)
6988
    if not nres.payload:
6989
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6990
                 osname, node)
6991

    
6992

    
6993
class LUCreateInstance(LogicalUnit):
6994
  """Create an instance.
6995

6996
  """
6997
  HPATH = "instance-add"
6998
  HTYPE = constants.HTYPE_INSTANCE
6999
  _OP_PARAMS = [
7000
    _PInstanceName,
7001
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES)),
7002
    ("start", True, ht.TBool),
7003
    ("wait_for_sync", True, ht.TBool),
7004
    ("ip_check", True, ht.TBool),
7005
    ("name_check", True, ht.TBool),
7006
    ("disks", ht.NoDefault, ht.TListOf(ht.TDict)),
7007
    ("nics", ht.NoDefault, ht.TListOf(ht.TDict)),
7008
    ("hvparams", ht.EmptyDict, ht.TDict),
7009
    ("beparams", ht.EmptyDict, ht.TDict),
7010
    ("osparams", ht.EmptyDict, ht.TDict),
7011
    ("no_install", None, ht.TMaybeBool),
7012
    ("os_type", None, ht.TMaybeString),
7013
    ("force_variant", False, ht.TBool),
7014
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone)),
7015
    ("source_x509_ca", None, ht.TMaybeString),
7016
    ("source_instance_name", None, ht.TMaybeString),
7017
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
7018
     ht.TPositiveInt),
7019
    ("src_node", None, ht.TMaybeString),
7020
    ("src_path", None, ht.TMaybeString),
7021
    ("pnode", None, ht.TMaybeString),
7022
    ("snode", None, ht.TMaybeString),
7023
    ("iallocator", None, ht.TMaybeString),
7024
    ("hypervisor", None, ht.TMaybeString),
7025
    ("disk_template", ht.NoDefault, _CheckDiskTemplate),
7026
    ("identify_defaults", False, ht.TBool),
7027
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER))),
7028
    ("file_storage_dir", None, ht.TMaybeString),
7029
    ]
7030
  REQ_BGL = False
7031

    
7032
  def CheckArguments(self):
7033
    """Check arguments.
7034

7035
    """
7036
    # do not require name_check to ease forward/backward compatibility
7037
    # for tools
7038
    if self.op.no_install and self.op.start:
7039
      self.LogInfo("No-installation mode selected, disabling startup")
7040
      self.op.start = False
7041
    # validate/normalize the instance name
7042
    self.op.instance_name = \
7043
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7044

    
7045
    if self.op.ip_check and not self.op.name_check:
7046
      # TODO: make the ip check more flexible and not depend on the name check
7047
      raise errors.OpPrereqError("Cannot do ip check without a name check",
7048
                                 errors.ECODE_INVAL)
7049

    
7050
    # check nics' parameter names
7051
    for nic in self.op.nics:
7052
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7053

    
7054
    # check disks. parameter names and consistent adopt/no-adopt strategy
7055
    has_adopt = has_no_adopt = False
7056
    for disk in self.op.disks:
7057
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7058
      if "adopt" in disk:
7059
        has_adopt = True
7060
      else:
7061
        has_no_adopt = True
7062
    if has_adopt and has_no_adopt:
7063
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7064
                                 errors.ECODE_INVAL)
7065
    if has_adopt:
7066
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7067
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7068
                                   " '%s' disk template" %
7069
                                   self.op.disk_template,
7070
                                   errors.ECODE_INVAL)
7071
      if self.op.iallocator is not None:
7072
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7073
                                   " iallocator script", errors.ECODE_INVAL)
7074
      if self.op.mode == constants.INSTANCE_IMPORT:
7075
        raise errors.OpPrereqError("Disk adoption not allowed for"
7076
                                   " instance import", errors.ECODE_INVAL)
7077

    
7078
    self.adopt_disks = has_adopt
7079

    
7080
    # instance name verification
7081
    if self.op.name_check:
7082
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7083
      self.op.instance_name = self.hostname1.name
7084
      # used in CheckPrereq for ip ping check
7085
      self.check_ip = self.hostname1.ip
7086
    else:
7087
      self.check_ip = None
7088

    
7089
    # file storage checks
7090
    if (self.op.file_driver and
7091
        not self.op.file_driver in constants.FILE_DRIVER):
7092
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7093
                                 self.op.file_driver, errors.ECODE_INVAL)
7094

    
7095
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7096
      raise errors.OpPrereqError("File storage directory path not absolute",
7097
                                 errors.ECODE_INVAL)
7098

    
7099
    ### Node/iallocator related checks
7100
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7101

    
7102
    if self.op.pnode is not None:
7103
      if self.op.disk_template in constants.DTS_NET_MIRROR:
7104
        if self.op.snode is None:
7105
          raise errors.OpPrereqError("The networked disk templates need"
7106
                                     " a mirror node", errors.ECODE_INVAL)
7107
      elif self.op.snode:
7108
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7109
                        " template")
7110
        self.op.snode = None
7111

    
7112
    self._cds = _GetClusterDomainSecret()
7113

    
7114
    if self.op.mode == constants.INSTANCE_IMPORT:
7115
      # On import force_variant must be True, because if we forced it at
7116
      # initial install, our only chance when importing it back is that it
7117
      # works again!
7118
      self.op.force_variant = True
7119

    
7120
      if self.op.no_install:
7121
        self.LogInfo("No-installation mode has no effect during import")
7122

    
7123
    elif self.op.mode == constants.INSTANCE_CREATE:
7124
      if self.op.os_type is None:
7125
        raise errors.OpPrereqError("No guest OS specified",
7126
                                   errors.ECODE_INVAL)
7127
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7128
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7129
                                   " installation" % self.op.os_type,
7130
                                   errors.ECODE_STATE)
7131
      if self.op.disk_template is None:
7132
        raise errors.OpPrereqError("No disk template specified",
7133
                                   errors.ECODE_INVAL)
7134

    
7135
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7136
      # Check handshake to ensure both clusters have the same domain secret
7137
      src_handshake = self.op.source_handshake
7138
      if not src_handshake:
7139
        raise errors.OpPrereqError("Missing source handshake",
7140
                                   errors.ECODE_INVAL)
7141

    
7142
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7143
                                                           src_handshake)
7144
      if errmsg:
7145
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7146
                                   errors.ECODE_INVAL)
7147

    
7148
      # Load and check source CA
7149
      self.source_x509_ca_pem = self.op.source_x509_ca
7150
      if not self.source_x509_ca_pem:
7151
        raise errors.OpPrereqError("Missing source X509 CA",
7152
                                   errors.ECODE_INVAL)
7153

    
7154
      try:
7155
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7156
                                                    self._cds)
7157
      except OpenSSL.crypto.Error, err:
7158
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7159
                                   (err, ), errors.ECODE_INVAL)
7160

    
7161
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7162
      if errcode is not None:
7163
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7164
                                   errors.ECODE_INVAL)
7165

    
7166
      self.source_x509_ca = cert
7167

    
7168
      src_instance_name = self.op.source_instance_name
7169
      if not src_instance_name:
7170
        raise errors.OpPrereqError("Missing source instance name",
7171
                                   errors.ECODE_INVAL)
7172

    
7173
      self.source_instance_name = \
7174
          netutils.GetHostname(name=src_instance_name).name
7175

    
7176
    else:
7177
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7178
                                 self.op.mode, errors.ECODE_INVAL)
7179

    
7180
  def ExpandNames(self):
7181
    """ExpandNames for CreateInstance.
7182

7183
    Figure out the right locks for instance creation.
7184

7185
    """
7186
    self.needed_locks = {}
7187

    
7188
    instance_name = self.op.instance_name
7189
    # this is just a preventive check, but someone might still add this
7190
    # instance in the meantime, and creation will fail at lock-add time
7191
    if instance_name in self.cfg.GetInstanceList():
7192
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7193
                                 instance_name, errors.ECODE_EXISTS)
7194

    
7195
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7196

    
7197
    if self.op.iallocator:
7198
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7199
    else:
7200
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7201
      nodelist = [self.op.pnode]
7202
      if self.op.snode is not None:
7203
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7204
        nodelist.append(self.op.snode)
7205
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7206

    
7207
    # in case of import lock the source node too
7208
    if self.op.mode == constants.INSTANCE_IMPORT:
7209
      src_node = self.op.src_node
7210
      src_path = self.op.src_path
7211

    
7212
      if src_path is None:
7213
        self.op.src_path = src_path = self.op.instance_name
7214

    
7215
      if src_node is None:
7216
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7217
        self.op.src_node = None
7218
        if os.path.isabs(src_path):
7219
          raise errors.OpPrereqError("Importing an instance from an absolute"
7220
                                     " path requires a source node option.",
7221
                                     errors.ECODE_INVAL)
7222
      else:
7223
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7224
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7225
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7226
        if not os.path.isabs(src_path):
7227
          self.op.src_path = src_path = \
7228
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7229

    
7230
  def _RunAllocator(self):
7231
    """Run the allocator based on input opcode.
7232

7233
    """
7234
    nics = [n.ToDict() for n in self.nics]
7235
    ial = IAllocator(self.cfg, self.rpc,
7236
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7237
                     name=self.op.instance_name,
7238
                     disk_template=self.op.disk_template,
7239
                     tags=[],
7240
                     os=self.op.os_type,
7241
                     vcpus=self.be_full[constants.BE_VCPUS],
7242
                     mem_size=self.be_full[constants.BE_MEMORY],
7243
                     disks=self.disks,
7244
                     nics=nics,
7245
                     hypervisor=self.op.hypervisor,
7246
                     )
7247

    
7248
    ial.Run(self.op.iallocator)
7249

    
7250
    if not ial.success:
7251
      raise errors.OpPrereqError("Can't compute nodes using"
7252
                                 " iallocator '%s': %s" %
7253
                                 (self.op.iallocator, ial.info),
7254
                                 errors.ECODE_NORES)
7255
    if len(ial.result) != ial.required_nodes:
7256
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7257
                                 " of nodes (%s), required %s" %
7258
                                 (self.op.iallocator, len(ial.result),
7259
                                  ial.required_nodes), errors.ECODE_FAULT)
7260
    self.op.pnode = ial.result[0]
7261
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7262
                 self.op.instance_name, self.op.iallocator,
7263
                 utils.CommaJoin(ial.result))
7264
    if ial.required_nodes == 2:
7265
      self.op.snode = ial.result[1]
7266

    
7267
  def BuildHooksEnv(self):
7268
    """Build hooks env.
7269

7270
    This runs on master, primary and secondary nodes of the instance.
7271

7272
    """
7273
    env = {
7274
      "ADD_MODE": self.op.mode,
7275
      }
7276
    if self.op.mode == constants.INSTANCE_IMPORT:
7277
      env["SRC_NODE"] = self.op.src_node
7278
      env["SRC_PATH"] = self.op.src_path
7279
      env["SRC_IMAGES"] = self.src_images
7280

    
7281
    env.update(_BuildInstanceHookEnv(
7282
      name=self.op.instance_name,
7283
      primary_node=self.op.pnode,
7284
      secondary_nodes=self.secondaries,
7285
      status=self.op.start,
7286
      os_type=self.op.os_type,
7287
      memory=self.be_full[constants.BE_MEMORY],
7288
      vcpus=self.be_full[constants.BE_VCPUS],
7289
      nics=_NICListToTuple(self, self.nics),
7290
      disk_template=self.op.disk_template,
7291
      disks=[(d["size"], d["mode"]) for d in self.disks],
7292
      bep=self.be_full,
7293
      hvp=self.hv_full,
7294
      hypervisor_name=self.op.hypervisor,
7295
    ))
7296

    
7297
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7298
          self.secondaries)
7299
    return env, nl, nl
7300

    
7301
  def _ReadExportInfo(self):
7302
    """Reads the export information from disk.
7303

7304
    It will override the opcode source node and path with the actual
7305
    information, if these two were not specified before.
7306

7307
    @return: the export information
7308

7309
    """
7310
    assert self.op.mode == constants.INSTANCE_IMPORT
7311

    
7312
    src_node = self.op.src_node
7313
    src_path = self.op.src_path
7314

    
7315
    if src_node is None:
7316
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7317
      exp_list = self.rpc.call_export_list(locked_nodes)
7318
      found = False
7319
      for node in exp_list:
7320
        if exp_list[node].fail_msg:
7321
          continue
7322
        if src_path in exp_list[node].payload:
7323
          found = True
7324
          self.op.src_node = src_node = node
7325
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7326
                                                       src_path)
7327
          break
7328
      if not found:
7329
        raise errors.OpPrereqError("No export found for relative path %s" %
7330
                                    src_path, errors.ECODE_INVAL)
7331

    
7332
    _CheckNodeOnline(self, src_node)
7333
    result = self.rpc.call_export_info(src_node, src_path)
7334
    result.Raise("No export or invalid export found in dir %s" % src_path)
7335

    
7336
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7337
    if not export_info.has_section(constants.INISECT_EXP):
7338
      raise errors.ProgrammerError("Corrupted export config",
7339
                                   errors.ECODE_ENVIRON)
7340

    
7341
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7342
    if (int(ei_version) != constants.EXPORT_VERSION):
7343
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7344
                                 (ei_version, constants.EXPORT_VERSION),
7345
                                 errors.ECODE_ENVIRON)
7346
    return export_info
7347

    
7348
  def _ReadExportParams(self, einfo):
7349
    """Use export parameters as defaults.
7350

7351
    In case the opcode doesn't specify (as in override) some instance
7352
    parameters, then try to use them from the export information, if
7353
    that declares them.
7354

7355
    """
7356
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7357

    
7358
    if self.op.disk_template is None:
7359
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7360
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7361
                                          "disk_template")
7362
      else:
7363
        raise errors.OpPrereqError("No disk template specified and the export"
7364
                                   " is missing the disk_template information",
7365
                                   errors.ECODE_INVAL)
7366

    
7367
    if not self.op.disks:
7368
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7369
        disks = []
7370
        # TODO: import the disk iv_name too
7371
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7372
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7373
          disks.append({"size": disk_sz})
7374
        self.op.disks = disks
7375
      else:
7376
        raise errors.OpPrereqError("No disk info specified and the export"
7377
                                   " is missing the disk information",
7378
                                   errors.ECODE_INVAL)
7379

    
7380
    if (not self.op.nics and
7381
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7382
      nics = []
7383
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7384
        ndict = {}
7385
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7386
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7387
          ndict[name] = v
7388
        nics.append(ndict)
7389
      self.op.nics = nics
7390

    
7391
    if (self.op.hypervisor is None and
7392
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7393
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7394
    if einfo.has_section(constants.INISECT_HYP):
7395
      # use the export parameters but do not override the ones
7396
      # specified by the user
7397
      for name, value in einfo.items(constants.INISECT_HYP):
7398
        if name not in self.op.hvparams:
7399
          self.op.hvparams[name] = value
7400

    
7401
    if einfo.has_section(constants.INISECT_BEP):
7402
      # use the parameters, without overriding
7403
      for name, value in einfo.items(constants.INISECT_BEP):
7404
        if name not in self.op.beparams:
7405
          self.op.beparams[name] = value
7406
    else:
7407
      # try to read the parameters old style, from the main section
7408
      for name in constants.BES_PARAMETERS:
7409
        if (name not in self.op.beparams and
7410
            einfo.has_option(constants.INISECT_INS, name)):
7411
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7412

    
7413
    if einfo.has_section(constants.INISECT_OSP):
7414
      # use the parameters, without overriding
7415
      for name, value in einfo.items(constants.INISECT_OSP):
7416
        if name not in self.op.osparams:
7417
          self.op.osparams[name] = value
7418

    
7419
  def _RevertToDefaults(self, cluster):
7420
    """Revert the instance parameters to the default values.
7421

7422
    """
7423
    # hvparams
7424
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7425
    for name in self.op.hvparams.keys():
7426
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7427
        del self.op.hvparams[name]
7428
    # beparams
7429
    be_defs = cluster.SimpleFillBE({})
7430
    for name in self.op.beparams.keys():
7431
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7432
        del self.op.beparams[name]
7433
    # nic params
7434
    nic_defs = cluster.SimpleFillNIC({})
7435
    for nic in self.op.nics:
7436
      for name in constants.NICS_PARAMETERS:
7437
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7438
          del nic[name]
7439
    # osparams
7440
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7441
    for name in self.op.osparams.keys():
7442
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7443
        del self.op.osparams[name]
7444

    
7445
  def CheckPrereq(self):
7446
    """Check prerequisites.
7447

7448
    """
7449
    if self.op.mode == constants.INSTANCE_IMPORT:
7450
      export_info = self._ReadExportInfo()
7451
      self._ReadExportParams(export_info)
7452

    
7453
    _CheckDiskTemplate(self.op.disk_template)
7454

    
7455
    if (not self.cfg.GetVGName() and
7456
        self.op.disk_template not in constants.DTS_NOT_LVM):
7457
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7458
                                 " instances", errors.ECODE_STATE)
7459

    
7460
    if self.op.hypervisor is None:
7461
      self.op.hypervisor = self.cfg.GetHypervisorType()
7462

    
7463
    cluster = self.cfg.GetClusterInfo()
7464
    enabled_hvs = cluster.enabled_hypervisors
7465
    if self.op.hypervisor not in enabled_hvs:
7466
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7467
                                 " cluster (%s)" % (self.op.hypervisor,
7468
                                  ",".join(enabled_hvs)),
7469
                                 errors.ECODE_STATE)
7470

    
7471
    # check hypervisor parameter syntax (locally)
7472
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7473
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7474
                                      self.op.hvparams)
7475
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7476
    hv_type.CheckParameterSyntax(filled_hvp)
7477
    self.hv_full = filled_hvp
7478
    # check that we don't specify global parameters on an instance
7479
    _CheckGlobalHvParams(self.op.hvparams)
7480

    
7481
    # fill and remember the beparams dict
7482
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7483
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7484

    
7485
    # build os parameters
7486
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7487

    
7488
    # now that hvp/bep are in final format, let's reset to defaults,
7489
    # if told to do so
7490
    if self.op.identify_defaults:
7491
      self._RevertToDefaults(cluster)
7492

    
7493
    # NIC buildup
7494
    self.nics = []
7495
    for idx, nic in enumerate(self.op.nics):
7496
      nic_mode_req = nic.get("mode", None)
7497
      nic_mode = nic_mode_req
7498
      if nic_mode is None:
7499
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7500

    
7501
      # in routed mode, for the first nic, the default ip is 'auto'
7502
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7503
        default_ip_mode = constants.VALUE_AUTO
7504
      else:
7505
        default_ip_mode = constants.VALUE_NONE
7506

    
7507
      # ip validity checks
7508
      ip = nic.get("ip", default_ip_mode)
7509
      if ip is None or ip.lower() == constants.VALUE_NONE:
7510
        nic_ip = None
7511
      elif ip.lower() == constants.VALUE_AUTO:
7512
        if not self.op.name_check:
7513
          raise errors.OpPrereqError("IP address set to auto but name checks"
7514
                                     " have been skipped",
7515
                                     errors.ECODE_INVAL)
7516
        nic_ip = self.hostname1.ip
7517
      else:
7518
        if not netutils.IPAddress.IsValid(ip):
7519
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7520
                                     errors.ECODE_INVAL)
7521
        nic_ip = ip
7522

    
7523
      # TODO: check the ip address for uniqueness
7524
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7525
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7526
                                   errors.ECODE_INVAL)
7527

    
7528
      # MAC address verification
7529
      mac = nic.get("mac", constants.VALUE_AUTO)
7530
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7531
        mac = utils.NormalizeAndValidateMac(mac)
7532

    
7533
        try:
7534
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7535
        except errors.ReservationError:
7536
          raise errors.OpPrereqError("MAC address %s already in use"
7537
                                     " in cluster" % mac,
7538
                                     errors.ECODE_NOTUNIQUE)
7539

    
7540
      # bridge verification
7541
      bridge = nic.get("bridge", None)
7542
      link = nic.get("link", None)
7543
      if bridge and link:
7544
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7545
                                   " at the same time", errors.ECODE_INVAL)
7546
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7547
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7548
                                   errors.ECODE_INVAL)
7549
      elif bridge:
7550
        link = bridge
7551

    
7552
      nicparams = {}
7553
      if nic_mode_req:
7554
        nicparams[constants.NIC_MODE] = nic_mode_req
7555
      if link:
7556
        nicparams[constants.NIC_LINK] = link
7557

    
7558
      check_params = cluster.SimpleFillNIC(nicparams)
7559
      objects.NIC.CheckParameterSyntax(check_params)
7560
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7561

    
7562
    # disk checks/pre-build
7563
    self.disks = []
7564
    for disk in self.op.disks:
7565
      mode = disk.get("mode", constants.DISK_RDWR)
7566
      if mode not in constants.DISK_ACCESS_SET:
7567
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7568
                                   mode, errors.ECODE_INVAL)
7569
      size = disk.get("size", None)
7570
      if size is None:
7571
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7572
      try:
7573
        size = int(size)
7574
      except (TypeError, ValueError):
7575
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7576
                                   errors.ECODE_INVAL)
7577
      vg = disk.get("vg", self.cfg.GetVGName())
7578
      new_disk = {"size": size, "mode": mode, "vg": vg}
7579
      if "adopt" in disk:
7580
        new_disk["adopt"] = disk["adopt"]
7581
      self.disks.append(new_disk)
7582

    
7583
    if self.op.mode == constants.INSTANCE_IMPORT:
7584

    
7585
      # Check that the new instance doesn't have less disks than the export
7586
      instance_disks = len(self.disks)
7587
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7588
      if instance_disks < export_disks:
7589
        raise errors.OpPrereqError("Not enough disks to import."
7590
                                   " (instance: %d, export: %d)" %
7591
                                   (instance_disks, export_disks),
7592
                                   errors.ECODE_INVAL)
7593

    
7594
      disk_images = []
7595
      for idx in range(export_disks):
7596
        option = 'disk%d_dump' % idx
7597
        if export_info.has_option(constants.INISECT_INS, option):
7598
          # FIXME: are the old os-es, disk sizes, etc. useful?
7599
          export_name = export_info.get(constants.INISECT_INS, option)
7600
          image = utils.PathJoin(self.op.src_path, export_name)
7601
          disk_images.append(image)
7602
        else:
7603
          disk_images.append(False)
7604

    
7605
      self.src_images = disk_images
7606

    
7607
      old_name = export_info.get(constants.INISECT_INS, 'name')
7608
      try:
7609
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7610
      except (TypeError, ValueError), err:
7611
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7612
                                   " an integer: %s" % str(err),
7613
                                   errors.ECODE_STATE)
7614
      if self.op.instance_name == old_name:
7615
        for idx, nic in enumerate(self.nics):
7616
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7617
            nic_mac_ini = 'nic%d_mac' % idx
7618
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7619

    
7620
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7621

    
7622
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7623
    if self.op.ip_check:
7624
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7625
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7626
                                   (self.check_ip, self.op.instance_name),
7627
                                   errors.ECODE_NOTUNIQUE)
7628

    
7629
    #### mac address generation
7630
    # By generating here the mac address both the allocator and the hooks get
7631
    # the real final mac address rather than the 'auto' or 'generate' value.
7632
    # There is a race condition between the generation and the instance object
7633
    # creation, which means that we know the mac is valid now, but we're not
7634
    # sure it will be when we actually add the instance. If things go bad
7635
    # adding the instance will abort because of a duplicate mac, and the
7636
    # creation job will fail.
7637
    for nic in self.nics:
7638
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7639
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7640

    
7641
    #### allocator run
7642

    
7643
    if self.op.iallocator is not None:
7644
      self._RunAllocator()
7645

    
7646
    #### node related checks
7647

    
7648
    # check primary node
7649
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7650
    assert self.pnode is not None, \
7651
      "Cannot retrieve locked node %s" % self.op.pnode
7652
    if pnode.offline:
7653
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7654
                                 pnode.name, errors.ECODE_STATE)
7655
    if pnode.drained:
7656
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7657
                                 pnode.name, errors.ECODE_STATE)
7658
    if not pnode.vm_capable:
7659
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7660
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7661

    
7662
    self.secondaries = []
7663

    
7664
    # mirror node verification
7665
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7666
      if self.op.snode == pnode.name:
7667
        raise errors.OpPrereqError("The secondary node cannot be the"
7668
                                   " primary node.", errors.ECODE_INVAL)
7669
      _CheckNodeOnline(self, self.op.snode)
7670
      _CheckNodeNotDrained(self, self.op.snode)
7671
      _CheckNodeVmCapable(self, self.op.snode)
7672
      self.secondaries.append(self.op.snode)
7673

    
7674
    nodenames = [pnode.name] + self.secondaries
7675

    
7676
    if not self.adopt_disks:
7677
      # Check lv size requirements, if not adopting
7678
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7679
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7680

    
7681
    else: # instead, we must check the adoption data
7682
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7683
      if len(all_lvs) != len(self.disks):
7684
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7685
                                   errors.ECODE_INVAL)
7686
      for lv_name in all_lvs:
7687
        try:
7688
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7689
          # to ReserveLV uses the same syntax
7690
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7691
        except errors.ReservationError:
7692
          raise errors.OpPrereqError("LV named %s used by another instance" %
7693
                                     lv_name, errors.ECODE_NOTUNIQUE)
7694

    
7695
      vg_names = self.rpc.call_vg_list([pnode.name])
7696
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7697

    
7698
      node_lvs = self.rpc.call_lv_list([pnode.name],
7699
                                       vg_names[pnode.name].payload.keys()
7700
                                      )[pnode.name]
7701
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7702
      node_lvs = node_lvs.payload
7703

    
7704
      delta = all_lvs.difference(node_lvs.keys())
7705
      if delta:
7706
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7707
                                   utils.CommaJoin(delta),
7708
                                   errors.ECODE_INVAL)
7709
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7710
      if online_lvs:
7711
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7712
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7713
                                   errors.ECODE_STATE)
7714
      # update the size of disk based on what is found
7715
      for dsk in self.disks:
7716
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7717

    
7718
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7719

    
7720
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7721
    # check OS parameters (remotely)
7722
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7723

    
7724
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7725

    
7726
    # memory check on primary node
7727
    if self.op.start:
7728
      _CheckNodeFreeMemory(self, self.pnode.name,
7729
                           "creating instance %s" % self.op.instance_name,
7730
                           self.be_full[constants.BE_MEMORY],
7731
                           self.op.hypervisor)
7732

    
7733
    self.dry_run_result = list(nodenames)
7734

    
7735
  def Exec(self, feedback_fn):
7736
    """Create and add the instance to the cluster.
7737

7738
    """
7739
    instance = self.op.instance_name
7740
    pnode_name = self.pnode.name
7741

    
7742
    ht_kind = self.op.hypervisor
7743
    if ht_kind in constants.HTS_REQ_PORT:
7744
      network_port = self.cfg.AllocatePort()
7745
    else:
7746
      network_port = None
7747

    
7748
    if constants.ENABLE_FILE_STORAGE:
7749
      # this is needed because os.path.join does not accept None arguments
7750
      if self.op.file_storage_dir is None:
7751
        string_file_storage_dir = ""
7752
      else:
7753
        string_file_storage_dir = self.op.file_storage_dir
7754

    
7755
      # build the full file storage dir path
7756
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7757
                                        string_file_storage_dir, instance)
7758
    else:
7759
      file_storage_dir = ""
7760

    
7761
    disks = _GenerateDiskTemplate(self,
7762
                                  self.op.disk_template,
7763
                                  instance, pnode_name,
7764
                                  self.secondaries,
7765
                                  self.disks,
7766
                                  file_storage_dir,
7767
                                  self.op.file_driver,
7768
                                  0,
7769
                                  feedback_fn)
7770

    
7771
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7772
                            primary_node=pnode_name,
7773
                            nics=self.nics, disks=disks,
7774
                            disk_template=self.op.disk_template,
7775
                            admin_up=False,
7776
                            network_port=network_port,
7777
                            beparams=self.op.beparams,
7778
                            hvparams=self.op.hvparams,
7779
                            hypervisor=self.op.hypervisor,
7780
                            osparams=self.op.osparams,
7781
                            )
7782

    
7783
    if self.adopt_disks:
7784
      # rename LVs to the newly-generated names; we need to construct
7785
      # 'fake' LV disks with the old data, plus the new unique_id
7786
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7787
      rename_to = []
7788
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7789
        rename_to.append(t_dsk.logical_id)
7790
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7791
        self.cfg.SetDiskID(t_dsk, pnode_name)
7792
      result = self.rpc.call_blockdev_rename(pnode_name,
7793
                                             zip(tmp_disks, rename_to))
7794
      result.Raise("Failed to rename adoped LVs")
7795
    else:
7796
      feedback_fn("* creating instance disks...")
7797
      try:
7798
        _CreateDisks(self, iobj)
7799
      except errors.OpExecError:
7800
        self.LogWarning("Device creation failed, reverting...")
7801
        try:
7802
          _RemoveDisks(self, iobj)
7803
        finally:
7804
          self.cfg.ReleaseDRBDMinors(instance)
7805
          raise
7806

    
7807
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7808
        feedback_fn("* wiping instance disks...")
7809
        try:
7810
          _WipeDisks(self, iobj)
7811
        except errors.OpExecError:
7812
          self.LogWarning("Device wiping failed, reverting...")
7813
          try:
7814
            _RemoveDisks(self, iobj)
7815
          finally:
7816
            self.cfg.ReleaseDRBDMinors(instance)
7817
            raise
7818

    
7819
    feedback_fn("adding instance %s to cluster config" % instance)
7820

    
7821
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7822

    
7823
    # Declare that we don't want to remove the instance lock anymore, as we've
7824
    # added the instance to the config
7825
    del self.remove_locks[locking.LEVEL_INSTANCE]
7826
    # Unlock all the nodes
7827
    if self.op.mode == constants.INSTANCE_IMPORT:
7828
      nodes_keep = [self.op.src_node]
7829
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7830
                       if node != self.op.src_node]
7831
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7832
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7833
    else:
7834
      self.context.glm.release(locking.LEVEL_NODE)
7835
      del self.acquired_locks[locking.LEVEL_NODE]
7836

    
7837
    if self.op.wait_for_sync:
7838
      disk_abort = not _WaitForSync(self, iobj)
7839
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7840
      # make sure the disks are not degraded (still sync-ing is ok)
7841
      time.sleep(15)
7842
      feedback_fn("* checking mirrors status")
7843
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7844
    else:
7845
      disk_abort = False
7846

    
7847
    if disk_abort:
7848
      _RemoveDisks(self, iobj)
7849
      self.cfg.RemoveInstance(iobj.name)
7850
      # Make sure the instance lock gets removed
7851
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7852
      raise errors.OpExecError("There are some degraded disks for"
7853
                               " this instance")
7854

    
7855
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7856
      if self.op.mode == constants.INSTANCE_CREATE:
7857
        if not self.op.no_install:
7858
          feedback_fn("* running the instance OS create scripts...")
7859
          # FIXME: pass debug option from opcode to backend
7860
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7861
                                                 self.op.debug_level)
7862
          result.Raise("Could not add os for instance %s"
7863
                       " on node %s" % (instance, pnode_name))
7864

    
7865
      elif self.op.mode == constants.INSTANCE_IMPORT:
7866
        feedback_fn("* running the instance OS import scripts...")
7867

    
7868
        transfers = []
7869

    
7870
        for idx, image in enumerate(self.src_images):
7871
          if not image:
7872
            continue
7873

    
7874
          # FIXME: pass debug option from opcode to backend
7875
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7876
                                             constants.IEIO_FILE, (image, ),
7877
                                             constants.IEIO_SCRIPT,
7878
                                             (iobj.disks[idx], idx),
7879
                                             None)
7880
          transfers.append(dt)
7881

    
7882
        import_result = \
7883
          masterd.instance.TransferInstanceData(self, feedback_fn,
7884
                                                self.op.src_node, pnode_name,
7885
                                                self.pnode.secondary_ip,
7886
                                                iobj, transfers)
7887
        if not compat.all(import_result):
7888
          self.LogWarning("Some disks for instance %s on node %s were not"
7889
                          " imported successfully" % (instance, pnode_name))
7890

    
7891
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7892
        feedback_fn("* preparing remote import...")
7893
        # The source cluster will stop the instance before attempting to make a
7894
        # connection. In some cases stopping an instance can take a long time,
7895
        # hence the shutdown timeout is added to the connection timeout.
7896
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
7897
                           self.op.source_shutdown_timeout)
7898
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7899

    
7900
        assert iobj.primary_node == self.pnode.name
7901
        disk_results = \
7902
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
7903
                                        self.source_x509_ca,
7904
                                        self._cds, timeouts)
7905
        if not compat.all(disk_results):
7906
          # TODO: Should the instance still be started, even if some disks
7907
          # failed to import (valid for local imports, too)?
7908
          self.LogWarning("Some disks for instance %s on node %s were not"
7909
                          " imported successfully" % (instance, pnode_name))
7910

    
7911
        # Run rename script on newly imported instance
7912
        assert iobj.name == instance
7913
        feedback_fn("Running rename script for %s" % instance)
7914
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7915
                                                   self.source_instance_name,
7916
                                                   self.op.debug_level)
7917
        if result.fail_msg:
7918
          self.LogWarning("Failed to run rename script for %s on node"
7919
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7920

    
7921
      else:
7922
        # also checked in the prereq part
7923
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7924
                                     % self.op.mode)
7925

    
7926
    if self.op.start:
7927
      iobj.admin_up = True
7928
      self.cfg.Update(iobj, feedback_fn)
7929
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7930
      feedback_fn("* starting instance...")
7931
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7932
      result.Raise("Could not start instance")
7933

    
7934
    return list(iobj.all_nodes)
7935

    
7936

    
7937
class LUConnectConsole(NoHooksLU):
7938
  """Connect to an instance's console.
7939

7940
  This is somewhat special in that it returns the command line that
7941
  you need to run on the master node in order to connect to the
7942
  console.
7943

7944
  """
7945
  _OP_PARAMS = [
7946
    _PInstanceName
7947
    ]
7948
  REQ_BGL = False
7949

    
7950
  def ExpandNames(self):
7951
    self._ExpandAndLockInstance()
7952

    
7953
  def CheckPrereq(self):
7954
    """Check prerequisites.
7955

7956
    This checks that the instance is in the cluster.
7957

7958
    """
7959
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7960
    assert self.instance is not None, \
7961
      "Cannot retrieve locked instance %s" % self.op.instance_name
7962
    _CheckNodeOnline(self, self.instance.primary_node)
7963

    
7964
  def Exec(self, feedback_fn):
7965
    """Connect to the console of an instance
7966

7967
    """
7968
    instance = self.instance
7969
    node = instance.primary_node
7970

    
7971
    node_insts = self.rpc.call_instance_list([node],
7972
                                             [instance.hypervisor])[node]
7973
    node_insts.Raise("Can't get node information from %s" % node)
7974

    
7975
    if instance.name not in node_insts.payload:
7976
      if instance.admin_up:
7977
        state = "ERROR_down"
7978
      else:
7979
        state = "ADMIN_down"
7980
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7981
                               (instance.name, state))
7982

    
7983
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7984

    
7985
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7986
    cluster = self.cfg.GetClusterInfo()
7987
    # beparams and hvparams are passed separately, to avoid editing the
7988
    # instance and then saving the defaults in the instance itself.
7989
    hvparams = cluster.FillHV(instance)
7990
    beparams = cluster.FillBE(instance)
7991
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7992

    
7993
    # build ssh cmdline
7994
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7995

    
7996

    
7997
class LUReplaceDisks(LogicalUnit):
7998
  """Replace the disks of an instance.
7999

8000
  """
8001
  HPATH = "mirrors-replace"
8002
  HTYPE = constants.HTYPE_INSTANCE
8003
  _OP_PARAMS = [
8004
    _PInstanceName,
8005
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES)),
8006
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt)),
8007
    ("remote_node", None, ht.TMaybeString),
8008
    ("iallocator", None, ht.TMaybeString),
8009
    ("early_release", False, ht.TBool),
8010
    ]
8011
  REQ_BGL = False
8012

    
8013
  def CheckArguments(self):
8014
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8015
                                  self.op.iallocator)
8016

    
8017
  def ExpandNames(self):
8018
    self._ExpandAndLockInstance()
8019

    
8020
    if self.op.iallocator is not None:
8021
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8022

    
8023
    elif self.op.remote_node is not None:
8024
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8025
      self.op.remote_node = remote_node
8026

    
8027
      # Warning: do not remove the locking of the new secondary here
8028
      # unless DRBD8.AddChildren is changed to work in parallel;
8029
      # currently it doesn't since parallel invocations of
8030
      # FindUnusedMinor will conflict
8031
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
8032
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8033

    
8034
    else:
8035
      self.needed_locks[locking.LEVEL_NODE] = []
8036
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8037

    
8038
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8039
                                   self.op.iallocator, self.op.remote_node,
8040
                                   self.op.disks, False, self.op.early_release)
8041

    
8042
    self.tasklets = [self.replacer]
8043

    
8044
  def DeclareLocks(self, level):
8045
    # If we're not already locking all nodes in the set we have to declare the
8046
    # instance's primary/secondary nodes.
8047
    if (level == locking.LEVEL_NODE and
8048
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
8049
      self._LockInstancesNodes()
8050

    
8051
  def BuildHooksEnv(self):
8052
    """Build hooks env.
8053

8054
    This runs on the master, the primary and all the secondaries.
8055

8056
    """
8057
    instance = self.replacer.instance
8058
    env = {
8059
      "MODE": self.op.mode,
8060
      "NEW_SECONDARY": self.op.remote_node,
8061
      "OLD_SECONDARY": instance.secondary_nodes[0],
8062
      }
8063
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8064
    nl = [
8065
      self.cfg.GetMasterNode(),
8066
      instance.primary_node,
8067
      ]
8068
    if self.op.remote_node is not None:
8069
      nl.append(self.op.remote_node)
8070
    return env, nl, nl
8071

    
8072

    
8073
class TLReplaceDisks(Tasklet):
8074
  """Replaces disks for an instance.
8075

8076
  Note: Locking is not within the scope of this class.
8077

8078
  """
8079
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8080
               disks, delay_iallocator, early_release):
8081
    """Initializes this class.
8082

8083
    """
8084
    Tasklet.__init__(self, lu)
8085

    
8086
    # Parameters
8087
    self.instance_name = instance_name
8088
    self.mode = mode
8089
    self.iallocator_name = iallocator_name
8090
    self.remote_node = remote_node
8091
    self.disks = disks
8092
    self.delay_iallocator = delay_iallocator
8093
    self.early_release = early_release
8094

    
8095
    # Runtime data
8096
    self.instance = None
8097
    self.new_node = None
8098
    self.target_node = None
8099
    self.other_node = None
8100
    self.remote_node_info = None
8101
    self.node_secondary_ip = None
8102

    
8103
  @staticmethod
8104
  def CheckArguments(mode, remote_node, iallocator):
8105
    """Helper function for users of this class.
8106

8107
    """
8108
    # check for valid parameter combination
8109
    if mode == constants.REPLACE_DISK_CHG:
8110
      if remote_node is None and iallocator is None:
8111
        raise errors.OpPrereqError("When changing the secondary either an"
8112
                                   " iallocator script must be used or the"
8113
                                   " new node given", errors.ECODE_INVAL)
8114

    
8115
      if remote_node is not None and iallocator is not None:
8116
        raise errors.OpPrereqError("Give either the iallocator or the new"
8117
                                   " secondary, not both", errors.ECODE_INVAL)
8118

    
8119
    elif remote_node is not None or iallocator is not None:
8120
      # Not replacing the secondary
8121
      raise errors.OpPrereqError("The iallocator and new node options can"
8122
                                 " only be used when changing the"
8123
                                 " secondary node", errors.ECODE_INVAL)
8124

    
8125
  @staticmethod
8126
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8127
    """Compute a new secondary node using an IAllocator.
8128

8129
    """
8130
    ial = IAllocator(lu.cfg, lu.rpc,
8131
                     mode=constants.IALLOCATOR_MODE_RELOC,
8132
                     name=instance_name,
8133
                     relocate_from=relocate_from)
8134

    
8135
    ial.Run(iallocator_name)
8136

    
8137
    if not ial.success:
8138
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8139
                                 " %s" % (iallocator_name, ial.info),
8140
                                 errors.ECODE_NORES)
8141

    
8142
    if len(ial.result) != ial.required_nodes:
8143
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8144
                                 " of nodes (%s), required %s" %
8145
                                 (iallocator_name,
8146
                                  len(ial.result), ial.required_nodes),
8147
                                 errors.ECODE_FAULT)
8148

    
8149
    remote_node_name = ial.result[0]
8150

    
8151
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8152
               instance_name, remote_node_name)
8153

    
8154
    return remote_node_name
8155

    
8156
  def _FindFaultyDisks(self, node_name):
8157
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8158
                                    node_name, True)
8159

    
8160
  def CheckPrereq(self):
8161
    """Check prerequisites.
8162

8163
    This checks that the instance is in the cluster.
8164

8165
    """
8166
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8167
    assert instance is not None, \
8168
      "Cannot retrieve locked instance %s" % self.instance_name
8169

    
8170
    if instance.disk_template != constants.DT_DRBD8:
8171
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8172
                                 " instances", errors.ECODE_INVAL)
8173

    
8174
    if len(instance.secondary_nodes) != 1:
8175
      raise errors.OpPrereqError("The instance has a strange layout,"
8176
                                 " expected one secondary but found %d" %
8177
                                 len(instance.secondary_nodes),
8178
                                 errors.ECODE_FAULT)
8179

    
8180
    if not self.delay_iallocator:
8181
      self._CheckPrereq2()
8182

    
8183
  def _CheckPrereq2(self):
8184
    """Check prerequisites, second part.
8185

8186
    This function should always be part of CheckPrereq. It was separated and is
8187
    now called from Exec because during node evacuation iallocator was only
8188
    called with an unmodified cluster model, not taking planned changes into
8189
    account.
8190

8191
    """
8192
    instance = self.instance
8193
    secondary_node = instance.secondary_nodes[0]
8194

    
8195
    if self.iallocator_name is None:
8196
      remote_node = self.remote_node
8197
    else:
8198
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8199
                                       instance.name, instance.secondary_nodes)
8200

    
8201
    if remote_node is not None:
8202
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8203
      assert self.remote_node_info is not None, \
8204
        "Cannot retrieve locked node %s" % remote_node
8205
    else:
8206
      self.remote_node_info = None
8207

    
8208
    if remote_node == self.instance.primary_node:
8209
      raise errors.OpPrereqError("The specified node is the primary node of"
8210
                                 " the instance.", errors.ECODE_INVAL)
8211

    
8212
    if remote_node == secondary_node:
8213
      raise errors.OpPrereqError("The specified node is already the"
8214
                                 " secondary node of the instance.",
8215
                                 errors.ECODE_INVAL)
8216

    
8217
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8218
                                    constants.REPLACE_DISK_CHG):
8219
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8220
                                 errors.ECODE_INVAL)
8221

    
8222
    if self.mode == constants.REPLACE_DISK_AUTO:
8223
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8224
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8225

    
8226
      if faulty_primary and faulty_secondary:
8227
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8228
                                   " one node and can not be repaired"
8229
                                   " automatically" % self.instance_name,
8230
                                   errors.ECODE_STATE)
8231

    
8232
      if faulty_primary:
8233
        self.disks = faulty_primary
8234
        self.target_node = instance.primary_node
8235
        self.other_node = secondary_node
8236
        check_nodes = [self.target_node, self.other_node]
8237
      elif faulty_secondary:
8238
        self.disks = faulty_secondary
8239
        self.target_node = secondary_node
8240
        self.other_node = instance.primary_node
8241
        check_nodes = [self.target_node, self.other_node]
8242
      else:
8243
        self.disks = []
8244
        check_nodes = []
8245

    
8246
    else:
8247
      # Non-automatic modes
8248
      if self.mode == constants.REPLACE_DISK_PRI:
8249
        self.target_node = instance.primary_node
8250
        self.other_node = secondary_node
8251
        check_nodes = [self.target_node, self.other_node]
8252

    
8253
      elif self.mode == constants.REPLACE_DISK_SEC:
8254
        self.target_node = secondary_node
8255
        self.other_node = instance.primary_node
8256
        check_nodes = [self.target_node, self.other_node]
8257

    
8258
      elif self.mode == constants.REPLACE_DISK_CHG:
8259
        self.new_node = remote_node
8260
        self.other_node = instance.primary_node
8261
        self.target_node = secondary_node
8262
        check_nodes = [self.new_node, self.other_node]
8263

    
8264
        _CheckNodeNotDrained(self.lu, remote_node)
8265
        _CheckNodeVmCapable(self.lu, remote_node)
8266

    
8267
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8268
        assert old_node_info is not None
8269
        if old_node_info.offline and not self.early_release:
8270
          # doesn't make sense to delay the release
8271
          self.early_release = True
8272
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8273
                          " early-release mode", secondary_node)
8274

    
8275
      else:
8276
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8277
                                     self.mode)
8278

    
8279
      # If not specified all disks should be replaced
8280
      if not self.disks:
8281
        self.disks = range(len(self.instance.disks))
8282

    
8283
    for node in check_nodes:
8284
      _CheckNodeOnline(self.lu, node)
8285

    
8286
    # Check whether disks are valid
8287
    for disk_idx in self.disks:
8288
      instance.FindDisk(disk_idx)
8289

    
8290
    # Get secondary node IP addresses
8291
    node_2nd_ip = {}
8292

    
8293
    for node_name in [self.target_node, self.other_node, self.new_node]:
8294
      if node_name is not None:
8295
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8296

    
8297
    self.node_secondary_ip = node_2nd_ip
8298

    
8299
  def Exec(self, feedback_fn):
8300
    """Execute disk replacement.
8301

8302
    This dispatches the disk replacement to the appropriate handler.
8303

8304
    """
8305
    if self.delay_iallocator:
8306
      self._CheckPrereq2()
8307

    
8308
    if not self.disks:
8309
      feedback_fn("No disks need replacement")
8310
      return
8311

    
8312
    feedback_fn("Replacing disk(s) %s for %s" %
8313
                (utils.CommaJoin(self.disks), self.instance.name))
8314

    
8315
    activate_disks = (not self.instance.admin_up)
8316

    
8317
    # Activate the instance disks if we're replacing them on a down instance
8318
    if activate_disks:
8319
      _StartInstanceDisks(self.lu, self.instance, True)
8320

    
8321
    try:
8322
      # Should we replace the secondary node?
8323
      if self.new_node is not None:
8324
        fn = self._ExecDrbd8Secondary
8325
      else:
8326
        fn = self._ExecDrbd8DiskOnly
8327

    
8328
      return fn(feedback_fn)
8329

    
8330
    finally:
8331
      # Deactivate the instance disks if we're replacing them on a
8332
      # down instance
8333
      if activate_disks:
8334
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8335

    
8336
  def _CheckVolumeGroup(self, nodes):
8337
    self.lu.LogInfo("Checking volume groups")
8338

    
8339
    vgname = self.cfg.GetVGName()
8340

    
8341
    # Make sure volume group exists on all involved nodes
8342
    results = self.rpc.call_vg_list(nodes)
8343
    if not results:
8344
      raise errors.OpExecError("Can't list volume groups on the nodes")
8345

    
8346
    for node in nodes:
8347
      res = results[node]
8348
      res.Raise("Error checking node %s" % node)
8349
      if vgname not in res.payload:
8350
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8351
                                 (vgname, node))
8352

    
8353
  def _CheckDisksExistence(self, nodes):
8354
    # Check disk existence
8355
    for idx, dev in enumerate(self.instance.disks):
8356
      if idx not in self.disks:
8357
        continue
8358

    
8359
      for node in nodes:
8360
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8361
        self.cfg.SetDiskID(dev, node)
8362

    
8363
        result = self.rpc.call_blockdev_find(node, dev)
8364

    
8365
        msg = result.fail_msg
8366
        if msg or not result.payload:
8367
          if not msg:
8368
            msg = "disk not found"
8369
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8370
                                   (idx, node, msg))
8371

    
8372
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8373
    for idx, dev in enumerate(self.instance.disks):
8374
      if idx not in self.disks:
8375
        continue
8376

    
8377
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8378
                      (idx, node_name))
8379

    
8380
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8381
                                   ldisk=ldisk):
8382
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8383
                                 " replace disks for instance %s" %
8384
                                 (node_name, self.instance.name))
8385

    
8386
  def _CreateNewStorage(self, node_name):
8387
    vgname = self.cfg.GetVGName()
8388
    iv_names = {}
8389

    
8390
    for idx, dev in enumerate(self.instance.disks):
8391
      if idx not in self.disks:
8392
        continue
8393

    
8394
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8395

    
8396
      self.cfg.SetDiskID(dev, node_name)
8397

    
8398
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8399
      names = _GenerateUniqueNames(self.lu, lv_names)
8400

    
8401
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8402
                             logical_id=(vgname, names[0]))
8403
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8404
                             logical_id=(vgname, names[1]))
8405

    
8406
      new_lvs = [lv_data, lv_meta]
8407
      old_lvs = dev.children
8408
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8409

    
8410
      # we pass force_create=True to force the LVM creation
8411
      for new_lv in new_lvs:
8412
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8413
                        _GetInstanceInfoText(self.instance), False)
8414

    
8415
    return iv_names
8416

    
8417
  def _CheckDevices(self, node_name, iv_names):
8418
    for name, (dev, _, _) in iv_names.iteritems():
8419
      self.cfg.SetDiskID(dev, node_name)
8420

    
8421
      result = self.rpc.call_blockdev_find(node_name, dev)
8422

    
8423
      msg = result.fail_msg
8424
      if msg or not result.payload:
8425
        if not msg:
8426
          msg = "disk not found"
8427
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8428
                                 (name, msg))
8429

    
8430
      if result.payload.is_degraded:
8431
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8432

    
8433
  def _RemoveOldStorage(self, node_name, iv_names):
8434
    for name, (_, old_lvs, _) in iv_names.iteritems():
8435
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8436

    
8437
      for lv in old_lvs:
8438
        self.cfg.SetDiskID(lv, node_name)
8439

    
8440
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8441
        if msg:
8442
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8443
                             hint="remove unused LVs manually")
8444

    
8445
  def _ReleaseNodeLock(self, node_name):
8446
    """Releases the lock for a given node."""
8447
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8448

    
8449
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8450
    """Replace a disk on the primary or secondary for DRBD 8.
8451

8452
    The algorithm for replace is quite complicated:
8453

8454
      1. for each disk to be replaced:
8455

8456
        1. create new LVs on the target node with unique names
8457
        1. detach old LVs from the drbd device
8458
        1. rename old LVs to name_replaced.<time_t>
8459
        1. rename new LVs to old LVs
8460
        1. attach the new LVs (with the old names now) to the drbd device
8461

8462
      1. wait for sync across all devices
8463

8464
      1. for each modified disk:
8465

8466
        1. remove old LVs (which have the name name_replaces.<time_t>)
8467

8468
    Failures are not very well handled.
8469

8470
    """
8471
    steps_total = 6
8472

    
8473
    # Step: check device activation
8474
    self.lu.LogStep(1, steps_total, "Check device existence")
8475
    self._CheckDisksExistence([self.other_node, self.target_node])
8476
    self._CheckVolumeGroup([self.target_node, self.other_node])
8477

    
8478
    # Step: check other node consistency
8479
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8480
    self._CheckDisksConsistency(self.other_node,
8481
                                self.other_node == self.instance.primary_node,
8482
                                False)
8483

    
8484
    # Step: create new storage
8485
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8486
    iv_names = self._CreateNewStorage(self.target_node)
8487

    
8488
    # Step: for each lv, detach+rename*2+attach
8489
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8490
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8491
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8492

    
8493
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8494
                                                     old_lvs)
8495
      result.Raise("Can't detach drbd from local storage on node"
8496
                   " %s for device %s" % (self.target_node, dev.iv_name))
8497
      #dev.children = []
8498
      #cfg.Update(instance)
8499

    
8500
      # ok, we created the new LVs, so now we know we have the needed
8501
      # storage; as such, we proceed on the target node to rename
8502
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8503
      # using the assumption that logical_id == physical_id (which in
8504
      # turn is the unique_id on that node)
8505

    
8506
      # FIXME(iustin): use a better name for the replaced LVs
8507
      temp_suffix = int(time.time())
8508
      ren_fn = lambda d, suff: (d.physical_id[0],
8509
                                d.physical_id[1] + "_replaced-%s" % suff)
8510

    
8511
      # Build the rename list based on what LVs exist on the node
8512
      rename_old_to_new = []
8513
      for to_ren in old_lvs:
8514
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8515
        if not result.fail_msg and result.payload:
8516
          # device exists
8517
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8518

    
8519
      self.lu.LogInfo("Renaming the old LVs on the target node")
8520
      result = self.rpc.call_blockdev_rename(self.target_node,
8521
                                             rename_old_to_new)
8522
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8523

    
8524
      # Now we rename the new LVs to the old LVs
8525
      self.lu.LogInfo("Renaming the new LVs on the target node")
8526
      rename_new_to_old = [(new, old.physical_id)
8527
                           for old, new in zip(old_lvs, new_lvs)]
8528
      result = self.rpc.call_blockdev_rename(self.target_node,
8529
                                             rename_new_to_old)
8530
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8531

    
8532
      for old, new in zip(old_lvs, new_lvs):
8533
        new.logical_id = old.logical_id
8534
        self.cfg.SetDiskID(new, self.target_node)
8535

    
8536
      for disk in old_lvs:
8537
        disk.logical_id = ren_fn(disk, temp_suffix)
8538
        self.cfg.SetDiskID(disk, self.target_node)
8539

    
8540
      # Now that the new lvs have the old name, we can add them to the device
8541
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8542
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8543
                                                  new_lvs)
8544
      msg = result.fail_msg
8545
      if msg:
8546
        for new_lv in new_lvs:
8547
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8548
                                               new_lv).fail_msg
8549
          if msg2:
8550
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8551
                               hint=("cleanup manually the unused logical"
8552
                                     "volumes"))
8553
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8554

    
8555
      dev.children = new_lvs
8556

    
8557
      self.cfg.Update(self.instance, feedback_fn)
8558

    
8559
    cstep = 5
8560
    if self.early_release:
8561
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8562
      cstep += 1
8563
      self._RemoveOldStorage(self.target_node, iv_names)
8564
      # WARNING: we release both node locks here, do not do other RPCs
8565
      # than WaitForSync to the primary node
8566
      self._ReleaseNodeLock([self.target_node, self.other_node])
8567

    
8568
    # Wait for sync
8569
    # This can fail as the old devices are degraded and _WaitForSync
8570
    # does a combined result over all disks, so we don't check its return value
8571
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8572
    cstep += 1
8573
    _WaitForSync(self.lu, self.instance)
8574

    
8575
    # Check all devices manually
8576
    self._CheckDevices(self.instance.primary_node, iv_names)
8577

    
8578
    # Step: remove old storage
8579
    if not self.early_release:
8580
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8581
      cstep += 1
8582
      self._RemoveOldStorage(self.target_node, iv_names)
8583

    
8584
  def _ExecDrbd8Secondary(self, feedback_fn):
8585
    """Replace the secondary node for DRBD 8.
8586

8587
    The algorithm for replace is quite complicated:
8588
      - for all disks of the instance:
8589
        - create new LVs on the new node with same names
8590
        - shutdown the drbd device on the old secondary
8591
        - disconnect the drbd network on the primary
8592
        - create the drbd device on the new secondary
8593
        - network attach the drbd on the primary, using an artifice:
8594
          the drbd code for Attach() will connect to the network if it
8595
          finds a device which is connected to the good local disks but
8596
          not network enabled
8597
      - wait for sync across all devices
8598
      - remove all disks from the old secondary
8599

8600
    Failures are not very well handled.
8601

8602
    """
8603
    steps_total = 6
8604

    
8605
    # Step: check device activation
8606
    self.lu.LogStep(1, steps_total, "Check device existence")
8607
    self._CheckDisksExistence([self.instance.primary_node])
8608
    self._CheckVolumeGroup([self.instance.primary_node])
8609

    
8610
    # Step: check other node consistency
8611
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8612
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8613

    
8614
    # Step: create new storage
8615
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8616
    for idx, dev in enumerate(self.instance.disks):
8617
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8618
                      (self.new_node, idx))
8619
      # we pass force_create=True to force LVM creation
8620
      for new_lv in dev.children:
8621
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8622
                        _GetInstanceInfoText(self.instance), False)
8623

    
8624
    # Step 4: dbrd minors and drbd setups changes
8625
    # after this, we must manually remove the drbd minors on both the
8626
    # error and the success paths
8627
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8628
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8629
                                         for dev in self.instance.disks],
8630
                                        self.instance.name)
8631
    logging.debug("Allocated minors %r", minors)
8632

    
8633
    iv_names = {}
8634
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8635
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8636
                      (self.new_node, idx))
8637
      # create new devices on new_node; note that we create two IDs:
8638
      # one without port, so the drbd will be activated without
8639
      # networking information on the new node at this stage, and one
8640
      # with network, for the latter activation in step 4
8641
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8642
      if self.instance.primary_node == o_node1:
8643
        p_minor = o_minor1
8644
      else:
8645
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8646
        p_minor = o_minor2
8647

    
8648
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8649
                      p_minor, new_minor, o_secret)
8650
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8651
                    p_minor, new_minor, o_secret)
8652

    
8653
      iv_names[idx] = (dev, dev.children, new_net_id)
8654
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8655
                    new_net_id)
8656
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8657
                              logical_id=new_alone_id,
8658
                              children=dev.children,
8659
                              size=dev.size)
8660
      try:
8661
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8662
                              _GetInstanceInfoText(self.instance), False)
8663
      except errors.GenericError:
8664
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8665
        raise
8666

    
8667
    # We have new devices, shutdown the drbd on the old secondary
8668
    for idx, dev in enumerate(self.instance.disks):
8669
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8670
      self.cfg.SetDiskID(dev, self.target_node)
8671
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8672
      if msg:
8673
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8674
                           "node: %s" % (idx, msg),
8675
                           hint=("Please cleanup this device manually as"
8676
                                 " soon as possible"))
8677

    
8678
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8679
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8680
                                               self.node_secondary_ip,
8681
                                               self.instance.disks)\
8682
                                              [self.instance.primary_node]
8683

    
8684
    msg = result.fail_msg
8685
    if msg:
8686
      # detaches didn't succeed (unlikely)
8687
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8688
      raise errors.OpExecError("Can't detach the disks from the network on"
8689
                               " old node: %s" % (msg,))
8690

    
8691
    # if we managed to detach at least one, we update all the disks of
8692
    # the instance to point to the new secondary
8693
    self.lu.LogInfo("Updating instance configuration")
8694
    for dev, _, new_logical_id in iv_names.itervalues():
8695
      dev.logical_id = new_logical_id
8696
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8697

    
8698
    self.cfg.Update(self.instance, feedback_fn)
8699

    
8700
    # and now perform the drbd attach
8701
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8702
                    " (standalone => connected)")
8703
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8704
                                            self.new_node],
8705
                                           self.node_secondary_ip,
8706
                                           self.instance.disks,
8707
                                           self.instance.name,
8708
                                           False)
8709
    for to_node, to_result in result.items():
8710
      msg = to_result.fail_msg
8711
      if msg:
8712
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8713
                           to_node, msg,
8714
                           hint=("please do a gnt-instance info to see the"
8715
                                 " status of disks"))
8716
    cstep = 5
8717
    if self.early_release:
8718
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8719
      cstep += 1
8720
      self._RemoveOldStorage(self.target_node, iv_names)
8721
      # WARNING: we release all node locks here, do not do other RPCs
8722
      # than WaitForSync to the primary node
8723
      self._ReleaseNodeLock([self.instance.primary_node,
8724
                             self.target_node,
8725
                             self.new_node])
8726

    
8727
    # Wait for sync
8728
    # This can fail as the old devices are degraded and _WaitForSync
8729
    # does a combined result over all disks, so we don't check its return value
8730
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8731
    cstep += 1
8732
    _WaitForSync(self.lu, self.instance)
8733

    
8734
    # Check all devices manually
8735
    self._CheckDevices(self.instance.primary_node, iv_names)
8736

    
8737
    # Step: remove old storage
8738
    if not self.early_release:
8739
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8740
      self._RemoveOldStorage(self.target_node, iv_names)
8741

    
8742

    
8743
class LURepairNodeStorage(NoHooksLU):
8744
  """Repairs the volume group on a node.
8745

8746
  """
8747
  _OP_PARAMS = [
8748
    _PNodeName,
8749
    ("storage_type", ht.NoDefault, _CheckStorageType),
8750
    ("name", ht.NoDefault, ht.TNonEmptyString),
8751
    ("ignore_consistency", False, ht.TBool),
8752
    ]
8753
  REQ_BGL = False
8754

    
8755
  def CheckArguments(self):
8756
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8757

    
8758
    storage_type = self.op.storage_type
8759

    
8760
    if (constants.SO_FIX_CONSISTENCY not in
8761
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8762
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8763
                                 " repaired" % storage_type,
8764
                                 errors.ECODE_INVAL)
8765

    
8766
  def ExpandNames(self):
8767
    self.needed_locks = {
8768
      locking.LEVEL_NODE: [self.op.node_name],
8769
      }
8770

    
8771
  def _CheckFaultyDisks(self, instance, node_name):
8772
    """Ensure faulty disks abort the opcode or at least warn."""
8773
    try:
8774
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8775
                                  node_name, True):
8776
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8777
                                   " node '%s'" % (instance.name, node_name),
8778
                                   errors.ECODE_STATE)
8779
    except errors.OpPrereqError, err:
8780
      if self.op.ignore_consistency:
8781
        self.proc.LogWarning(str(err.args[0]))
8782
      else:
8783
        raise
8784

    
8785
  def CheckPrereq(self):
8786
    """Check prerequisites.
8787

8788
    """
8789
    # Check whether any instance on this node has faulty disks
8790
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8791
      if not inst.admin_up:
8792
        continue
8793
      check_nodes = set(inst.all_nodes)
8794
      check_nodes.discard(self.op.node_name)
8795
      for inst_node_name in check_nodes:
8796
        self._CheckFaultyDisks(inst, inst_node_name)
8797

    
8798
  def Exec(self, feedback_fn):
8799
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8800
                (self.op.name, self.op.node_name))
8801

    
8802
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8803
    result = self.rpc.call_storage_execute(self.op.node_name,
8804
                                           self.op.storage_type, st_args,
8805
                                           self.op.name,
8806
                                           constants.SO_FIX_CONSISTENCY)
8807
    result.Raise("Failed to repair storage unit '%s' on %s" %
8808
                 (self.op.name, self.op.node_name))
8809

    
8810

    
8811
class LUNodeEvacuationStrategy(NoHooksLU):
8812
  """Computes the node evacuation strategy.
8813

8814
  """
8815
  _OP_PARAMS = [
8816
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
8817
    ("remote_node", None, ht.TMaybeString),
8818
    ("iallocator", None, ht.TMaybeString),
8819
    ]
8820
  REQ_BGL = False
8821

    
8822
  def CheckArguments(self):
8823
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8824

    
8825
  def ExpandNames(self):
8826
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8827
    self.needed_locks = locks = {}
8828
    if self.op.remote_node is None:
8829
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8830
    else:
8831
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8832
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8833

    
8834
  def Exec(self, feedback_fn):
8835
    if self.op.remote_node is not None:
8836
      instances = []
8837
      for node in self.op.nodes:
8838
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8839
      result = []
8840
      for i in instances:
8841
        if i.primary_node == self.op.remote_node:
8842
          raise errors.OpPrereqError("Node %s is the primary node of"
8843
                                     " instance %s, cannot use it as"
8844
                                     " secondary" %
8845
                                     (self.op.remote_node, i.name),
8846
                                     errors.ECODE_INVAL)
8847
        result.append([i.name, self.op.remote_node])
8848
    else:
8849
      ial = IAllocator(self.cfg, self.rpc,
8850
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8851
                       evac_nodes=self.op.nodes)
8852
      ial.Run(self.op.iallocator, validate=True)
8853
      if not ial.success:
8854
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8855
                                 errors.ECODE_NORES)
8856
      result = ial.result
8857
    return result
8858

    
8859

    
8860
class LUGrowDisk(LogicalUnit):
8861
  """Grow a disk of an instance.
8862

8863
  """
8864
  HPATH = "disk-grow"
8865
  HTYPE = constants.HTYPE_INSTANCE
8866
  _OP_PARAMS = [
8867
    _PInstanceName,
8868
    ("disk", ht.NoDefault, ht.TInt),
8869
    ("amount", ht.NoDefault, ht.TInt),
8870
    ("wait_for_sync", True, ht.TBool),
8871
    ]
8872
  REQ_BGL = False
8873

    
8874
  def ExpandNames(self):
8875
    self._ExpandAndLockInstance()
8876
    self.needed_locks[locking.LEVEL_NODE] = []
8877
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8878

    
8879
  def DeclareLocks(self, level):
8880
    if level == locking.LEVEL_NODE:
8881
      self._LockInstancesNodes()
8882

    
8883
  def BuildHooksEnv(self):
8884
    """Build hooks env.
8885

8886
    This runs on the master, the primary and all the secondaries.
8887

8888
    """
8889
    env = {
8890
      "DISK": self.op.disk,
8891
      "AMOUNT": self.op.amount,
8892
      }
8893
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8894
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8895
    return env, nl, nl
8896

    
8897
  def CheckPrereq(self):
8898
    """Check prerequisites.
8899

8900
    This checks that the instance is in the cluster.
8901

8902
    """
8903
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8904
    assert instance is not None, \
8905
      "Cannot retrieve locked instance %s" % self.op.instance_name
8906
    nodenames = list(instance.all_nodes)
8907
    for node in nodenames:
8908
      _CheckNodeOnline(self, node)
8909

    
8910
    self.instance = instance
8911

    
8912
    if instance.disk_template not in constants.DTS_GROWABLE:
8913
      raise errors.OpPrereqError("Instance's disk layout does not support"
8914
                                 " growing.", errors.ECODE_INVAL)
8915

    
8916
    self.disk = instance.FindDisk(self.op.disk)
8917

    
8918
    if instance.disk_template != constants.DT_FILE:
8919
      # TODO: check the free disk space for file, when that feature
8920
      # will be supported
8921
      _CheckNodesFreeDiskPerVG(self, nodenames,
8922
                               {self.disk.physical_id[0]: self.op.amount})
8923

    
8924
  def Exec(self, feedback_fn):
8925
    """Execute disk grow.
8926

8927
    """
8928
    instance = self.instance
8929
    disk = self.disk
8930

    
8931
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8932
    if not disks_ok:
8933
      raise errors.OpExecError("Cannot activate block device to grow")
8934

    
8935
    for node in instance.all_nodes:
8936
      self.cfg.SetDiskID(disk, node)
8937
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8938
      result.Raise("Grow request failed to node %s" % node)
8939

    
8940
      # TODO: Rewrite code to work properly
8941
      # DRBD goes into sync mode for a short amount of time after executing the
8942
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8943
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8944
      # time is a work-around.
8945
      time.sleep(5)
8946

    
8947
    disk.RecordGrow(self.op.amount)
8948
    self.cfg.Update(instance, feedback_fn)
8949
    if self.op.wait_for_sync:
8950
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8951
      if disk_abort:
8952
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8953
                             " status.\nPlease check the instance.")
8954
      if not instance.admin_up:
8955
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8956
    elif not instance.admin_up:
8957
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8958
                           " not supposed to be running because no wait for"
8959
                           " sync mode was requested.")
8960

    
8961

    
8962
class LUQueryInstanceData(NoHooksLU):
8963
  """Query runtime instance data.
8964

8965
  """
8966
  _OP_PARAMS = [
8967
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
8968
    ("static", False, ht.TBool),
8969
    ]
8970
  REQ_BGL = False
8971

    
8972
  def ExpandNames(self):
8973
    self.needed_locks = {}
8974
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8975

    
8976
    if self.op.instances:
8977
      self.wanted_names = []
8978
      for name in self.op.instances:
8979
        full_name = _ExpandInstanceName(self.cfg, name)
8980
        self.wanted_names.append(full_name)
8981
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8982
    else:
8983
      self.wanted_names = None
8984
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8985

    
8986
    self.needed_locks[locking.LEVEL_NODE] = []
8987
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8988

    
8989
  def DeclareLocks(self, level):
8990
    if level == locking.LEVEL_NODE:
8991
      self._LockInstancesNodes()
8992

    
8993
  def CheckPrereq(self):
8994
    """Check prerequisites.
8995

8996
    This only checks the optional instance list against the existing names.
8997

8998
    """
8999
    if self.wanted_names is None:
9000
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
9001

    
9002
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
9003
                             in self.wanted_names]
9004

    
9005
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9006
    """Returns the status of a block device
9007

9008
    """
9009
    if self.op.static or not node:
9010
      return None
9011

    
9012
    self.cfg.SetDiskID(dev, node)
9013

    
9014
    result = self.rpc.call_blockdev_find(node, dev)
9015
    if result.offline:
9016
      return None
9017

    
9018
    result.Raise("Can't compute disk status for %s" % instance_name)
9019

    
9020
    status = result.payload
9021
    if status is None:
9022
      return None
9023

    
9024
    return (status.dev_path, status.major, status.minor,
9025
            status.sync_percent, status.estimated_time,
9026
            status.is_degraded, status.ldisk_status)
9027

    
9028
  def _ComputeDiskStatus(self, instance, snode, dev):
9029
    """Compute block device status.
9030

9031
    """
9032
    if dev.dev_type in constants.LDS_DRBD:
9033
      # we change the snode then (otherwise we use the one passed in)
9034
      if dev.logical_id[0] == instance.primary_node:
9035
        snode = dev.logical_id[1]
9036
      else:
9037
        snode = dev.logical_id[0]
9038

    
9039
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9040
                                              instance.name, dev)
9041
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9042

    
9043
    if dev.children:
9044
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9045
                      for child in dev.children]
9046
    else:
9047
      dev_children = []
9048

    
9049
    data = {
9050
      "iv_name": dev.iv_name,
9051
      "dev_type": dev.dev_type,
9052
      "logical_id": dev.logical_id,
9053
      "physical_id": dev.physical_id,
9054
      "pstatus": dev_pstatus,
9055
      "sstatus": dev_sstatus,
9056
      "children": dev_children,
9057
      "mode": dev.mode,
9058
      "size": dev.size,
9059
      }
9060

    
9061
    return data
9062

    
9063
  def Exec(self, feedback_fn):
9064
    """Gather and return data"""
9065
    result = {}
9066

    
9067
    cluster = self.cfg.GetClusterInfo()
9068

    
9069
    for instance in self.wanted_instances:
9070
      if not self.op.static:
9071
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9072
                                                  instance.name,
9073
                                                  instance.hypervisor)
9074
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9075
        remote_info = remote_info.payload
9076
        if remote_info and "state" in remote_info:
9077
          remote_state = "up"
9078
        else:
9079
          remote_state = "down"
9080
      else:
9081
        remote_state = None
9082
      if instance.admin_up:
9083
        config_state = "up"
9084
      else:
9085
        config_state = "down"
9086

    
9087
      disks = [self._ComputeDiskStatus(instance, None, device)
9088
               for device in instance.disks]
9089

    
9090
      idict = {
9091
        "name": instance.name,
9092
        "config_state": config_state,
9093
        "run_state": remote_state,
9094
        "pnode": instance.primary_node,
9095
        "snodes": instance.secondary_nodes,
9096
        "os": instance.os,
9097
        # this happens to be the same format used for hooks
9098
        "nics": _NICListToTuple(self, instance.nics),
9099
        "disk_template": instance.disk_template,
9100
        "disks": disks,
9101
        "hypervisor": instance.hypervisor,
9102
        "network_port": instance.network_port,
9103
        "hv_instance": instance.hvparams,
9104
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9105
        "be_instance": instance.beparams,
9106
        "be_actual": cluster.FillBE(instance),
9107
        "os_instance": instance.osparams,
9108
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9109
        "serial_no": instance.serial_no,
9110
        "mtime": instance.mtime,
9111
        "ctime": instance.ctime,
9112
        "uuid": instance.uuid,
9113
        }
9114

    
9115
      result[instance.name] = idict
9116

    
9117
    return result
9118

    
9119

    
9120
class LUSetInstanceParams(LogicalUnit):
9121
  """Modifies an instances's parameters.
9122

9123
  """
9124
  HPATH = "instance-modify"
9125
  HTYPE = constants.HTYPE_INSTANCE
9126
  _OP_PARAMS = [
9127
    _PInstanceName,
9128
    ("nics", ht.EmptyList, ht.TList),
9129
    ("disks", ht.EmptyList, ht.TList),
9130
    ("beparams", ht.EmptyDict, ht.TDict),
9131
    ("hvparams", ht.EmptyDict, ht.TDict),
9132
    ("disk_template", None, ht.TMaybeString),
9133
    ("remote_node", None, ht.TMaybeString),
9134
    ("os_name", None, ht.TMaybeString),
9135
    ("force_variant", False, ht.TBool),
9136
    ("osparams", None, ht.TOr(ht.TDict, ht.TNone)),
9137
    _PForce,
9138
    ]
9139
  REQ_BGL = False
9140

    
9141
  def CheckArguments(self):
9142
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9143
            self.op.hvparams or self.op.beparams or self.op.os_name):
9144
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9145

    
9146
    if self.op.hvparams:
9147
      _CheckGlobalHvParams(self.op.hvparams)
9148

    
9149
    # Disk validation
9150
    disk_addremove = 0
9151
    for disk_op, disk_dict in self.op.disks:
9152
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9153
      if disk_op == constants.DDM_REMOVE:
9154
        disk_addremove += 1
9155
        continue
9156
      elif disk_op == constants.DDM_ADD:
9157
        disk_addremove += 1
9158
      else:
9159
        if not isinstance(disk_op, int):
9160
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9161
        if not isinstance(disk_dict, dict):
9162
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9163
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9164

    
9165
      if disk_op == constants.DDM_ADD:
9166
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
9167
        if mode not in constants.DISK_ACCESS_SET:
9168
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9169
                                     errors.ECODE_INVAL)
9170
        size = disk_dict.get('size', None)
9171
        if size is None:
9172
          raise errors.OpPrereqError("Required disk parameter size missing",
9173
                                     errors.ECODE_INVAL)
9174
        try:
9175
          size = int(size)
9176
        except (TypeError, ValueError), err:
9177
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9178
                                     str(err), errors.ECODE_INVAL)
9179
        disk_dict['size'] = size
9180
      else:
9181
        # modification of disk
9182
        if 'size' in disk_dict:
9183
          raise errors.OpPrereqError("Disk size change not possible, use"
9184
                                     " grow-disk", errors.ECODE_INVAL)
9185

    
9186
    if disk_addremove > 1:
9187
      raise errors.OpPrereqError("Only one disk add or remove operation"
9188
                                 " supported at a time", errors.ECODE_INVAL)
9189

    
9190
    if self.op.disks and self.op.disk_template is not None:
9191
      raise errors.OpPrereqError("Disk template conversion and other disk"
9192
                                 " changes not supported at the same time",
9193
                                 errors.ECODE_INVAL)
9194

    
9195
    if self.op.disk_template:
9196
      _CheckDiskTemplate(self.op.disk_template)
9197
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
9198
          self.op.remote_node is None):
9199
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
9200
                                   " one requires specifying a secondary node",
9201
                                   errors.ECODE_INVAL)
9202

    
9203
    # NIC validation
9204
    nic_addremove = 0
9205
    for nic_op, nic_dict in self.op.nics:
9206
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9207
      if nic_op == constants.DDM_REMOVE:
9208
        nic_addremove += 1
9209
        continue
9210
      elif nic_op == constants.DDM_ADD:
9211
        nic_addremove += 1
9212
      else:
9213
        if not isinstance(nic_op, int):
9214
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9215
        if not isinstance(nic_dict, dict):
9216
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9217
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9218

    
9219
      # nic_dict should be a dict
9220
      nic_ip = nic_dict.get('ip', None)
9221
      if nic_ip is not None:
9222
        if nic_ip.lower() == constants.VALUE_NONE:
9223
          nic_dict['ip'] = None
9224
        else:
9225
          if not netutils.IPAddress.IsValid(nic_ip):
9226
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9227
                                       errors.ECODE_INVAL)
9228

    
9229
      nic_bridge = nic_dict.get('bridge', None)
9230
      nic_link = nic_dict.get('link', None)
9231
      if nic_bridge and nic_link:
9232
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9233
                                   " at the same time", errors.ECODE_INVAL)
9234
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9235
        nic_dict['bridge'] = None
9236
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9237
        nic_dict['link'] = None
9238

    
9239
      if nic_op == constants.DDM_ADD:
9240
        nic_mac = nic_dict.get('mac', None)
9241
        if nic_mac is None:
9242
          nic_dict['mac'] = constants.VALUE_AUTO
9243

    
9244
      if 'mac' in nic_dict:
9245
        nic_mac = nic_dict['mac']
9246
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9247
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9248

    
9249
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9250
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9251
                                     " modifying an existing nic",
9252
                                     errors.ECODE_INVAL)
9253

    
9254
    if nic_addremove > 1:
9255
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9256
                                 " supported at a time", errors.ECODE_INVAL)
9257

    
9258
  def ExpandNames(self):
9259
    self._ExpandAndLockInstance()
9260
    self.needed_locks[locking.LEVEL_NODE] = []
9261
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9262

    
9263
  def DeclareLocks(self, level):
9264
    if level == locking.LEVEL_NODE:
9265
      self._LockInstancesNodes()
9266
      if self.op.disk_template and self.op.remote_node:
9267
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9268
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9269

    
9270
  def BuildHooksEnv(self):
9271
    """Build hooks env.
9272

9273
    This runs on the master, primary and secondaries.
9274

9275
    """
9276
    args = dict()
9277
    if constants.BE_MEMORY in self.be_new:
9278
      args['memory'] = self.be_new[constants.BE_MEMORY]
9279
    if constants.BE_VCPUS in self.be_new:
9280
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9281
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9282
    # information at all.
9283
    if self.op.nics:
9284
      args['nics'] = []
9285
      nic_override = dict(self.op.nics)
9286
      for idx, nic in enumerate(self.instance.nics):
9287
        if idx in nic_override:
9288
          this_nic_override = nic_override[idx]
9289
        else:
9290
          this_nic_override = {}
9291
        if 'ip' in this_nic_override:
9292
          ip = this_nic_override['ip']
9293
        else:
9294
          ip = nic.ip
9295
        if 'mac' in this_nic_override:
9296
          mac = this_nic_override['mac']
9297
        else:
9298
          mac = nic.mac
9299
        if idx in self.nic_pnew:
9300
          nicparams = self.nic_pnew[idx]
9301
        else:
9302
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9303
        mode = nicparams[constants.NIC_MODE]
9304
        link = nicparams[constants.NIC_LINK]
9305
        args['nics'].append((ip, mac, mode, link))
9306
      if constants.DDM_ADD in nic_override:
9307
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9308
        mac = nic_override[constants.DDM_ADD]['mac']
9309
        nicparams = self.nic_pnew[constants.DDM_ADD]
9310
        mode = nicparams[constants.NIC_MODE]
9311
        link = nicparams[constants.NIC_LINK]
9312
        args['nics'].append((ip, mac, mode, link))
9313
      elif constants.DDM_REMOVE in nic_override:
9314
        del args['nics'][-1]
9315

    
9316
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9317
    if self.op.disk_template:
9318
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9319
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9320
    return env, nl, nl
9321

    
9322
  def CheckPrereq(self):
9323
    """Check prerequisites.
9324

9325
    This only checks the instance list against the existing names.
9326

9327
    """
9328
    # checking the new params on the primary/secondary nodes
9329

    
9330
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9331
    cluster = self.cluster = self.cfg.GetClusterInfo()
9332
    assert self.instance is not None, \
9333
      "Cannot retrieve locked instance %s" % self.op.instance_name
9334
    pnode = instance.primary_node
9335
    nodelist = list(instance.all_nodes)
9336

    
9337
    # OS change
9338
    if self.op.os_name and not self.op.force:
9339
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9340
                      self.op.force_variant)
9341
      instance_os = self.op.os_name
9342
    else:
9343
      instance_os = instance.os
9344

    
9345
    if self.op.disk_template:
9346
      if instance.disk_template == self.op.disk_template:
9347
        raise errors.OpPrereqError("Instance already has disk template %s" %
9348
                                   instance.disk_template, errors.ECODE_INVAL)
9349

    
9350
      if (instance.disk_template,
9351
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9352
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9353
                                   " %s to %s" % (instance.disk_template,
9354
                                                  self.op.disk_template),
9355
                                   errors.ECODE_INVAL)
9356
      _CheckInstanceDown(self, instance, "cannot change disk template")
9357
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9358
        if self.op.remote_node == pnode:
9359
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9360
                                     " as the primary node of the instance" %
9361
                                     self.op.remote_node, errors.ECODE_STATE)
9362
        _CheckNodeOnline(self, self.op.remote_node)
9363
        _CheckNodeNotDrained(self, self.op.remote_node)
9364
        # FIXME: here we assume that the old instance type is DT_PLAIN
9365
        assert instance.disk_template == constants.DT_PLAIN
9366
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9367
                 for d in instance.disks]
9368
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9369
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9370

    
9371
    # hvparams processing
9372
    if self.op.hvparams:
9373
      hv_type = instance.hypervisor
9374
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9375
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9376
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9377

    
9378
      # local check
9379
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9380
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9381
      self.hv_new = hv_new # the new actual values
9382
      self.hv_inst = i_hvdict # the new dict (without defaults)
9383
    else:
9384
      self.hv_new = self.hv_inst = {}
9385

    
9386
    # beparams processing
9387
    if self.op.beparams:
9388
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9389
                                   use_none=True)
9390
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9391
      be_new = cluster.SimpleFillBE(i_bedict)
9392
      self.be_new = be_new # the new actual values
9393
      self.be_inst = i_bedict # the new dict (without defaults)
9394
    else:
9395
      self.be_new = self.be_inst = {}
9396

    
9397
    # osparams processing
9398
    if self.op.osparams:
9399
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9400
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9401
      self.os_inst = i_osdict # the new dict (without defaults)
9402
    else:
9403
      self.os_inst = {}
9404

    
9405
    self.warn = []
9406

    
9407
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9408
      mem_check_list = [pnode]
9409
      if be_new[constants.BE_AUTO_BALANCE]:
9410
        # either we changed auto_balance to yes or it was from before
9411
        mem_check_list.extend(instance.secondary_nodes)
9412
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9413
                                                  instance.hypervisor)
9414
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9415
                                         instance.hypervisor)
9416
      pninfo = nodeinfo[pnode]
9417
      msg = pninfo.fail_msg
9418
      if msg:
9419
        # Assume the primary node is unreachable and go ahead
9420
        self.warn.append("Can't get info from primary node %s: %s" %
9421
                         (pnode,  msg))
9422
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9423
        self.warn.append("Node data from primary node %s doesn't contain"
9424
                         " free memory information" % pnode)
9425
      elif instance_info.fail_msg:
9426
        self.warn.append("Can't get instance runtime information: %s" %
9427
                        instance_info.fail_msg)
9428
      else:
9429
        if instance_info.payload:
9430
          current_mem = int(instance_info.payload['memory'])
9431
        else:
9432
          # Assume instance not running
9433
          # (there is a slight race condition here, but it's not very probable,
9434
          # and we have no other way to check)
9435
          current_mem = 0
9436
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9437
                    pninfo.payload['memory_free'])
9438
        if miss_mem > 0:
9439
          raise errors.OpPrereqError("This change will prevent the instance"
9440
                                     " from starting, due to %d MB of memory"
9441
                                     " missing on its primary node" % miss_mem,
9442
                                     errors.ECODE_NORES)
9443

    
9444
      if be_new[constants.BE_AUTO_BALANCE]:
9445
        for node, nres in nodeinfo.items():
9446
          if node not in instance.secondary_nodes:
9447
            continue
9448
          msg = nres.fail_msg
9449
          if msg:
9450
            self.warn.append("Can't get info from secondary node %s: %s" %
9451
                             (node, msg))
9452
          elif not isinstance(nres.payload.get('memory_free', None), int):
9453
            self.warn.append("Secondary node %s didn't return free"
9454
                             " memory information" % node)
9455
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9456
            self.warn.append("Not enough memory to failover instance to"
9457
                             " secondary node %s" % node)
9458

    
9459
    # NIC processing
9460
    self.nic_pnew = {}
9461
    self.nic_pinst = {}
9462
    for nic_op, nic_dict in self.op.nics:
9463
      if nic_op == constants.DDM_REMOVE:
9464
        if not instance.nics:
9465
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9466
                                     errors.ECODE_INVAL)
9467
        continue
9468
      if nic_op != constants.DDM_ADD:
9469
        # an existing nic
9470
        if not instance.nics:
9471
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9472
                                     " no NICs" % nic_op,
9473
                                     errors.ECODE_INVAL)
9474
        if nic_op < 0 or nic_op >= len(instance.nics):
9475
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9476
                                     " are 0 to %d" %
9477
                                     (nic_op, len(instance.nics) - 1),
9478
                                     errors.ECODE_INVAL)
9479
        old_nic_params = instance.nics[nic_op].nicparams
9480
        old_nic_ip = instance.nics[nic_op].ip
9481
      else:
9482
        old_nic_params = {}
9483
        old_nic_ip = None
9484

    
9485
      update_params_dict = dict([(key, nic_dict[key])
9486
                                 for key in constants.NICS_PARAMETERS
9487
                                 if key in nic_dict])
9488

    
9489
      if 'bridge' in nic_dict:
9490
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9491

    
9492
      new_nic_params = _GetUpdatedParams(old_nic_params,
9493
                                         update_params_dict)
9494
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9495
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9496
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9497
      self.nic_pinst[nic_op] = new_nic_params
9498
      self.nic_pnew[nic_op] = new_filled_nic_params
9499
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9500

    
9501
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9502
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9503
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9504
        if msg:
9505
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9506
          if self.op.force:
9507
            self.warn.append(msg)
9508
          else:
9509
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9510
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9511
        if 'ip' in nic_dict:
9512
          nic_ip = nic_dict['ip']
9513
        else:
9514
          nic_ip = old_nic_ip
9515
        if nic_ip is None:
9516
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9517
                                     ' on a routed nic', errors.ECODE_INVAL)
9518
      if 'mac' in nic_dict:
9519
        nic_mac = nic_dict['mac']
9520
        if nic_mac is None:
9521
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9522
                                     errors.ECODE_INVAL)
9523
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9524
          # otherwise generate the mac
9525
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9526
        else:
9527
          # or validate/reserve the current one
9528
          try:
9529
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9530
          except errors.ReservationError:
9531
            raise errors.OpPrereqError("MAC address %s already in use"
9532
                                       " in cluster" % nic_mac,
9533
                                       errors.ECODE_NOTUNIQUE)
9534

    
9535
    # DISK processing
9536
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9537
      raise errors.OpPrereqError("Disk operations not supported for"
9538
                                 " diskless instances",
9539
                                 errors.ECODE_INVAL)
9540
    for disk_op, _ in self.op.disks:
9541
      if disk_op == constants.DDM_REMOVE:
9542
        if len(instance.disks) == 1:
9543
          raise errors.OpPrereqError("Cannot remove the last disk of"
9544
                                     " an instance", errors.ECODE_INVAL)
9545
        _CheckInstanceDown(self, instance, "cannot remove disks")
9546

    
9547
      if (disk_op == constants.DDM_ADD and
9548
          len(instance.nics) >= constants.MAX_DISKS):
9549
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9550
                                   " add more" % constants.MAX_DISKS,
9551
                                   errors.ECODE_STATE)
9552
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9553
        # an existing disk
9554
        if disk_op < 0 or disk_op >= len(instance.disks):
9555
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9556
                                     " are 0 to %d" %
9557
                                     (disk_op, len(instance.disks)),
9558
                                     errors.ECODE_INVAL)
9559

    
9560
    return
9561

    
9562
  def _ConvertPlainToDrbd(self, feedback_fn):
9563
    """Converts an instance from plain to drbd.
9564

9565
    """
9566
    feedback_fn("Converting template to drbd")
9567
    instance = self.instance
9568
    pnode = instance.primary_node
9569
    snode = self.op.remote_node
9570

    
9571
    # create a fake disk info for _GenerateDiskTemplate
9572
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9573
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9574
                                      instance.name, pnode, [snode],
9575
                                      disk_info, None, None, 0, feedback_fn)
9576
    info = _GetInstanceInfoText(instance)
9577
    feedback_fn("Creating aditional volumes...")
9578
    # first, create the missing data and meta devices
9579
    for disk in new_disks:
9580
      # unfortunately this is... not too nice
9581
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9582
                            info, True)
9583
      for child in disk.children:
9584
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9585
    # at this stage, all new LVs have been created, we can rename the
9586
    # old ones
9587
    feedback_fn("Renaming original volumes...")
9588
    rename_list = [(o, n.children[0].logical_id)
9589
                   for (o, n) in zip(instance.disks, new_disks)]
9590
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9591
    result.Raise("Failed to rename original LVs")
9592

    
9593
    feedback_fn("Initializing DRBD devices...")
9594
    # all child devices are in place, we can now create the DRBD devices
9595
    for disk in new_disks:
9596
      for node in [pnode, snode]:
9597
        f_create = node == pnode
9598
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9599

    
9600
    # at this point, the instance has been modified
9601
    instance.disk_template = constants.DT_DRBD8
9602
    instance.disks = new_disks
9603
    self.cfg.Update(instance, feedback_fn)
9604

    
9605
    # disks are created, waiting for sync
9606
    disk_abort = not _WaitForSync(self, instance)
9607
    if disk_abort:
9608
      raise errors.OpExecError("There are some degraded disks for"
9609
                               " this instance, please cleanup manually")
9610

    
9611
  def _ConvertDrbdToPlain(self, feedback_fn):
9612
    """Converts an instance from drbd to plain.
9613

9614
    """
9615
    instance = self.instance
9616
    assert len(instance.secondary_nodes) == 1
9617
    pnode = instance.primary_node
9618
    snode = instance.secondary_nodes[0]
9619
    feedback_fn("Converting template to plain")
9620

    
9621
    old_disks = instance.disks
9622
    new_disks = [d.children[0] for d in old_disks]
9623

    
9624
    # copy over size and mode
9625
    for parent, child in zip(old_disks, new_disks):
9626
      child.size = parent.size
9627
      child.mode = parent.mode
9628

    
9629
    # update instance structure
9630
    instance.disks = new_disks
9631
    instance.disk_template = constants.DT_PLAIN
9632
    self.cfg.Update(instance, feedback_fn)
9633

    
9634
    feedback_fn("Removing volumes on the secondary node...")
9635
    for disk in old_disks:
9636
      self.cfg.SetDiskID(disk, snode)
9637
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9638
      if msg:
9639
        self.LogWarning("Could not remove block device %s on node %s,"
9640
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9641

    
9642
    feedback_fn("Removing unneeded volumes on the primary node...")
9643
    for idx, disk in enumerate(old_disks):
9644
      meta = disk.children[1]
9645
      self.cfg.SetDiskID(meta, pnode)
9646
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9647
      if msg:
9648
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9649
                        " continuing anyway: %s", idx, pnode, msg)
9650

    
9651
  def Exec(self, feedback_fn):
9652
    """Modifies an instance.
9653

9654
    All parameters take effect only at the next restart of the instance.
9655

9656
    """
9657
    # Process here the warnings from CheckPrereq, as we don't have a
9658
    # feedback_fn there.
9659
    for warn in self.warn:
9660
      feedback_fn("WARNING: %s" % warn)
9661

    
9662
    result = []
9663
    instance = self.instance
9664
    # disk changes
9665
    for disk_op, disk_dict in self.op.disks:
9666
      if disk_op == constants.DDM_REMOVE:
9667
        # remove the last disk
9668
        device = instance.disks.pop()
9669
        device_idx = len(instance.disks)
9670
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9671
          self.cfg.SetDiskID(disk, node)
9672
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9673
          if msg:
9674
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9675
                            " continuing anyway", device_idx, node, msg)
9676
        result.append(("disk/%d" % device_idx, "remove"))
9677
      elif disk_op == constants.DDM_ADD:
9678
        # add a new disk
9679
        if instance.disk_template == constants.DT_FILE:
9680
          file_driver, file_path = instance.disks[0].logical_id
9681
          file_path = os.path.dirname(file_path)
9682
        else:
9683
          file_driver = file_path = None
9684
        disk_idx_base = len(instance.disks)
9685
        new_disk = _GenerateDiskTemplate(self,
9686
                                         instance.disk_template,
9687
                                         instance.name, instance.primary_node,
9688
                                         instance.secondary_nodes,
9689
                                         [disk_dict],
9690
                                         file_path,
9691
                                         file_driver,
9692
                                         disk_idx_base, feedback_fn)[0]
9693
        instance.disks.append(new_disk)
9694
        info = _GetInstanceInfoText(instance)
9695

    
9696
        logging.info("Creating volume %s for instance %s",
9697
                     new_disk.iv_name, instance.name)
9698
        # Note: this needs to be kept in sync with _CreateDisks
9699
        #HARDCODE
9700
        for node in instance.all_nodes:
9701
          f_create = node == instance.primary_node
9702
          try:
9703
            _CreateBlockDev(self, node, instance, new_disk,
9704
                            f_create, info, f_create)
9705
          except errors.OpExecError, err:
9706
            self.LogWarning("Failed to create volume %s (%s) on"
9707
                            " node %s: %s",
9708
                            new_disk.iv_name, new_disk, node, err)
9709
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9710
                       (new_disk.size, new_disk.mode)))
9711
      else:
9712
        # change a given disk
9713
        instance.disks[disk_op].mode = disk_dict['mode']
9714
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9715

    
9716
    if self.op.disk_template:
9717
      r_shut = _ShutdownInstanceDisks(self, instance)
9718
      if not r_shut:
9719
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9720
                                 " proceed with disk template conversion")
9721
      mode = (instance.disk_template, self.op.disk_template)
9722
      try:
9723
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9724
      except:
9725
        self.cfg.ReleaseDRBDMinors(instance.name)
9726
        raise
9727
      result.append(("disk_template", self.op.disk_template))
9728

    
9729
    # NIC changes
9730
    for nic_op, nic_dict in self.op.nics:
9731
      if nic_op == constants.DDM_REMOVE:
9732
        # remove the last nic
9733
        del instance.nics[-1]
9734
        result.append(("nic.%d" % len(instance.nics), "remove"))
9735
      elif nic_op == constants.DDM_ADD:
9736
        # mac and bridge should be set, by now
9737
        mac = nic_dict['mac']
9738
        ip = nic_dict.get('ip', None)
9739
        nicparams = self.nic_pinst[constants.DDM_ADD]
9740
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9741
        instance.nics.append(new_nic)
9742
        result.append(("nic.%d" % (len(instance.nics) - 1),
9743
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9744
                       (new_nic.mac, new_nic.ip,
9745
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9746
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9747
                       )))
9748
      else:
9749
        for key in 'mac', 'ip':
9750
          if key in nic_dict:
9751
            setattr(instance.nics[nic_op], key, nic_dict[key])
9752
        if nic_op in self.nic_pinst:
9753
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9754
        for key, val in nic_dict.iteritems():
9755
          result.append(("nic.%s/%d" % (key, nic_op), val))
9756

    
9757
    # hvparams changes
9758
    if self.op.hvparams:
9759
      instance.hvparams = self.hv_inst
9760
      for key, val in self.op.hvparams.iteritems():
9761
        result.append(("hv/%s" % key, val))
9762

    
9763
    # beparams changes
9764
    if self.op.beparams:
9765
      instance.beparams = self.be_inst
9766
      for key, val in self.op.beparams.iteritems():
9767
        result.append(("be/%s" % key, val))
9768

    
9769
    # OS change
9770
    if self.op.os_name:
9771
      instance.os = self.op.os_name
9772

    
9773
    # osparams changes
9774
    if self.op.osparams:
9775
      instance.osparams = self.os_inst
9776
      for key, val in self.op.osparams.iteritems():
9777
        result.append(("os/%s" % key, val))
9778

    
9779
    self.cfg.Update(instance, feedback_fn)
9780

    
9781
    return result
9782

    
9783
  _DISK_CONVERSIONS = {
9784
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9785
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9786
    }
9787

    
9788

    
9789
class LUQueryExports(NoHooksLU):
9790
  """Query the exports list
9791

9792
  """
9793
  _OP_PARAMS = [
9794
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
9795
    ("use_locking", False, ht.TBool),
9796
    ]
9797
  REQ_BGL = False
9798

    
9799
  def ExpandNames(self):
9800
    self.needed_locks = {}
9801
    self.share_locks[locking.LEVEL_NODE] = 1
9802
    if not self.op.nodes:
9803
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9804
    else:
9805
      self.needed_locks[locking.LEVEL_NODE] = \
9806
        _GetWantedNodes(self, self.op.nodes)
9807

    
9808
  def Exec(self, feedback_fn):
9809
    """Compute the list of all the exported system images.
9810

9811
    @rtype: dict
9812
    @return: a dictionary with the structure node->(export-list)
9813
        where export-list is a list of the instances exported on
9814
        that node.
9815

9816
    """
9817
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9818
    rpcresult = self.rpc.call_export_list(self.nodes)
9819
    result = {}
9820
    for node in rpcresult:
9821
      if rpcresult[node].fail_msg:
9822
        result[node] = False
9823
      else:
9824
        result[node] = rpcresult[node].payload
9825

    
9826
    return result
9827

    
9828

    
9829
class LUPrepareExport(NoHooksLU):
9830
  """Prepares an instance for an export and returns useful information.
9831

9832
  """
9833
  _OP_PARAMS = [
9834
    _PInstanceName,
9835
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES)),
9836
    ]
9837
  REQ_BGL = False
9838

    
9839
  def ExpandNames(self):
9840
    self._ExpandAndLockInstance()
9841

    
9842
  def CheckPrereq(self):
9843
    """Check prerequisites.
9844

9845
    """
9846
    instance_name = self.op.instance_name
9847

    
9848
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9849
    assert self.instance is not None, \
9850
          "Cannot retrieve locked instance %s" % self.op.instance_name
9851
    _CheckNodeOnline(self, self.instance.primary_node)
9852

    
9853
    self._cds = _GetClusterDomainSecret()
9854

    
9855
  def Exec(self, feedback_fn):
9856
    """Prepares an instance for an export.
9857

9858
    """
9859
    instance = self.instance
9860

    
9861
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9862
      salt = utils.GenerateSecret(8)
9863

    
9864
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9865
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9866
                                              constants.RIE_CERT_VALIDITY)
9867
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9868

    
9869
      (name, cert_pem) = result.payload
9870

    
9871
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9872
                                             cert_pem)
9873

    
9874
      return {
9875
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9876
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9877
                          salt),
9878
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9879
        }
9880

    
9881
    return None
9882

    
9883

    
9884
class LUExportInstance(LogicalUnit):
9885
  """Export an instance to an image in the cluster.
9886

9887
  """
9888
  HPATH = "instance-export"
9889
  HTYPE = constants.HTYPE_INSTANCE
9890
  _OP_PARAMS = [
9891
    _PInstanceName,
9892
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList)),
9893
    ("shutdown", True, ht.TBool),
9894
    _PShutdownTimeout,
9895
    ("remove_instance", False, ht.TBool),
9896
    ("ignore_remove_failures", False, ht.TBool),
9897
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES)),
9898
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone)),
9899
    ("destination_x509_ca", None, ht.TMaybeString),
9900
    ]
9901
  REQ_BGL = False
9902

    
9903
  def CheckArguments(self):
9904
    """Check the arguments.
9905

9906
    """
9907
    self.x509_key_name = self.op.x509_key_name
9908
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9909

    
9910
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9911
      if not self.x509_key_name:
9912
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9913
                                   errors.ECODE_INVAL)
9914

    
9915
      if not self.dest_x509_ca_pem:
9916
        raise errors.OpPrereqError("Missing destination X509 CA",
9917
                                   errors.ECODE_INVAL)
9918

    
9919
  def ExpandNames(self):
9920
    self._ExpandAndLockInstance()
9921

    
9922
    # Lock all nodes for local exports
9923
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9924
      # FIXME: lock only instance primary and destination node
9925
      #
9926
      # Sad but true, for now we have do lock all nodes, as we don't know where
9927
      # the previous export might be, and in this LU we search for it and
9928
      # remove it from its current node. In the future we could fix this by:
9929
      #  - making a tasklet to search (share-lock all), then create the
9930
      #    new one, then one to remove, after
9931
      #  - removing the removal operation altogether
9932
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9933

    
9934
  def DeclareLocks(self, level):
9935
    """Last minute lock declaration."""
9936
    # All nodes are locked anyway, so nothing to do here.
9937

    
9938
  def BuildHooksEnv(self):
9939
    """Build hooks env.
9940

9941
    This will run on the master, primary node and target node.
9942

9943
    """
9944
    env = {
9945
      "EXPORT_MODE": self.op.mode,
9946
      "EXPORT_NODE": self.op.target_node,
9947
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9948
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9949
      # TODO: Generic function for boolean env variables
9950
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9951
      }
9952

    
9953
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9954

    
9955
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9956

    
9957
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9958
      nl.append(self.op.target_node)
9959

    
9960
    return env, nl, nl
9961

    
9962
  def CheckPrereq(self):
9963
    """Check prerequisites.
9964

9965
    This checks that the instance and node names are valid.
9966

9967
    """
9968
    instance_name = self.op.instance_name
9969

    
9970
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9971
    assert self.instance is not None, \
9972
          "Cannot retrieve locked instance %s" % self.op.instance_name
9973
    _CheckNodeOnline(self, self.instance.primary_node)
9974

    
9975
    if (self.op.remove_instance and self.instance.admin_up and
9976
        not self.op.shutdown):
9977
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9978
                                 " down before")
9979

    
9980
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9981
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9982
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9983
      assert self.dst_node is not None
9984

    
9985
      _CheckNodeOnline(self, self.dst_node.name)
9986
      _CheckNodeNotDrained(self, self.dst_node.name)
9987

    
9988
      self._cds = None
9989
      self.dest_disk_info = None
9990
      self.dest_x509_ca = None
9991

    
9992
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9993
      self.dst_node = None
9994

    
9995
      if len(self.op.target_node) != len(self.instance.disks):
9996
        raise errors.OpPrereqError(("Received destination information for %s"
9997
                                    " disks, but instance %s has %s disks") %
9998
                                   (len(self.op.target_node), instance_name,
9999
                                    len(self.instance.disks)),
10000
                                   errors.ECODE_INVAL)
10001

    
10002
      cds = _GetClusterDomainSecret()
10003

    
10004
      # Check X509 key name
10005
      try:
10006
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10007
      except (TypeError, ValueError), err:
10008
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10009

    
10010
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10011
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10012
                                   errors.ECODE_INVAL)
10013

    
10014
      # Load and verify CA
10015
      try:
10016
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10017
      except OpenSSL.crypto.Error, err:
10018
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10019
                                   (err, ), errors.ECODE_INVAL)
10020

    
10021
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10022
      if errcode is not None:
10023
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10024
                                   (msg, ), errors.ECODE_INVAL)
10025

    
10026
      self.dest_x509_ca = cert
10027

    
10028
      # Verify target information
10029
      disk_info = []
10030
      for idx, disk_data in enumerate(self.op.target_node):
10031
        try:
10032
          (host, port, magic) = \
10033
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10034
        except errors.GenericError, err:
10035
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10036
                                     (idx, err), errors.ECODE_INVAL)
10037

    
10038
        disk_info.append((host, port, magic))
10039

    
10040
      assert len(disk_info) == len(self.op.target_node)
10041
      self.dest_disk_info = disk_info
10042

    
10043
    else:
10044
      raise errors.ProgrammerError("Unhandled export mode %r" %
10045
                                   self.op.mode)
10046

    
10047
    # instance disk type verification
10048
    # TODO: Implement export support for file-based disks
10049
    for disk in self.instance.disks:
10050
      if disk.dev_type == constants.LD_FILE:
10051
        raise errors.OpPrereqError("Export not supported for instances with"
10052
                                   " file-based disks", errors.ECODE_INVAL)
10053

    
10054
  def _CleanupExports(self, feedback_fn):
10055
    """Removes exports of current instance from all other nodes.
10056

10057
    If an instance in a cluster with nodes A..D was exported to node C, its
10058
    exports will be removed from the nodes A, B and D.
10059

10060
    """
10061
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10062

    
10063
    nodelist = self.cfg.GetNodeList()
10064
    nodelist.remove(self.dst_node.name)
10065

    
10066
    # on one-node clusters nodelist will be empty after the removal
10067
    # if we proceed the backup would be removed because OpQueryExports
10068
    # substitutes an empty list with the full cluster node list.
10069
    iname = self.instance.name
10070
    if nodelist:
10071
      feedback_fn("Removing old exports for instance %s" % iname)
10072
      exportlist = self.rpc.call_export_list(nodelist)
10073
      for node in exportlist:
10074
        if exportlist[node].fail_msg:
10075
          continue
10076
        if iname in exportlist[node].payload:
10077
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10078
          if msg:
10079
            self.LogWarning("Could not remove older export for instance %s"
10080
                            " on node %s: %s", iname, node, msg)
10081

    
10082
  def Exec(self, feedback_fn):
10083
    """Export an instance to an image in the cluster.
10084

10085
    """
10086
    assert self.op.mode in constants.EXPORT_MODES
10087

    
10088
    instance = self.instance
10089
    src_node = instance.primary_node
10090

    
10091
    if self.op.shutdown:
10092
      # shutdown the instance, but not the disks
10093
      feedback_fn("Shutting down instance %s" % instance.name)
10094
      result = self.rpc.call_instance_shutdown(src_node, instance,
10095
                                               self.op.shutdown_timeout)
10096
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10097
      result.Raise("Could not shutdown instance %s on"
10098
                   " node %s" % (instance.name, src_node))
10099

    
10100
    # set the disks ID correctly since call_instance_start needs the
10101
    # correct drbd minor to create the symlinks
10102
    for disk in instance.disks:
10103
      self.cfg.SetDiskID(disk, src_node)
10104

    
10105
    activate_disks = (not instance.admin_up)
10106

    
10107
    if activate_disks:
10108
      # Activate the instance disks if we'exporting a stopped instance
10109
      feedback_fn("Activating disks for %s" % instance.name)
10110
      _StartInstanceDisks(self, instance, None)
10111

    
10112
    try:
10113
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10114
                                                     instance)
10115

    
10116
      helper.CreateSnapshots()
10117
      try:
10118
        if (self.op.shutdown and instance.admin_up and
10119
            not self.op.remove_instance):
10120
          assert not activate_disks
10121
          feedback_fn("Starting instance %s" % instance.name)
10122
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10123
          msg = result.fail_msg
10124
          if msg:
10125
            feedback_fn("Failed to start instance: %s" % msg)
10126
            _ShutdownInstanceDisks(self, instance)
10127
            raise errors.OpExecError("Could not start instance: %s" % msg)
10128

    
10129
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10130
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10131
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10132
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10133
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10134

    
10135
          (key_name, _, _) = self.x509_key_name
10136

    
10137
          dest_ca_pem = \
10138
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10139
                                            self.dest_x509_ca)
10140

    
10141
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10142
                                                     key_name, dest_ca_pem,
10143
                                                     timeouts)
10144
      finally:
10145
        helper.Cleanup()
10146

    
10147
      # Check for backwards compatibility
10148
      assert len(dresults) == len(instance.disks)
10149
      assert compat.all(isinstance(i, bool) for i in dresults), \
10150
             "Not all results are boolean: %r" % dresults
10151

    
10152
    finally:
10153
      if activate_disks:
10154
        feedback_fn("Deactivating disks for %s" % instance.name)
10155
        _ShutdownInstanceDisks(self, instance)
10156

    
10157
    if not (compat.all(dresults) and fin_resu):
10158
      failures = []
10159
      if not fin_resu:
10160
        failures.append("export finalization")
10161
      if not compat.all(dresults):
10162
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10163
                               if not dsk)
10164
        failures.append("disk export: disk(s) %s" % fdsk)
10165

    
10166
      raise errors.OpExecError("Export failed, errors in %s" %
10167
                               utils.CommaJoin(failures))
10168

    
10169
    # At this point, the export was successful, we can cleanup/finish
10170

    
10171
    # Remove instance if requested
10172
    if self.op.remove_instance:
10173
      feedback_fn("Removing instance %s" % instance.name)
10174
      _RemoveInstance(self, feedback_fn, instance,
10175
                      self.op.ignore_remove_failures)
10176

    
10177
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10178
      self._CleanupExports(feedback_fn)
10179

    
10180
    return fin_resu, dresults
10181

    
10182

    
10183
class LURemoveExport(NoHooksLU):
10184
  """Remove exports related to the named instance.
10185

10186
  """
10187
  _OP_PARAMS = [
10188
    _PInstanceName,
10189
    ]
10190
  REQ_BGL = False
10191

    
10192
  def ExpandNames(self):
10193
    self.needed_locks = {}
10194
    # We need all nodes to be locked in order for RemoveExport to work, but we
10195
    # don't need to lock the instance itself, as nothing will happen to it (and
10196
    # we can remove exports also for a removed instance)
10197
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10198

    
10199
  def Exec(self, feedback_fn):
10200
    """Remove any export.
10201

10202
    """
10203
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10204
    # If the instance was not found we'll try with the name that was passed in.
10205
    # This will only work if it was an FQDN, though.
10206
    fqdn_warn = False
10207
    if not instance_name:
10208
      fqdn_warn = True
10209
      instance_name = self.op.instance_name
10210

    
10211
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
10212
    exportlist = self.rpc.call_export_list(locked_nodes)
10213
    found = False
10214
    for node in exportlist:
10215
      msg = exportlist[node].fail_msg
10216
      if msg:
10217
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10218
        continue
10219
      if instance_name in exportlist[node].payload:
10220
        found = True
10221
        result = self.rpc.call_export_remove(node, instance_name)
10222
        msg = result.fail_msg
10223
        if msg:
10224
          logging.error("Could not remove export for instance %s"
10225
                        " on node %s: %s", instance_name, node, msg)
10226

    
10227
    if fqdn_warn and not found:
10228
      feedback_fn("Export not found. If trying to remove an export belonging"
10229
                  " to a deleted instance please use its Fully Qualified"
10230
                  " Domain Name.")
10231

    
10232

    
10233
class LUQueryGroups(NoHooksLU):
10234
  """Logical unit for querying node groups.
10235

10236
  """
10237
  # pylint: disable-msg=W0142
10238
  _OP_PARAMS = [
10239
    _POutputFields,
10240
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10241
    ]
10242

    
10243
  REQ_BGL = False
10244

    
10245
  _FIELDS_DYNAMIC = utils.FieldSet()
10246

    
10247
  _SIMPLE_FIELDS = ["name", "uuid"]
10248

    
10249
  _FIELDS_STATIC = utils.FieldSet(
10250
      "node_cnt", "node_list", "pinst_cnt", "pinst_list", *_SIMPLE_FIELDS)
10251

    
10252
  def CheckArguments(self):
10253
    _CheckOutputFields(static=self._FIELDS_STATIC,
10254
                       dynamic=self._FIELDS_DYNAMIC,
10255
                       selected=self.op.output_fields)
10256

    
10257
  def ExpandNames(self):
10258
    self.needed_locks = {}
10259

    
10260
  def Exec(self, feedback_fn):
10261
    """Computes the list of groups and their attributes.
10262

10263
    """
10264
    all_groups = self.cfg.GetAllNodeGroupsInfo()
10265

    
10266
    if not self.op.names:
10267
      my_groups = utils.NiceSort(all_groups.keys())
10268
    else:
10269
      # Accept names to be either names or UUIDs.
10270
      all_uuid = frozenset(all_groups.keys())
10271
      name_to_uuid = dict((g.name, g.uuid) for g in all_groups.values())
10272
      my_groups = []
10273
      missing = []
10274

    
10275
      for name in self.op.names:
10276
        if name in all_uuid:
10277
          my_groups.append(name)
10278
        elif name in name_to_uuid:
10279
          my_groups.append(name_to_uuid[name])
10280
        else:
10281
          missing.append(name)
10282

    
10283
      if missing:
10284
        raise errors.OpPrereqError("Some groups do not exist: %s" % missing,
10285
                                   errors.ECODE_NOENT)
10286

    
10287
    do_nodes = bool(frozenset(["node_cnt", "node_list"]).
10288
                    intersection(self.op.output_fields))
10289

    
10290
    do_instances = bool(frozenset(["pinst_cnt", "pinst_list"]).
10291
                        intersection(self.op.output_fields))
10292

    
10293
    # We need to map group->[nodes], and group->[instances]. The former is
10294
    # directly attainable, but the latter we have to do through instance->node,
10295
    # hence we need to process nodes even if we only need instance information.
10296
    if do_nodes or do_instances:
10297
      all_nodes = self.cfg.GetAllNodesInfo()
10298
      group_to_nodes = dict((all_groups[name].uuid, []) for name in my_groups)
10299
      node_to_group = {}
10300

    
10301
      for node in all_nodes.values():
10302
        if node.group in group_to_nodes:
10303
          group_to_nodes[node.group].append(node.name)
10304
          node_to_group[node.name] = node.group
10305

    
10306
      if do_instances:
10307
        all_instances = self.cfg.GetAllInstancesInfo()
10308
        group_to_instances = dict((all_groups[name].uuid, [])
10309
                                  for name in my_groups)
10310
        for instance in all_instances.values():
10311
          node = instance.primary_node
10312
          if node in node_to_group:
10313
            group_to_instances[node_to_group[node]].append(instance.name)
10314

    
10315
    output = []
10316

    
10317
    for name in my_groups:
10318
      group = all_groups[name]
10319
      group_output = []
10320

    
10321
      for field in self.op.output_fields:
10322
        if field in self._SIMPLE_FIELDS:
10323
          val = getattr(group, field)
10324
        elif field == "node_list":
10325
          val = utils.NiceSort(group_to_nodes[group.uuid])
10326
        elif field == "node_cnt":
10327
          val = len(group_to_nodes[group.uuid])
10328
        elif field == "pinst_list":
10329
          val = utils.NiceSort(group_to_instances[group.uuid])
10330
        elif field == "pinst_cnt":
10331
          val = len(group_to_instances[group.uuid])
10332
        else:
10333
          raise errors.ParameterError(field)
10334
        group_output.append(val)
10335
      output.append(group_output)
10336

    
10337
    return output
10338

    
10339

    
10340
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10341
  """Generic tags LU.
10342

10343
  This is an abstract class which is the parent of all the other tags LUs.
10344

10345
  """
10346

    
10347
  def ExpandNames(self):
10348
    self.needed_locks = {}
10349
    if self.op.kind == constants.TAG_NODE:
10350
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10351
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10352
    elif self.op.kind == constants.TAG_INSTANCE:
10353
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10354
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10355

    
10356
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10357
    # not possible to acquire the BGL based on opcode parameters)
10358

    
10359
  def CheckPrereq(self):
10360
    """Check prerequisites.
10361

10362
    """
10363
    if self.op.kind == constants.TAG_CLUSTER:
10364
      self.target = self.cfg.GetClusterInfo()
10365
    elif self.op.kind == constants.TAG_NODE:
10366
      self.target = self.cfg.GetNodeInfo(self.op.name)
10367
    elif self.op.kind == constants.TAG_INSTANCE:
10368
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10369
    else:
10370
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10371
                                 str(self.op.kind), errors.ECODE_INVAL)
10372

    
10373

    
10374
class LUGetTags(TagsLU):
10375
  """Returns the tags of a given object.
10376

10377
  """
10378
  _OP_PARAMS = [
10379
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10380
    # Name is only meaningful for nodes and instances
10381
    ("name", ht.NoDefault, ht.TMaybeString),
10382
    ]
10383
  REQ_BGL = False
10384

    
10385
  def ExpandNames(self):
10386
    TagsLU.ExpandNames(self)
10387

    
10388
    # Share locks as this is only a read operation
10389
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10390

    
10391
  def Exec(self, feedback_fn):
10392
    """Returns the tag list.
10393

10394
    """
10395
    return list(self.target.GetTags())
10396

    
10397

    
10398
class LUSearchTags(NoHooksLU):
10399
  """Searches the tags for a given pattern.
10400

10401
  """
10402
  _OP_PARAMS = [
10403
    ("pattern", ht.NoDefault, ht.TNonEmptyString),
10404
    ]
10405
  REQ_BGL = False
10406

    
10407
  def ExpandNames(self):
10408
    self.needed_locks = {}
10409

    
10410
  def CheckPrereq(self):
10411
    """Check prerequisites.
10412

10413
    This checks the pattern passed for validity by compiling it.
10414

10415
    """
10416
    try:
10417
      self.re = re.compile(self.op.pattern)
10418
    except re.error, err:
10419
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10420
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10421

    
10422
  def Exec(self, feedback_fn):
10423
    """Returns the tag list.
10424

10425
    """
10426
    cfg = self.cfg
10427
    tgts = [("/cluster", cfg.GetClusterInfo())]
10428
    ilist = cfg.GetAllInstancesInfo().values()
10429
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10430
    nlist = cfg.GetAllNodesInfo().values()
10431
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10432
    results = []
10433
    for path, target in tgts:
10434
      for tag in target.GetTags():
10435
        if self.re.search(tag):
10436
          results.append((path, tag))
10437
    return results
10438

    
10439

    
10440
class LUAddTags(TagsLU):
10441
  """Sets a tag on a given object.
10442

10443
  """
10444
  _OP_PARAMS = [
10445
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10446
    # Name is only meaningful for nodes and instances
10447
    ("name", ht.NoDefault, ht.TMaybeString),
10448
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10449
    ]
10450
  REQ_BGL = False
10451

    
10452
  def CheckPrereq(self):
10453
    """Check prerequisites.
10454

10455
    This checks the type and length of the tag name and value.
10456

10457
    """
10458
    TagsLU.CheckPrereq(self)
10459
    for tag in self.op.tags:
10460
      objects.TaggableObject.ValidateTag(tag)
10461

    
10462
  def Exec(self, feedback_fn):
10463
    """Sets the tag.
10464

10465
    """
10466
    try:
10467
      for tag in self.op.tags:
10468
        self.target.AddTag(tag)
10469
    except errors.TagError, err:
10470
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10471
    self.cfg.Update(self.target, feedback_fn)
10472

    
10473

    
10474
class LUDelTags(TagsLU):
10475
  """Delete a list of tags from a given object.
10476

10477
  """
10478
  _OP_PARAMS = [
10479
    ("kind", ht.NoDefault, ht.TElemOf(constants.VALID_TAG_TYPES)),
10480
    # Name is only meaningful for nodes and instances
10481
    ("name", ht.NoDefault, ht.TMaybeString),
10482
    ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
10483
    ]
10484
  REQ_BGL = False
10485

    
10486
  def CheckPrereq(self):
10487
    """Check prerequisites.
10488

10489
    This checks that we have the given tag.
10490

10491
    """
10492
    TagsLU.CheckPrereq(self)
10493
    for tag in self.op.tags:
10494
      objects.TaggableObject.ValidateTag(tag)
10495
    del_tags = frozenset(self.op.tags)
10496
    cur_tags = self.target.GetTags()
10497

    
10498
    diff_tags = del_tags - cur_tags
10499
    if diff_tags:
10500
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10501
      raise errors.OpPrereqError("Tag(s) %s not found" %
10502
                                 (utils.CommaJoin(diff_names), ),
10503
                                 errors.ECODE_NOENT)
10504

    
10505
  def Exec(self, feedback_fn):
10506
    """Remove the tag from the object.
10507

10508
    """
10509
    for tag in self.op.tags:
10510
      self.target.RemoveTag(tag)
10511
    self.cfg.Update(self.target, feedback_fn)
10512

    
10513

    
10514
class LUTestDelay(NoHooksLU):
10515
  """Sleep for a specified amount of time.
10516

10517
  This LU sleeps on the master and/or nodes for a specified amount of
10518
  time.
10519

10520
  """
10521
  _OP_PARAMS = [
10522
    ("duration", ht.NoDefault, ht.TFloat),
10523
    ("on_master", True, ht.TBool),
10524
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
10525
    ("repeat", 0, ht.TPositiveInt)
10526
    ]
10527
  REQ_BGL = False
10528

    
10529
  def ExpandNames(self):
10530
    """Expand names and set required locks.
10531

10532
    This expands the node list, if any.
10533

10534
    """
10535
    self.needed_locks = {}
10536
    if self.op.on_nodes:
10537
      # _GetWantedNodes can be used here, but is not always appropriate to use
10538
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10539
      # more information.
10540
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10541
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10542

    
10543
  def _TestDelay(self):
10544
    """Do the actual sleep.
10545

10546
    """
10547
    if self.op.on_master:
10548
      if not utils.TestDelay(self.op.duration):
10549
        raise errors.OpExecError("Error during master delay test")
10550
    if self.op.on_nodes:
10551
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10552
      for node, node_result in result.items():
10553
        node_result.Raise("Failure during rpc call to node %s" % node)
10554

    
10555
  def Exec(self, feedback_fn):
10556
    """Execute the test delay opcode, with the wanted repetitions.
10557

10558
    """
10559
    if self.op.repeat == 0:
10560
      self._TestDelay()
10561
    else:
10562
      top_value = self.op.repeat - 1
10563
      for i in range(self.op.repeat):
10564
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10565
        self._TestDelay()
10566

    
10567

    
10568
class LUTestJobqueue(NoHooksLU):
10569
  """Utility LU to test some aspects of the job queue.
10570

10571
  """
10572
  _OP_PARAMS = [
10573
    ("notify_waitlock", False, ht.TBool),
10574
    ("notify_exec", False, ht.TBool),
10575
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString)),
10576
    ("fail", False, ht.TBool),
10577
    ]
10578
  REQ_BGL = False
10579

    
10580
  # Must be lower than default timeout for WaitForJobChange to see whether it
10581
  # notices changed jobs
10582
  _CLIENT_CONNECT_TIMEOUT = 20.0
10583
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10584

    
10585
  @classmethod
10586
  def _NotifyUsingSocket(cls, cb, errcls):
10587
    """Opens a Unix socket and waits for another program to connect.
10588

10589
    @type cb: callable
10590
    @param cb: Callback to send socket name to client
10591
    @type errcls: class
10592
    @param errcls: Exception class to use for errors
10593

10594
    """
10595
    # Using a temporary directory as there's no easy way to create temporary
10596
    # sockets without writing a custom loop around tempfile.mktemp and
10597
    # socket.bind
10598
    tmpdir = tempfile.mkdtemp()
10599
    try:
10600
      tmpsock = utils.PathJoin(tmpdir, "sock")
10601

    
10602
      logging.debug("Creating temporary socket at %s", tmpsock)
10603
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10604
      try:
10605
        sock.bind(tmpsock)
10606
        sock.listen(1)
10607

    
10608
        # Send details to client
10609
        cb(tmpsock)
10610

    
10611
        # Wait for client to connect before continuing
10612
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10613
        try:
10614
          (conn, _) = sock.accept()
10615
        except socket.error, err:
10616
          raise errcls("Client didn't connect in time (%s)" % err)
10617
      finally:
10618
        sock.close()
10619
    finally:
10620
      # Remove as soon as client is connected
10621
      shutil.rmtree(tmpdir)
10622

    
10623
    # Wait for client to close
10624
    try:
10625
      try:
10626
        # pylint: disable-msg=E1101
10627
        # Instance of '_socketobject' has no ... member
10628
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10629
        conn.recv(1)
10630
      except socket.error, err:
10631
        raise errcls("Client failed to confirm notification (%s)" % err)
10632
    finally:
10633
      conn.close()
10634

    
10635
  def _SendNotification(self, test, arg, sockname):
10636
    """Sends a notification to the client.
10637

10638
    @type test: string
10639
    @param test: Test name
10640
    @param arg: Test argument (depends on test)
10641
    @type sockname: string
10642
    @param sockname: Socket path
10643

10644
    """
10645
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10646

    
10647
  def _Notify(self, prereq, test, arg):
10648
    """Notifies the client of a test.
10649

10650
    @type prereq: bool
10651
    @param prereq: Whether this is a prereq-phase test
10652
    @type test: string
10653
    @param test: Test name
10654
    @param arg: Test argument (depends on test)
10655

10656
    """
10657
    if prereq:
10658
      errcls = errors.OpPrereqError
10659
    else:
10660
      errcls = errors.OpExecError
10661

    
10662
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10663
                                                  test, arg),
10664
                                   errcls)
10665

    
10666
  def CheckArguments(self):
10667
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10668
    self.expandnames_calls = 0
10669

    
10670
  def ExpandNames(self):
10671
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10672
    if checkargs_calls < 1:
10673
      raise errors.ProgrammerError("CheckArguments was not called")
10674

    
10675
    self.expandnames_calls += 1
10676

    
10677
    if self.op.notify_waitlock:
10678
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10679

    
10680
    self.LogInfo("Expanding names")
10681

    
10682
    # Get lock on master node (just to get a lock, not for a particular reason)
10683
    self.needed_locks = {
10684
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10685
      }
10686

    
10687
  def Exec(self, feedback_fn):
10688
    if self.expandnames_calls < 1:
10689
      raise errors.ProgrammerError("ExpandNames was not called")
10690

    
10691
    if self.op.notify_exec:
10692
      self._Notify(False, constants.JQT_EXEC, None)
10693

    
10694
    self.LogInfo("Executing")
10695

    
10696
    if self.op.log_messages:
10697
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10698
      for idx, msg in enumerate(self.op.log_messages):
10699
        self.LogInfo("Sending log message %s", idx + 1)
10700
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10701
        # Report how many test messages have been sent
10702
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10703

    
10704
    if self.op.fail:
10705
      raise errors.OpExecError("Opcode failure was requested")
10706

    
10707
    return True
10708

    
10709

    
10710
class IAllocator(object):
10711
  """IAllocator framework.
10712

10713
  An IAllocator instance has three sets of attributes:
10714
    - cfg that is needed to query the cluster
10715
    - input data (all members of the _KEYS class attribute are required)
10716
    - four buffer attributes (in|out_data|text), that represent the
10717
      input (to the external script) in text and data structure format,
10718
      and the output from it, again in two formats
10719
    - the result variables from the script (success, info, nodes) for
10720
      easy usage
10721

10722
  """
10723
  # pylint: disable-msg=R0902
10724
  # lots of instance attributes
10725
  _ALLO_KEYS = [
10726
    "name", "mem_size", "disks", "disk_template",
10727
    "os", "tags", "nics", "vcpus", "hypervisor",
10728
    ]
10729
  _RELO_KEYS = [
10730
    "name", "relocate_from",
10731
    ]
10732
  _EVAC_KEYS = [
10733
    "evac_nodes",
10734
    ]
10735

    
10736
  def __init__(self, cfg, rpc, mode, **kwargs):
10737
    self.cfg = cfg
10738
    self.rpc = rpc
10739
    # init buffer variables
10740
    self.in_text = self.out_text = self.in_data = self.out_data = None
10741
    # init all input fields so that pylint is happy
10742
    self.mode = mode
10743
    self.mem_size = self.disks = self.disk_template = None
10744
    self.os = self.tags = self.nics = self.vcpus = None
10745
    self.hypervisor = None
10746
    self.relocate_from = None
10747
    self.name = None
10748
    self.evac_nodes = None
10749
    # computed fields
10750
    self.required_nodes = None
10751
    # init result fields
10752
    self.success = self.info = self.result = None
10753
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10754
      keyset = self._ALLO_KEYS
10755
      fn = self._AddNewInstance
10756
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10757
      keyset = self._RELO_KEYS
10758
      fn = self._AddRelocateInstance
10759
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10760
      keyset = self._EVAC_KEYS
10761
      fn = self._AddEvacuateNodes
10762
    else:
10763
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10764
                                   " IAllocator" % self.mode)
10765
    for key in kwargs:
10766
      if key not in keyset:
10767
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10768
                                     " IAllocator" % key)
10769
      setattr(self, key, kwargs[key])
10770

    
10771
    for key in keyset:
10772
      if key not in kwargs:
10773
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10774
                                     " IAllocator" % key)
10775
    self._BuildInputData(fn)
10776

    
10777
  def _ComputeClusterData(self):
10778
    """Compute the generic allocator input data.
10779

10780
    This is the data that is independent of the actual operation.
10781

10782
    """
10783
    cfg = self.cfg
10784
    cluster_info = cfg.GetClusterInfo()
10785
    # cluster data
10786
    data = {
10787
      "version": constants.IALLOCATOR_VERSION,
10788
      "cluster_name": cfg.GetClusterName(),
10789
      "cluster_tags": list(cluster_info.GetTags()),
10790
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10791
      # we don't have job IDs
10792
      }
10793
    iinfo = cfg.GetAllInstancesInfo().values()
10794
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10795

    
10796
    # node data
10797
    node_list = cfg.GetNodeList()
10798

    
10799
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10800
      hypervisor_name = self.hypervisor
10801
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10802
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10803
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10804
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10805

    
10806
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10807
                                        hypervisor_name)
10808
    node_iinfo = \
10809
      self.rpc.call_all_instances_info(node_list,
10810
                                       cluster_info.enabled_hypervisors)
10811

    
10812
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10813

    
10814
    data["nodes"] = self._ComputeNodeData(cfg, node_data, node_iinfo, i_list)
10815

    
10816
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10817

    
10818
    self.in_data = data
10819

    
10820
  @staticmethod
10821
  def _ComputeNodeGroupData(cfg):
10822
    """Compute node groups data.
10823

10824
    """
10825
    ng = {}
10826
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10827
      ng[guuid] = { "name": gdata.name }
10828
    return ng
10829

    
10830
  @staticmethod
10831
  def _ComputeNodeData(cfg, node_data, node_iinfo, i_list):
10832
    """Compute global node data.
10833

10834
    """
10835
    node_results = {}
10836
    for nname, nresult in node_data.items():
10837
      # first fill in static (config-based) values
10838
      ninfo = cfg.GetNodeInfo(nname)
10839
      pnr = {
10840
        "tags": list(ninfo.GetTags()),
10841
        "primary_ip": ninfo.primary_ip,
10842
        "secondary_ip": ninfo.secondary_ip,
10843
        "offline": ninfo.offline,
10844
        "drained": ninfo.drained,
10845
        "master_candidate": ninfo.master_candidate,
10846
        "group": ninfo.group,
10847
        "master_capable": ninfo.master_capable,
10848
        "vm_capable": ninfo.vm_capable,
10849
        }
10850

    
10851
      if not (ninfo.offline or ninfo.drained):
10852
        nresult.Raise("Can't get data for node %s" % nname)
10853
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10854
                                nname)
10855
        remote_info = nresult.payload
10856

    
10857
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10858
                     'vg_size', 'vg_free', 'cpu_total']:
10859
          if attr not in remote_info:
10860
            raise errors.OpExecError("Node '%s' didn't return attribute"
10861
                                     " '%s'" % (nname, attr))
10862
          if not isinstance(remote_info[attr], int):
10863
            raise errors.OpExecError("Node '%s' returned invalid value"
10864
                                     " for '%s': %s" %
10865
                                     (nname, attr, remote_info[attr]))
10866
        # compute memory used by primary instances
10867
        i_p_mem = i_p_up_mem = 0
10868
        for iinfo, beinfo in i_list:
10869
          if iinfo.primary_node == nname:
10870
            i_p_mem += beinfo[constants.BE_MEMORY]
10871
            if iinfo.name not in node_iinfo[nname].payload:
10872
              i_used_mem = 0
10873
            else:
10874
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10875
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10876
            remote_info['memory_free'] -= max(0, i_mem_diff)
10877

    
10878
            if iinfo.admin_up:
10879
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10880

    
10881
        # compute memory used by instances
10882
        pnr_dyn = {
10883
          "total_memory": remote_info['memory_total'],
10884
          "reserved_memory": remote_info['memory_dom0'],
10885
          "free_memory": remote_info['memory_free'],
10886
          "total_disk": remote_info['vg_size'],
10887
          "free_disk": remote_info['vg_free'],
10888
          "total_cpus": remote_info['cpu_total'],
10889
          "i_pri_memory": i_p_mem,
10890
          "i_pri_up_memory": i_p_up_mem,
10891
          }
10892
        pnr.update(pnr_dyn)
10893

    
10894
      node_results[nname] = pnr
10895

    
10896
    return node_results
10897

    
10898
  @staticmethod
10899
  def _ComputeInstanceData(cluster_info, i_list):
10900
    """Compute global instance data.
10901

10902
    """
10903
    instance_data = {}
10904
    for iinfo, beinfo in i_list:
10905
      nic_data = []
10906
      for nic in iinfo.nics:
10907
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10908
        nic_dict = {"mac": nic.mac,
10909
                    "ip": nic.ip,
10910
                    "mode": filled_params[constants.NIC_MODE],
10911
                    "link": filled_params[constants.NIC_LINK],
10912
                   }
10913
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10914
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10915
        nic_data.append(nic_dict)
10916
      pir = {
10917
        "tags": list(iinfo.GetTags()),
10918
        "admin_up": iinfo.admin_up,
10919
        "vcpus": beinfo[constants.BE_VCPUS],
10920
        "memory": beinfo[constants.BE_MEMORY],
10921
        "os": iinfo.os,
10922
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10923
        "nics": nic_data,
10924
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10925
        "disk_template": iinfo.disk_template,
10926
        "hypervisor": iinfo.hypervisor,
10927
        }
10928
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10929
                                                 pir["disks"])
10930
      instance_data[iinfo.name] = pir
10931

    
10932
    return instance_data
10933

    
10934
  def _AddNewInstance(self):
10935
    """Add new instance data to allocator structure.
10936

10937
    This in combination with _AllocatorGetClusterData will create the
10938
    correct structure needed as input for the allocator.
10939

10940
    The checks for the completeness of the opcode must have already been
10941
    done.
10942

10943
    """
10944
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10945

    
10946
    if self.disk_template in constants.DTS_NET_MIRROR:
10947
      self.required_nodes = 2
10948
    else:
10949
      self.required_nodes = 1
10950
    request = {
10951
      "name": self.name,
10952
      "disk_template": self.disk_template,
10953
      "tags": self.tags,
10954
      "os": self.os,
10955
      "vcpus": self.vcpus,
10956
      "memory": self.mem_size,
10957
      "disks": self.disks,
10958
      "disk_space_total": disk_space,
10959
      "nics": self.nics,
10960
      "required_nodes": self.required_nodes,
10961
      }
10962
    return request
10963

    
10964
  def _AddRelocateInstance(self):
10965
    """Add relocate instance data to allocator structure.
10966

10967
    This in combination with _IAllocatorGetClusterData will create the
10968
    correct structure needed as input for the allocator.
10969

10970
    The checks for the completeness of the opcode must have already been
10971
    done.
10972

10973
    """
10974
    instance = self.cfg.GetInstanceInfo(self.name)
10975
    if instance is None:
10976
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10977
                                   " IAllocator" % self.name)
10978

    
10979
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10980
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10981
                                 errors.ECODE_INVAL)
10982

    
10983
    if len(instance.secondary_nodes) != 1:
10984
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10985
                                 errors.ECODE_STATE)
10986

    
10987
    self.required_nodes = 1
10988
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10989
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10990

    
10991
    request = {
10992
      "name": self.name,
10993
      "disk_space_total": disk_space,
10994
      "required_nodes": self.required_nodes,
10995
      "relocate_from": self.relocate_from,
10996
      }
10997
    return request
10998

    
10999
  def _AddEvacuateNodes(self):
11000
    """Add evacuate nodes data to allocator structure.
11001

11002
    """
11003
    request = {
11004
      "evac_nodes": self.evac_nodes
11005
      }
11006
    return request
11007

    
11008
  def _BuildInputData(self, fn):
11009
    """Build input data structures.
11010

11011
    """
11012
    self._ComputeClusterData()
11013

    
11014
    request = fn()
11015
    request["type"] = self.mode
11016
    self.in_data["request"] = request
11017

    
11018
    self.in_text = serializer.Dump(self.in_data)
11019

    
11020
  def Run(self, name, validate=True, call_fn=None):
11021
    """Run an instance allocator and return the results.
11022

11023
    """
11024
    if call_fn is None:
11025
      call_fn = self.rpc.call_iallocator_runner
11026

    
11027
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11028
    result.Raise("Failure while running the iallocator script")
11029

    
11030
    self.out_text = result.payload
11031
    if validate:
11032
      self._ValidateResult()
11033

    
11034
  def _ValidateResult(self):
11035
    """Process the allocator results.
11036

11037
    This will process and if successful save the result in
11038
    self.out_data and the other parameters.
11039

11040
    """
11041
    try:
11042
      rdict = serializer.Load(self.out_text)
11043
    except Exception, err:
11044
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11045

    
11046
    if not isinstance(rdict, dict):
11047
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11048

    
11049
    # TODO: remove backwards compatiblity in later versions
11050
    if "nodes" in rdict and "result" not in rdict:
11051
      rdict["result"] = rdict["nodes"]
11052
      del rdict["nodes"]
11053

    
11054
    for key in "success", "info", "result":
11055
      if key not in rdict:
11056
        raise errors.OpExecError("Can't parse iallocator results:"
11057
                                 " missing key '%s'" % key)
11058
      setattr(self, key, rdict[key])
11059

    
11060
    if not isinstance(rdict["result"], list):
11061
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11062
                               " is not a list")
11063
    self.out_data = rdict
11064

    
11065

    
11066
class LUTestAllocator(NoHooksLU):
11067
  """Run allocator tests.
11068

11069
  This LU runs the allocator tests
11070

11071
  """
11072
  _OP_PARAMS = [
11073
    ("direction", ht.NoDefault,
11074
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
11075
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES)),
11076
    ("name", ht.NoDefault, ht.TNonEmptyString),
11077
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
11078
      ht.TDictOf(ht.TElemOf(["mac", "ip", "bridge"]),
11079
               ht.TOr(ht.TNone, ht.TNonEmptyString))))),
11080
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList)),
11081
    ("hypervisor", None, ht.TMaybeString),
11082
    ("allocator", None, ht.TMaybeString),
11083
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
11084
    ("mem_size", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
11085
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt)),
11086
    ("os", None, ht.TMaybeString),
11087
    ("disk_template", None, ht.TMaybeString),
11088
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString))),
11089
    ]
11090

    
11091
  def CheckPrereq(self):
11092
    """Check prerequisites.
11093

11094
    This checks the opcode parameters depending on the director and mode test.
11095

11096
    """
11097
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11098
      for attr in ["mem_size", "disks", "disk_template",
11099
                   "os", "tags", "nics", "vcpus"]:
11100
        if not hasattr(self.op, attr):
11101
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11102
                                     attr, errors.ECODE_INVAL)
11103
      iname = self.cfg.ExpandInstanceName(self.op.name)
11104
      if iname is not None:
11105
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11106
                                   iname, errors.ECODE_EXISTS)
11107
      if not isinstance(self.op.nics, list):
11108
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11109
                                   errors.ECODE_INVAL)
11110
      if not isinstance(self.op.disks, list):
11111
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11112
                                   errors.ECODE_INVAL)
11113
      for row in self.op.disks:
11114
        if (not isinstance(row, dict) or
11115
            "size" not in row or
11116
            not isinstance(row["size"], int) or
11117
            "mode" not in row or
11118
            row["mode"] not in ['r', 'w']):
11119
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11120
                                     " parameter", errors.ECODE_INVAL)
11121
      if self.op.hypervisor is None:
11122
        self.op.hypervisor = self.cfg.GetHypervisorType()
11123
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11124
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11125
      self.op.name = fname
11126
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11127
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11128
      if not hasattr(self.op, "evac_nodes"):
11129
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11130
                                   " opcode input", errors.ECODE_INVAL)
11131
    else:
11132
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11133
                                 self.op.mode, errors.ECODE_INVAL)
11134

    
11135
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11136
      if self.op.allocator is None:
11137
        raise errors.OpPrereqError("Missing allocator name",
11138
                                   errors.ECODE_INVAL)
11139
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11140
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11141
                                 self.op.direction, errors.ECODE_INVAL)
11142

    
11143
  def Exec(self, feedback_fn):
11144
    """Run the allocator test.
11145

11146
    """
11147
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11148
      ial = IAllocator(self.cfg, self.rpc,
11149
                       mode=self.op.mode,
11150
                       name=self.op.name,
11151
                       mem_size=self.op.mem_size,
11152
                       disks=self.op.disks,
11153
                       disk_template=self.op.disk_template,
11154
                       os=self.op.os,
11155
                       tags=self.op.tags,
11156
                       nics=self.op.nics,
11157
                       vcpus=self.op.vcpus,
11158
                       hypervisor=self.op.hypervisor,
11159
                       )
11160
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11161
      ial = IAllocator(self.cfg, self.rpc,
11162
                       mode=self.op.mode,
11163
                       name=self.op.name,
11164
                       relocate_from=list(self.relocate_from),
11165
                       )
11166
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11167
      ial = IAllocator(self.cfg, self.rpc,
11168
                       mode=self.op.mode,
11169
                       evac_nodes=self.op.evac_nodes)
11170
    else:
11171
      raise errors.ProgrammerError("Uncatched mode %s in"
11172
                                   " LUTestAllocator.Exec", self.op.mode)
11173

    
11174
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11175
      result = ial.in_text
11176
    else:
11177
      ial.Run(self.op.allocator, validate=False)
11178
      result = ial.out_text
11179
    return result