Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ edd8fe4c

History | View | Annotate | Download (393.2 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

    
44
from ganeti import ssh
45
from ganeti import utils
46
from ganeti import errors
47
from ganeti import hypervisor
48
from ganeti import locking
49
from ganeti import constants
50
from ganeti import objects
51
from ganeti import serializer
52
from ganeti import ssconf
53
from ganeti import uidpool
54
from ganeti import compat
55
from ganeti import masterd
56
from ganeti import netutils
57
from ganeti import query
58
from ganeti import qlang
59
from ganeti import opcodes
60

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

    
63

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

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

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

    
76

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

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

90
  Note that all commands require root permissions.
91

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

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

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

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

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

    
133
    # Tasklets
134
    self.tasklets = None
135

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

    
139
    self.CheckArguments()
140

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

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

    
149
  ssh = property(fget=__GetSSH)
150

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

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

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

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

166
    """
167
    pass
168

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

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

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

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

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

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

194
    Examples::
195

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

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

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

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

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

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

233
    """
234

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

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

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

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

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

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

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

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

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

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

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

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

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

292
    """
293
    raise NotImplementedError
294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
381
    del self.recalculate_locks[locking.LEVEL_NODE]
382

    
383

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

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

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

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

397
    This just raises an error.
398

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

    
402

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

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

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

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

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

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

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

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

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

435
    """
436
    pass
437

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

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

445
    """
446
    raise NotImplementedError
447

    
448

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

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

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

459
    """
460
    self.names = names
461
    self.use_locking = use_locking
462

    
463
    self.query = query.Query(self.FIELDS, fields)
464
    self.requested_data = self.query.RequestedData()
465

    
466
    self.do_locking = None
467
    self.wanted = None
468

    
469
  def _GetNames(self, lu, all_names, lock_level):
470
    """Helper function to determine names asked for in the query.
471

472
    """
473
    if self.do_locking:
474
      names = lu.acquired_locks[lock_level]
475
    else:
476
      names = all_names
477

    
478
    if self.wanted == locking.ALL_SET:
479
      assert not self.names
480
      # caller didn't specify names, so ordering is not important
481
      return utils.NiceSort(names)
482

    
483
    # caller specified names and we must keep the same order
484
    assert self.names
485
    assert not self.do_locking or lu.acquired_locks[lock_level]
486

    
487
    missing = set(self.wanted).difference(names)
488
    if missing:
489
      raise errors.OpExecError("Some items were removed before retrieving"
490
                               " their data: %s" % missing)
491

    
492
    # Return expanded names
493
    return self.wanted
494

    
495
  @classmethod
496
  def FieldsQuery(cls, fields):
497
    """Returns list of available fields.
498

499
    @return: List of L{objects.QueryFieldDefinition}
500

501
    """
502
    return query.QueryFields(cls.FIELDS, fields)
503

    
504
  def ExpandNames(self, lu):
505
    """Expand names for this query.
506

507
    See L{LogicalUnit.ExpandNames}.
508

509
    """
510
    raise NotImplementedError()
511

    
512
  def DeclareLocks(self, lu, level):
513
    """Declare locks for this query.
514

515
    See L{LogicalUnit.DeclareLocks}.
516

517
    """
518
    raise NotImplementedError()
519

    
520
  def _GetQueryData(self, lu):
521
    """Collects all data for this query.
522

523
    @return: Query data object
524

525
    """
526
    raise NotImplementedError()
527

    
528
  def NewStyleQuery(self, lu):
529
    """Collect data and execute query.
530

531
    """
532
    return query.GetQueryResponse(self.query, self._GetQueryData(lu))
533

    
534
  def OldStyleQuery(self, lu):
535
    """Collect data and execute query.
536

537
    """
538
    return self.query.OldStyleQuery(self._GetQueryData(lu))
539

    
540

    
541
def _GetWantedNodes(lu, nodes):
542
  """Returns list of checked and expanded node names.
543

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

552
  """
553
  if nodes:
554
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
555

    
556
  return utils.NiceSort(lu.cfg.GetNodeList())
557

    
558

    
559
def _GetWantedInstances(lu, instances):
560
  """Returns list of checked and expanded instance names.
561

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

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

    
578

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

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

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

    
611

    
612
def _CheckOutputFields(static, dynamic, selected):
613
  """Checks whether all selected fields are valid.
614

615
  @type static: L{utils.FieldSet}
616
  @param static: static fields set
617
  @type dynamic: L{utils.FieldSet}
618
  @param dynamic: dynamic fields set
619

620
  """
621
  f = utils.FieldSet()
622
  f.Extend(static)
623
  f.Extend(dynamic)
624

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

    
630

    
631
def _CheckGlobalHvParams(params):
632
  """Validates that given hypervisor params are not global ones.
633

634
  This will ensure that instances don't get customised versions of
635
  global params.
636

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

    
645

    
646
def _CheckNodeOnline(lu, node, msg=None):
647
  """Ensure that a given node is online.
648

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

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

    
660

    
661
def _CheckNodeNotDrained(lu, node):
662
  """Ensure that a given node is not drained.
663

664
  @param lu: the LU on behalf of which we make the check
665
  @param node: the node to check
666
  @raise errors.OpPrereqError: if the node is drained
667

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

    
673

    
674
def _CheckNodeVmCapable(lu, node):
675
  """Ensure that a given node is vm capable.
676

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

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

    
686

    
687
def _CheckNodeHasOS(lu, node, os_name, force_variant):
688
  """Ensure that a node supports a given OS.
689

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

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

    
704

    
705
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
706
  """Ensure that a node has the given secondary ip.
707

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

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

    
731

    
732
def _GetClusterDomainSecret():
733
  """Reads the cluster domain secret.
734

735
  """
736
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
737
                               strict=True)
738

    
739

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

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

    
751
  if instance.name in ins_l.payload:
752
    raise errors.OpPrereqError("Instance %s is running, %s" %
753
                               (instance.name, reason), errors.ECODE_STATE)
754

    
755

    
756
def _ExpandItemName(fn, name, kind):
757
  """Expand an item name.
758

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

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

    
772

    
773
def _ExpandNodeName(cfg, name):
774
  """Wrapper over L{_ExpandItemName} for nodes."""
775
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
776

    
777

    
778
def _ExpandInstanceName(cfg, name):
779
  """Wrapper over L{_ExpandItemName} for instance."""
780
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
781

    
782

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

788
  This builds the hook environment from individual variables.
789

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

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

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

    
852
  env["INSTANCE_NIC_COUNT"] = nic_count
853

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

    
862
  env["INSTANCE_DISK_COUNT"] = disk_count
863

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

    
868
  return env
869

    
870

    
871
def _NICListToTuple(lu, nics):
872
  """Build a list of nic information tuples.
873

874
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
875
  value in LUInstanceQueryData.
876

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

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

    
894

    
895
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
896
  """Builds instance related env variables for hooks from an object.
897

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

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

    
932

    
933
def _AdjustCandidatePool(lu, exceptions):
934
  """Adjust the candidate pool after node operations.
935

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

    
948

    
949
def _DecideSelfPromotion(lu, exceptions=None):
950
  """Decide whether I should promote myself as a master candidate.
951

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

    
959

    
960
def _CheckNicsBridgesExist(lu, target_nics, target_node):
961
  """Check that the brigdes needed by a list of nics exist.
962

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

    
973

    
974
def _CheckInstanceBridgesExist(lu, instance, node=None):
975
  """Check that the brigdes needed by an instance exist.
976

977
  """
978
  if node is None:
979
    node = instance.primary_node
980
  _CheckNicsBridgesExist(lu, instance.nics, node)
981

    
982

    
983
def _CheckOSVariant(os_obj, name):
984
  """Check whether an OS name conforms to the os variants specification.
985

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

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

    
999
  if variant not in os_obj.supported_variants:
1000
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1001

    
1002

    
1003
def _GetNodeInstancesInner(cfg, fn):
1004
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1005

    
1006

    
1007
def _GetNodeInstances(cfg, node_name):
1008
  """Returns a list of all primary and secondary instances on a node.
1009

1010
  """
1011

    
1012
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1013

    
1014

    
1015
def _GetNodePrimaryInstances(cfg, node_name):
1016
  """Returns primary instances on a node.
1017

1018
  """
1019
  return _GetNodeInstancesInner(cfg,
1020
                                lambda inst: node_name == inst.primary_node)
1021

    
1022

    
1023
def _GetNodeSecondaryInstances(cfg, node_name):
1024
  """Returns secondary instances on a node.
1025

1026
  """
1027
  return _GetNodeInstancesInner(cfg,
1028
                                lambda inst: node_name in inst.secondary_nodes)
1029

    
1030

    
1031
def _GetStorageTypeArgs(cfg, storage_type):
1032
  """Returns the arguments for a storage type.
1033

1034
  """
1035
  # Special case for file storage
1036
  if storage_type == constants.ST_FILE:
1037
    # storage.FileStorage wants a list of storage directories
1038
    return [[cfg.GetFileStorageDir()]]
1039

    
1040
  return []
1041

    
1042

    
1043
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1044
  faulty = []
1045

    
1046
  for dev in instance.disks:
1047
    cfg.SetDiskID(dev, node_name)
1048

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

    
1053
  for idx, bdev_status in enumerate(result.payload):
1054
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1055
      faulty.append(idx)
1056

    
1057
  return faulty
1058

    
1059

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

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

1068
  @type iallocator_slot: string
1069
  @param iallocator_slot: the name of the opcode iallocator slot
1070
  @type node_slot: string
1071
  @param node_slot: the name of the opcode target node slot
1072

1073
  """
1074
  node = getattr(lu.op, node_slot, None)
1075
  iallocator = getattr(lu.op, iallocator_slot, None)
1076

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

    
1091

    
1092
class LUClusterPostInit(LogicalUnit):
1093
  """Logical unit for running hooks after cluster initialization.
1094

1095
  """
1096
  HPATH = "cluster-init"
1097
  HTYPE = constants.HTYPE_CLUSTER
1098

    
1099
  def BuildHooksEnv(self):
1100
    """Build hooks env.
1101

1102
    """
1103
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1104
    mn = self.cfg.GetMasterNode()
1105
    return env, [], [mn]
1106

    
1107
  def Exec(self, feedback_fn):
1108
    """Nothing to do.
1109

1110
    """
1111
    return True
1112

    
1113

    
1114
class LUClusterDestroy(LogicalUnit):
1115
  """Logical unit for destroying the cluster.
1116

1117
  """
1118
  HPATH = "cluster-destroy"
1119
  HTYPE = constants.HTYPE_CLUSTER
1120

    
1121
  def BuildHooksEnv(self):
1122
    """Build hooks env.
1123

1124
    """
1125
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1126
    return env, [], []
1127

    
1128
  def CheckPrereq(self):
1129
    """Check prerequisites.
1130

1131
    This checks whether the cluster is empty.
1132

1133
    Any errors are signaled by raising errors.OpPrereqError.
1134

1135
    """
1136
    master = self.cfg.GetMasterNode()
1137

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

    
1149
  def Exec(self, feedback_fn):
1150
    """Destroys the cluster.
1151

1152
    """
1153
    master = self.cfg.GetMasterNode()
1154

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

    
1163
    result = self.rpc.call_node_stop_master(master, False)
1164
    result.Raise("Could not disable the master role")
1165

    
1166
    return master
1167

    
1168

    
1169
def _VerifyCertificate(filename):
1170
  """Verifies a certificate for LUClusterVerify.
1171

1172
  @type filename: string
1173
  @param filename: Path to PEM file
1174

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

    
1183
  (errcode, msg) = \
1184
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1185
                                constants.SSL_CERT_EXPIRATION_ERROR)
1186

    
1187
  if msg:
1188
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1189
  else:
1190
    fnamemsg = None
1191

    
1192
  if errcode is None:
1193
    return (None, fnamemsg)
1194
  elif errcode == utils.CERT_WARNING:
1195
    return (LUClusterVerify.ETYPE_WARNING, fnamemsg)
1196
  elif errcode == utils.CERT_ERROR:
1197
    return (LUClusterVerify.ETYPE_ERROR, fnamemsg)
1198

    
1199
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1200

    
1201

    
1202
class LUClusterVerify(LogicalUnit):
1203
  """Verifies the cluster status.
1204

1205
  """
1206
  HPATH = "cluster-verify"
1207
  HTYPE = constants.HTYPE_CLUSTER
1208
  REQ_BGL = False
1209

    
1210
  TCLUSTER = "cluster"
1211
  TNODE = "node"
1212
  TINSTANCE = "instance"
1213

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

    
1241
  ETYPE_FIELD = "code"
1242
  ETYPE_ERROR = "ERROR"
1243
  ETYPE_WARNING = "WARNING"
1244

    
1245
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1246

    
1247
  class NodeImage(object):
1248
    """A class representing the logical and physical status of a node.
1249

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

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

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

    
1304
  def _Error(self, ecode, item, msg, *args, **kwargs):
1305
    """Format an error message.
1306

1307
    Based on the opcode's error_codes parameter, either format a
1308
    parseable error code, or a simpler error string.
1309

1310
    This must be called only from Exec and functions called from Exec.
1311

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

    
1330
  def _ErrorIf(self, cond, *args, **kwargs):
1331
    """Log an error message if the passed condition is True.
1332

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

    
1341
  def _VerifyNode(self, ninfo, nresult):
1342
    """Perform some basic validation on data returned from a node.
1343

1344
      - check the result data structure is well formed and has all the
1345
        mandatory fields
1346
      - check ganeti version
1347

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

1355
    """
1356
    node = ninfo.name
1357
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1358

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

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

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

    
1384
    # node seems compatible, we can actually try to look into its results
1385

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

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

    
1400
    test = nresult.get(constants.NV_NODESETUP,
1401
                           ["Missing NODESETUP results"])
1402
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1403
             "; ".join(test))
1404

    
1405
    return True
1406

    
1407
  def _VerifyNodeTime(self, ninfo, nresult,
1408
                      nvinfo_starttime, nvinfo_endtime):
1409
    """Check the node time.
1410

1411
    @type ninfo: L{objects.Node}
1412
    @param ninfo: the node to check
1413
    @param nresult: the remote results for the node
1414
    @param nvinfo_starttime: the start time of the RPC call
1415
    @param nvinfo_endtime: the end time of the RPC call
1416

1417
    """
1418
    node = ninfo.name
1419
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1420

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

    
1428
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1429
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1430
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1431
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1432
    else:
1433
      ntime_diff = None
1434

    
1435
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1436
             "Node time diverges by at least %s from master node time",
1437
             ntime_diff)
1438

    
1439
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1440
    """Check the node time.
1441

1442
    @type ninfo: L{objects.Node}
1443
    @param ninfo: the node to check
1444
    @param nresult: the remote results for the node
1445
    @param vg_name: the configured VG name
1446

1447
    """
1448
    if vg_name is None:
1449
      return
1450

    
1451
    node = ninfo.name
1452
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1453

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

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

    
1476
  def _VerifyNodeNetwork(self, ninfo, nresult):
1477
    """Check the node time.
1478

1479
    @type ninfo: L{objects.Node}
1480
    @param ninfo: the node to check
1481
    @param nresult: the remote results for the node
1482

1483
    """
1484
    node = ninfo.name
1485
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1486

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

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

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

    
1518
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1519
                      diskstatus):
1520
    """Verify an instance.
1521

1522
    This function checks to see if the required block devices are
1523
    available on the instance's node.
1524

1525
    """
1526
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1527
    node_current = instanceconfig.primary_node
1528

    
1529
    node_vol_should = {}
1530
    instanceconfig.MapLVsByNode(node_vol_should)
1531

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

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

    
1549
    for node, n_img in node_image.items():
1550
      if (not node == node_current):
1551
        test = instance in n_img.instances
1552
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1553
                 "instance should not run on node %s", node)
1554

    
1555
    diskdata = [(nname, success, status, idx)
1556
                for (nname, disks) in diskstatus.items()
1557
                for idx, (success, status) in enumerate(disks)]
1558

    
1559
    for nname, success, bdev_status, idx in diskdata:
1560
      _ErrorIf(instanceconfig.admin_up and not success,
1561
               self.EINSTANCEFAULTYDISK, instance,
1562
               "couldn't retrieve status for disk/%s on %s: %s",
1563
               idx, nname, bdev_status)
1564
      _ErrorIf((instanceconfig.admin_up and success and
1565
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1566
               self.EINSTANCEFAULTYDISK, instance,
1567
               "disk/%s on %s is faulty", idx, nname)
1568

    
1569
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1570
    """Verify if there are any unknown volumes in the cluster.
1571

1572
    The .os, .swap and backup volumes are ignored. All other volumes are
1573
    reported as unknown.
1574

1575
    @type reserved: L{ganeti.utils.FieldSet}
1576
    @param reserved: a FieldSet of reserved volume names
1577

1578
    """
1579
    for node, n_img in node_image.items():
1580
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1581
        # skip non-healthy nodes
1582
        continue
1583
      for volume in n_img.volumes:
1584
        test = ((node not in node_vol_should or
1585
                volume not in node_vol_should[node]) and
1586
                not reserved.Matches(volume))
1587
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1588
                      "volume %s is unknown", volume)
1589

    
1590
  def _VerifyOrphanInstances(self, instancelist, node_image):
1591
    """Verify the list of running instances.
1592

1593
    This checks what instances are running but unknown to the cluster.
1594

1595
    """
1596
    for node, n_img in node_image.items():
1597
      for o_inst in n_img.instances:
1598
        test = o_inst not in instancelist
1599
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1600
                      "instance %s on node %s should not exist", o_inst, node)
1601

    
1602
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1603
    """Verify N+1 Memory Resilience.
1604

1605
    Check that if one single node dies we can still start all the
1606
    instances it was primary for.
1607

1608
    """
1609
    for node, n_img in node_image.items():
1610
      # This code checks that every node which is now listed as
1611
      # secondary has enough memory to host all instances it is
1612
      # supposed to should a single other node in the cluster fail.
1613
      # FIXME: not ready for failover to an arbitrary node
1614
      # FIXME: does not support file-backed instances
1615
      # WARNING: we currently take into account down instances as well
1616
      # as up ones, considering that even if they're down someone
1617
      # might want to start them even in the event of a node failure.
1618
      for prinode, instances in n_img.sbp.items():
1619
        needed_mem = 0
1620
        for instance in instances:
1621
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1622
          if bep[constants.BE_AUTO_BALANCE]:
1623
            needed_mem += bep[constants.BE_MEMORY]
1624
        test = n_img.mfree < needed_mem
1625
        self._ErrorIf(test, self.ENODEN1, node,
1626
                      "not enough memory to accomodate instance failovers"
1627
                      " should node %s fail", prinode)
1628

    
1629
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1630
                       master_files):
1631
    """Verifies and computes the node required file checksums.
1632

1633
    @type ninfo: L{objects.Node}
1634
    @param ninfo: the node to check
1635
    @param nresult: the remote results for the node
1636
    @param file_list: required list of files
1637
    @param local_cksum: dictionary of local files and their checksums
1638
    @param master_files: list of files that only masters should have
1639

1640
    """
1641
    node = ninfo.name
1642
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1643

    
1644
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1645
    test = not isinstance(remote_cksum, dict)
1646
    _ErrorIf(test, self.ENODEFILECHECK, node,
1647
             "node hasn't returned file checksum data")
1648
    if test:
1649
      return
1650

    
1651
    for file_name in file_list:
1652
      node_is_mc = ninfo.master_candidate
1653
      must_have = (file_name not in master_files) or node_is_mc
1654
      # missing
1655
      test1 = file_name not in remote_cksum
1656
      # invalid checksum
1657
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1658
      # existing and good
1659
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1660
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1661
               "file '%s' missing", file_name)
1662
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1663
               "file '%s' has wrong checksum", file_name)
1664
      # not candidate and this is not a must-have file
1665
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1666
               "file '%s' should not exist on non master"
1667
               " candidates (and the file is outdated)", file_name)
1668
      # all good, except non-master/non-must have combination
1669
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1670
               "file '%s' should not exist"
1671
               " on non master candidates", file_name)
1672

    
1673
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1674
                      drbd_map):
1675
    """Verifies and the node DRBD status.
1676

1677
    @type ninfo: L{objects.Node}
1678
    @param ninfo: the node to check
1679
    @param nresult: the remote results for the node
1680
    @param instanceinfo: the dict of instances
1681
    @param drbd_helper: the configured DRBD usermode helper
1682
    @param drbd_map: the DRBD map as returned by
1683
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1684

1685
    """
1686
    node = ninfo.name
1687
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1688

    
1689
    if drbd_helper:
1690
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1691
      test = (helper_result == None)
1692
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1693
               "no drbd usermode helper returned")
1694
      if helper_result:
1695
        status, payload = helper_result
1696
        test = not status
1697
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1698
                 "drbd usermode helper check unsuccessful: %s", payload)
1699
        test = status and (payload != drbd_helper)
1700
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1701
                 "wrong drbd usermode helper: %s", payload)
1702

    
1703
    # compute the DRBD minors
1704
    node_drbd = {}
1705
    for minor, instance in drbd_map[node].items():
1706
      test = instance not in instanceinfo
1707
      _ErrorIf(test, self.ECLUSTERCFG, None,
1708
               "ghost instance '%s' in temporary DRBD map", instance)
1709
        # ghost instance should not be running, but otherwise we
1710
        # don't give double warnings (both ghost instance and
1711
        # unallocated minor in use)
1712
      if test:
1713
        node_drbd[minor] = (instance, False)
1714
      else:
1715
        instance = instanceinfo[instance]
1716
        node_drbd[minor] = (instance.name, instance.admin_up)
1717

    
1718
    # and now check them
1719
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1720
    test = not isinstance(used_minors, (tuple, list))
1721
    _ErrorIf(test, self.ENODEDRBD, node,
1722
             "cannot parse drbd status file: %s", str(used_minors))
1723
    if test:
1724
      # we cannot check drbd status
1725
      return
1726

    
1727
    for minor, (iname, must_exist) in node_drbd.items():
1728
      test = minor not in used_minors and must_exist
1729
      _ErrorIf(test, self.ENODEDRBD, node,
1730
               "drbd minor %d of instance %s is not active", minor, iname)
1731
    for minor in used_minors:
1732
      test = minor not in node_drbd
1733
      _ErrorIf(test, self.ENODEDRBD, node,
1734
               "unallocated drbd minor %d is in use", minor)
1735

    
1736
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1737
    """Builds the node OS structures.
1738

1739
    @type ninfo: L{objects.Node}
1740
    @param ninfo: the node to check
1741
    @param nresult: the remote results for the node
1742
    @param nimg: the node image object
1743

1744
    """
1745
    node = ninfo.name
1746
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1747

    
1748
    remote_os = nresult.get(constants.NV_OSLIST, None)
1749
    test = (not isinstance(remote_os, list) or
1750
            not compat.all(isinstance(v, list) and len(v) == 7
1751
                           for v in remote_os))
1752

    
1753
    _ErrorIf(test, self.ENODEOS, node,
1754
             "node hasn't returned valid OS data")
1755

    
1756
    nimg.os_fail = test
1757

    
1758
    if test:
1759
      return
1760

    
1761
    os_dict = {}
1762

    
1763
    for (name, os_path, status, diagnose,
1764
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1765

    
1766
      if name not in os_dict:
1767
        os_dict[name] = []
1768

    
1769
      # parameters is a list of lists instead of list of tuples due to
1770
      # JSON lacking a real tuple type, fix it:
1771
      parameters = [tuple(v) for v in parameters]
1772
      os_dict[name].append((os_path, status, diagnose,
1773
                            set(variants), set(parameters), set(api_ver)))
1774

    
1775
    nimg.oslist = os_dict
1776

    
1777
  def _VerifyNodeOS(self, ninfo, nimg, base):
1778
    """Verifies the node OS list.
1779

1780
    @type ninfo: L{objects.Node}
1781
    @param ninfo: the node to check
1782
    @param nimg: the node image object
1783
    @param base: the 'template' node we match against (e.g. from the master)
1784

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

    
1789
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1790

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

    
1824
    # check any missing OSes
1825
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1826
    _ErrorIf(missing, self.ENODEOS, node,
1827
             "OSes present on reference node %s but missing on this node: %s",
1828
             base.name, utils.CommaJoin(missing))
1829

    
1830
  def _VerifyOob(self, ninfo, nresult):
1831
    """Verifies out of band functionality of a node.
1832

1833
    @type ninfo: L{objects.Node}
1834
    @param ninfo: the node to check
1835
    @param nresult: the remote results for the node
1836

1837
    """
1838
    node = ninfo.name
1839
    # We just have to verify the paths on master and/or master candidates
1840
    # as the oob helper is invoked on the master
1841
    if ((ninfo.master_candidate or ninfo.master_capable) and
1842
        constants.NV_OOB_PATHS in nresult):
1843
      for path_result in nresult[constants.NV_OOB_PATHS]:
1844
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
1845

    
1846
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1847
    """Verifies and updates the node volume data.
1848

1849
    This function will update a L{NodeImage}'s internal structures
1850
    with data from the remote call.
1851

1852
    @type ninfo: L{objects.Node}
1853
    @param ninfo: the node to check
1854
    @param nresult: the remote results for the node
1855
    @param nimg: the node image object
1856
    @param vg_name: the configured VG name
1857

1858
    """
1859
    node = ninfo.name
1860
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1861

    
1862
    nimg.lvm_fail = True
1863
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1864
    if vg_name is None:
1865
      pass
1866
    elif isinstance(lvdata, basestring):
1867
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1868
               utils.SafeEncode(lvdata))
1869
    elif not isinstance(lvdata, dict):
1870
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1871
    else:
1872
      nimg.volumes = lvdata
1873
      nimg.lvm_fail = False
1874

    
1875
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1876
    """Verifies and updates the node instance list.
1877

1878
    If the listing was successful, then updates this node's instance
1879
    list. Otherwise, it marks the RPC call as failed for the instance
1880
    list key.
1881

1882
    @type ninfo: L{objects.Node}
1883
    @param ninfo: the node to check
1884
    @param nresult: the remote results for the node
1885
    @param nimg: the node image object
1886

1887
    """
1888
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1889
    test = not isinstance(idata, list)
1890
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1891
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1892
    if test:
1893
      nimg.hyp_fail = True
1894
    else:
1895
      nimg.instances = idata
1896

    
1897
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1898
    """Verifies and computes a node information map
1899

1900
    @type ninfo: L{objects.Node}
1901
    @param ninfo: the node to check
1902
    @param nresult: the remote results for the node
1903
    @param nimg: the node image object
1904
    @param vg_name: the configured VG name
1905

1906
    """
1907
    node = ninfo.name
1908
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1909

    
1910
    # try to read free memory (from the hypervisor)
1911
    hv_info = nresult.get(constants.NV_HVINFO, None)
1912
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1913
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1914
    if not test:
1915
      try:
1916
        nimg.mfree = int(hv_info["memory_free"])
1917
      except (ValueError, TypeError):
1918
        _ErrorIf(True, self.ENODERPC, node,
1919
                 "node returned invalid nodeinfo, check hypervisor")
1920

    
1921
    # FIXME: devise a free space model for file based instances as well
1922
    if vg_name is not None:
1923
      test = (constants.NV_VGLIST not in nresult or
1924
              vg_name not in nresult[constants.NV_VGLIST])
1925
      _ErrorIf(test, self.ENODELVM, node,
1926
               "node didn't return data for the volume group '%s'"
1927
               " - it is either missing or broken", vg_name)
1928
      if not test:
1929
        try:
1930
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1931
        except (ValueError, TypeError):
1932
          _ErrorIf(True, self.ENODERPC, node,
1933
                   "node returned invalid LVM info, check LVM status")
1934

    
1935
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1936
    """Gets per-disk status information for all instances.
1937

1938
    @type nodelist: list of strings
1939
    @param nodelist: Node names
1940
    @type node_image: dict of (name, L{objects.Node})
1941
    @param node_image: Node objects
1942
    @type instanceinfo: dict of (name, L{objects.Instance})
1943
    @param instanceinfo: Instance objects
1944
    @rtype: {instance: {node: [(succes, payload)]}}
1945
    @return: a dictionary of per-instance dictionaries with nodes as
1946
        keys and disk information as values; the disk information is a
1947
        list of tuples (success, payload)
1948

1949
    """
1950
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1951

    
1952
    node_disks = {}
1953
    node_disks_devonly = {}
1954
    diskless_instances = set()
1955
    diskless = constants.DT_DISKLESS
1956

    
1957
    for nname in nodelist:
1958
      node_instances = list(itertools.chain(node_image[nname].pinst,
1959
                                            node_image[nname].sinst))
1960
      diskless_instances.update(inst for inst in node_instances
1961
                                if instanceinfo[inst].disk_template == diskless)
1962
      disks = [(inst, disk)
1963
               for inst in node_instances
1964
               for disk in instanceinfo[inst].disks]
1965

    
1966
      if not disks:
1967
        # No need to collect data
1968
        continue
1969

    
1970
      node_disks[nname] = disks
1971

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

    
1976
      for dev in devonly:
1977
        self.cfg.SetDiskID(dev, nname)
1978

    
1979
      node_disks_devonly[nname] = devonly
1980

    
1981
    assert len(node_disks) == len(node_disks_devonly)
1982

    
1983
    # Collect data from all nodes with disks
1984
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1985
                                                          node_disks_devonly)
1986

    
1987
    assert len(result) == len(node_disks)
1988

    
1989
    instdisk = {}
1990

    
1991
    for (nname, nres) in result.items():
1992
      disks = node_disks[nname]
1993

    
1994
      if nres.offline:
1995
        # No data from this node
1996
        data = len(disks) * [(False, "node offline")]
1997
      else:
1998
        msg = nres.fail_msg
1999
        _ErrorIf(msg, self.ENODERPC, nname,
2000
                 "while getting disk information: %s", msg)
2001
        if msg:
2002
          # No data from this node
2003
          data = len(disks) * [(False, msg)]
2004
        else:
2005
          data = []
2006
          for idx, i in enumerate(nres.payload):
2007
            if isinstance(i, (tuple, list)) and len(i) == 2:
2008
              data.append(i)
2009
            else:
2010
              logging.warning("Invalid result from node %s, entry %d: %s",
2011
                              nname, idx, i)
2012
              data.append((False, "Invalid result from the remote node"))
2013

    
2014
      for ((inst, _), status) in zip(disks, data):
2015
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2016

    
2017
    # Add empty entries for diskless instances.
2018
    for inst in diskless_instances:
2019
      assert inst not in instdisk
2020
      instdisk[inst] = {}
2021

    
2022
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2023
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2024
                      compat.all(isinstance(s, (tuple, list)) and
2025
                                 len(s) == 2 for s in statuses)
2026
                      for inst, nnames in instdisk.items()
2027
                      for nname, statuses in nnames.items())
2028
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2029

    
2030
    return instdisk
2031

    
2032
  def BuildHooksEnv(self):
2033
    """Build hooks env.
2034

2035
    Cluster-Verify hooks just ran in the post phase and their failure makes
2036
    the output be logged in the verify output and the verification to fail.
2037

2038
    """
2039
    all_nodes = self.cfg.GetNodeList()
2040
    env = {
2041
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2042
      }
2043
    for node in self.cfg.GetAllNodesInfo().values():
2044
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2045

    
2046
    return env, [], all_nodes
2047

    
2048
  def Exec(self, feedback_fn):
2049
    """Verify integrity of cluster, performing various test on nodes.
2050

2051
    """
2052
    # This method has too many local variables. pylint: disable-msg=R0914
2053
    self.bad = False
2054
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2055
    verbose = self.op.verbose
2056
    self._feedback_fn = feedback_fn
2057
    feedback_fn("* Verifying global settings")
2058
    for msg in self.cfg.VerifyConfig():
2059
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2060

    
2061
    # Check the cluster certificates
2062
    for cert_filename in constants.ALL_CERT_FILES:
2063
      (errcode, msg) = _VerifyCertificate(cert_filename)
2064
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2065

    
2066
    vg_name = self.cfg.GetVGName()
2067
    drbd_helper = self.cfg.GetDRBDHelper()
2068
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2069
    cluster = self.cfg.GetClusterInfo()
2070
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2071
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2072
    nodeinfo_byname = dict(zip(nodelist, nodeinfo))
2073
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2074
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2075
                        for iname in instancelist)
2076
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2077
    i_non_redundant = [] # Non redundant instances
2078
    i_non_a_balanced = [] # Non auto-balanced instances
2079
    n_offline = 0 # Count of offline nodes
2080
    n_drained = 0 # Count of nodes being drained
2081
    node_vol_should = {}
2082

    
2083
    # FIXME: verify OS list
2084
    # do local checksums
2085
    master_files = [constants.CLUSTER_CONF_FILE]
2086
    master_node = self.master_node = self.cfg.GetMasterNode()
2087
    master_ip = self.cfg.GetMasterIP()
2088

    
2089
    file_names = ssconf.SimpleStore().GetFileList()
2090
    file_names.extend(constants.ALL_CERT_FILES)
2091
    file_names.extend(master_files)
2092
    if cluster.modify_etc_hosts:
2093
      file_names.append(constants.ETC_HOSTS)
2094

    
2095
    local_checksums = utils.FingerprintFiles(file_names)
2096

    
2097
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2098
    node_verify_param = {
2099
      constants.NV_FILELIST: file_names,
2100
      constants.NV_NODELIST: [node.name for node in nodeinfo
2101
                              if not node.offline],
2102
      constants.NV_HYPERVISOR: hypervisors,
2103
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2104
                                  node.secondary_ip) for node in nodeinfo
2105
                                 if not node.offline],
2106
      constants.NV_INSTANCELIST: hypervisors,
2107
      constants.NV_VERSION: None,
2108
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2109
      constants.NV_NODESETUP: None,
2110
      constants.NV_TIME: None,
2111
      constants.NV_MASTERIP: (master_node, master_ip),
2112
      constants.NV_OSLIST: None,
2113
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2114
      }
2115

    
2116
    if vg_name is not None:
2117
      node_verify_param[constants.NV_VGLIST] = None
2118
      node_verify_param[constants.NV_LVLIST] = vg_name
2119
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2120
      node_verify_param[constants.NV_DRBDLIST] = None
2121

    
2122
    if drbd_helper:
2123
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2124

    
2125
    # Build our expected cluster state
2126
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2127
                                                 name=node.name,
2128
                                                 vm_capable=node.vm_capable))
2129
                      for node in nodeinfo)
2130

    
2131
    # Gather OOB paths
2132
    oob_paths = []
2133
    for node in nodeinfo:
2134
      path = _SupportsOob(self.cfg, node)
2135
      if path and path not in oob_paths:
2136
        oob_paths.append(path)
2137

    
2138
    if oob_paths:
2139
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2140

    
2141
    for instance in instancelist:
2142
      inst_config = instanceinfo[instance]
2143

    
2144
      for nname in inst_config.all_nodes:
2145
        if nname not in node_image:
2146
          # ghost node
2147
          gnode = self.NodeImage(name=nname)
2148
          gnode.ghost = True
2149
          node_image[nname] = gnode
2150

    
2151
      inst_config.MapLVsByNode(node_vol_should)
2152

    
2153
      pnode = inst_config.primary_node
2154
      node_image[pnode].pinst.append(instance)
2155

    
2156
      for snode in inst_config.secondary_nodes:
2157
        nimg = node_image[snode]
2158
        nimg.sinst.append(instance)
2159
        if pnode not in nimg.sbp:
2160
          nimg.sbp[pnode] = []
2161
        nimg.sbp[pnode].append(instance)
2162

    
2163
    # At this point, we have the in-memory data structures complete,
2164
    # except for the runtime information, which we'll gather next
2165

    
2166
    # Due to the way our RPC system works, exact response times cannot be
2167
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2168
    # time before and after executing the request, we can at least have a time
2169
    # window.
2170
    nvinfo_starttime = time.time()
2171
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2172
                                           self.cfg.GetClusterName())
2173
    nvinfo_endtime = time.time()
2174

    
2175
    all_drbd_map = self.cfg.ComputeDRBDMap()
2176

    
2177
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2178
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2179

    
2180
    feedback_fn("* Verifying node status")
2181

    
2182
    refos_img = None
2183

    
2184
    for node_i in nodeinfo:
2185
      node = node_i.name
2186
      nimg = node_image[node]
2187

    
2188
      if node_i.offline:
2189
        if verbose:
2190
          feedback_fn("* Skipping offline node %s" % (node,))
2191
        n_offline += 1
2192
        continue
2193

    
2194
      if node == master_node:
2195
        ntype = "master"
2196
      elif node_i.master_candidate:
2197
        ntype = "master candidate"
2198
      elif node_i.drained:
2199
        ntype = "drained"
2200
        n_drained += 1
2201
      else:
2202
        ntype = "regular"
2203
      if verbose:
2204
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2205

    
2206
      msg = all_nvinfo[node].fail_msg
2207
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2208
      if msg:
2209
        nimg.rpc_fail = True
2210
        continue
2211

    
2212
      nresult = all_nvinfo[node].payload
2213

    
2214
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2215
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2216
      self._VerifyNodeNetwork(node_i, nresult)
2217
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2218
                            master_files)
2219

    
2220
      self._VerifyOob(node_i, nresult)
2221

    
2222
      if nimg.vm_capable:
2223
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2224
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2225
                             all_drbd_map)
2226

    
2227
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2228
        self._UpdateNodeInstances(node_i, nresult, nimg)
2229
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2230
        self._UpdateNodeOS(node_i, nresult, nimg)
2231
        if not nimg.os_fail:
2232
          if refos_img is None:
2233
            refos_img = nimg
2234
          self._VerifyNodeOS(node_i, nimg, refos_img)
2235

    
2236
    feedback_fn("* Verifying instance status")
2237
    for instance in instancelist:
2238
      if verbose:
2239
        feedback_fn("* Verifying instance %s" % instance)
2240
      inst_config = instanceinfo[instance]
2241
      self._VerifyInstance(instance, inst_config, node_image,
2242
                           instdisk[instance])
2243
      inst_nodes_offline = []
2244

    
2245
      pnode = inst_config.primary_node
2246
      pnode_img = node_image[pnode]
2247
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2248
               self.ENODERPC, pnode, "instance %s, connection to"
2249
               " primary node failed", instance)
2250

    
2251
      if pnode_img.offline:
2252
        inst_nodes_offline.append(pnode)
2253

    
2254
      # If the instance is non-redundant we cannot survive losing its primary
2255
      # node, so we are not N+1 compliant. On the other hand we have no disk
2256
      # templates with more than one secondary so that situation is not well
2257
      # supported either.
2258
      # FIXME: does not support file-backed instances
2259
      if not inst_config.secondary_nodes:
2260
        i_non_redundant.append(instance)
2261

    
2262
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2263
               instance, "instance has multiple secondary nodes: %s",
2264
               utils.CommaJoin(inst_config.secondary_nodes),
2265
               code=self.ETYPE_WARNING)
2266

    
2267
      if inst_config.disk_template in constants.DTS_NET_MIRROR:
2268
        pnode = inst_config.primary_node
2269
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2270
        instance_groups = {}
2271

    
2272
        for node in instance_nodes:
2273
          instance_groups.setdefault(nodeinfo_byname[node].group,
2274
                                     []).append(node)
2275

    
2276
        pretty_list = [
2277
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2278
          # Sort so that we always list the primary node first.
2279
          for group, nodes in sorted(instance_groups.items(),
2280
                                     key=lambda (_, nodes): pnode in nodes,
2281
                                     reverse=True)]
2282

    
2283
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2284
                      instance, "instance has primary and secondary nodes in"
2285
                      " different groups: %s", utils.CommaJoin(pretty_list),
2286
                      code=self.ETYPE_WARNING)
2287

    
2288
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2289
        i_non_a_balanced.append(instance)
2290

    
2291
      for snode in inst_config.secondary_nodes:
2292
        s_img = node_image[snode]
2293
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2294
                 "instance %s, connection to secondary node failed", instance)
2295

    
2296
        if s_img.offline:
2297
          inst_nodes_offline.append(snode)
2298

    
2299
      # warn that the instance lives on offline nodes
2300
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2301
               "instance lives on offline node(s) %s",
2302
               utils.CommaJoin(inst_nodes_offline))
2303
      # ... or ghost/non-vm_capable nodes
2304
      for node in inst_config.all_nodes:
2305
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2306
                 "instance lives on ghost node %s", node)
2307
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2308
                 instance, "instance lives on non-vm_capable node %s", node)
2309

    
2310
    feedback_fn("* Verifying orphan volumes")
2311
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2312
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2313

    
2314
    feedback_fn("* Verifying orphan instances")
2315
    self._VerifyOrphanInstances(instancelist, node_image)
2316

    
2317
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2318
      feedback_fn("* Verifying N+1 Memory redundancy")
2319
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2320

    
2321
    feedback_fn("* Other Notes")
2322
    if i_non_redundant:
2323
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2324
                  % len(i_non_redundant))
2325

    
2326
    if i_non_a_balanced:
2327
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2328
                  % len(i_non_a_balanced))
2329

    
2330
    if n_offline:
2331
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2332

    
2333
    if n_drained:
2334
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2335

    
2336
    return not self.bad
2337

    
2338
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2339
    """Analyze the post-hooks' result
2340

2341
    This method analyses the hook result, handles it, and sends some
2342
    nicely-formatted feedback back to the user.
2343

2344
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2345
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2346
    @param hooks_results: the results of the multi-node hooks rpc call
2347
    @param feedback_fn: function used send feedback back to the caller
2348
    @param lu_result: previous Exec result
2349
    @return: the new Exec result, based on the previous result
2350
        and hook results
2351

2352
    """
2353
    # We only really run POST phase hooks, and are only interested in
2354
    # their results
2355
    if phase == constants.HOOKS_PHASE_POST:
2356
      # Used to change hooks' output to proper indentation
2357
      feedback_fn("* Hooks Results")
2358
      assert hooks_results, "invalid result from hooks"
2359

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

    
2381
      return lu_result
2382

    
2383

    
2384
class LUClusterVerifyDisks(NoHooksLU):
2385
  """Verifies the cluster disks status.
2386

2387
  """
2388
  REQ_BGL = False
2389

    
2390
  def ExpandNames(self):
2391
    self.needed_locks = {
2392
      locking.LEVEL_NODE: locking.ALL_SET,
2393
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2394
    }
2395
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2396

    
2397
  def Exec(self, feedback_fn):
2398
    """Verify integrity of cluster disks.
2399

2400
    @rtype: tuple of three items
2401
    @return: a tuple of (dict of node-to-node_error, list of instances
2402
        which need activate-disks, dict of instance: (node, volume) for
2403
        missing volumes
2404

2405
    """
2406
    result = res_nodes, res_instances, res_missing = {}, [], {}
2407

    
2408
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2409
    instances = [self.cfg.GetInstanceInfo(name)
2410
                 for name in self.cfg.GetInstanceList()]
2411

    
2412
    nv_dict = {}
2413
    for inst in instances:
2414
      inst_lvs = {}
2415
      if (not inst.admin_up or
2416
          inst.disk_template not in constants.DTS_NET_MIRROR):
2417
        continue
2418
      inst.MapLVsByNode(inst_lvs)
2419
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2420
      for node, vol_list in inst_lvs.iteritems():
2421
        for vol in vol_list:
2422
          nv_dict[(node, vol)] = inst
2423

    
2424
    if not nv_dict:
2425
      return result
2426

    
2427
    vg_names = self.rpc.call_vg_list(nodes)
2428
    for node in nodes:
2429
      vg_names[node].Raise("Cannot get list of VGs")
2430

    
2431
    for node in nodes:
2432
      # node_volume
2433
      node_res = self.rpc.call_lv_list([node],
2434
                                       vg_names[node].payload.keys())[node]
2435
      if node_res.offline:
2436
        continue
2437
      msg = node_res.fail_msg
2438
      if msg:
2439
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2440
        res_nodes[node] = msg
2441
        continue
2442

    
2443
      lvs = node_res.payload
2444
      for lv_name, (_, _, lv_online) in lvs.items():
2445
        inst = nv_dict.pop((node, lv_name), None)
2446
        if (not lv_online and inst is not None
2447
            and inst.name not in res_instances):
2448
          res_instances.append(inst.name)
2449

    
2450
    # any leftover items in nv_dict are missing LVs, let's arrange the
2451
    # data better
2452
    for key, inst in nv_dict.iteritems():
2453
      if inst.name not in res_missing:
2454
        res_missing[inst.name] = []
2455
      res_missing[inst.name].append(key)
2456

    
2457
    return result
2458

    
2459

    
2460
class LUClusterRepairDiskSizes(NoHooksLU):
2461
  """Verifies the cluster disks sizes.
2462

2463
  """
2464
  REQ_BGL = False
2465

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

    
2485
  def DeclareLocks(self, level):
2486
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2487
      self._LockInstancesNodes(primary_only=True)
2488

    
2489
  def CheckPrereq(self):
2490
    """Check prerequisites.
2491

2492
    This only checks the optional instance list against the existing names.
2493

2494
    """
2495
    if self.wanted_names is None:
2496
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2497

    
2498
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2499
                             in self.wanted_names]
2500

    
2501
  def _EnsureChildSizes(self, disk):
2502
    """Ensure children of the disk have the needed disk size.
2503

2504
    This is valid mainly for DRBD8 and fixes an issue where the
2505
    children have smaller disk size.
2506

2507
    @param disk: an L{ganeti.objects.Disk} object
2508

2509
    """
2510
    if disk.dev_type == constants.LD_DRBD8:
2511
      assert disk.children, "Empty children for DRBD8?"
2512
      fchild = disk.children[0]
2513
      mismatch = fchild.size < disk.size
2514
      if mismatch:
2515
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2516
                     fchild.size, disk.size)
2517
        fchild.size = disk.size
2518

    
2519
      # and we recurse on this child only, not on the metadev
2520
      return self._EnsureChildSizes(fchild) or mismatch
2521
    else:
2522
      return False
2523

    
2524
  def Exec(self, feedback_fn):
2525
    """Verify the size of cluster disks.
2526

2527
    """
2528
    # TODO: check child disks too
2529
    # TODO: check differences in size between primary/secondary nodes
2530
    per_node_disks = {}
2531
    for instance in self.wanted_instances:
2532
      pnode = instance.primary_node
2533
      if pnode not in per_node_disks:
2534
        per_node_disks[pnode] = []
2535
      for idx, disk in enumerate(instance.disks):
2536
        per_node_disks[pnode].append((instance, idx, disk))
2537

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

    
2574

    
2575
class LUClusterRename(LogicalUnit):
2576
  """Rename the cluster.
2577

2578
  """
2579
  HPATH = "cluster-rename"
2580
  HTYPE = constants.HTYPE_CLUSTER
2581

    
2582
  def BuildHooksEnv(self):
2583
    """Build hooks env.
2584

2585
    """
2586
    env = {
2587
      "OP_TARGET": self.cfg.GetClusterName(),
2588
      "NEW_NAME": self.op.name,
2589
      }
2590
    mn = self.cfg.GetMasterNode()
2591
    all_nodes = self.cfg.GetNodeList()
2592
    return env, [mn], all_nodes
2593

    
2594
  def CheckPrereq(self):
2595
    """Verify that the passed name is a valid one.
2596

2597
    """
2598
    hostname = netutils.GetHostname(name=self.op.name,
2599
                                    family=self.cfg.GetPrimaryIPFamily())
2600

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

    
2615
    self.op.name = new_name
2616

    
2617
  def Exec(self, feedback_fn):
2618
    """Rename the cluster.
2619

2620
    """
2621
    clustername = self.op.name
2622
    ip = self.ip
2623

    
2624
    # shutdown the master IP
2625
    master = self.cfg.GetMasterNode()
2626
    result = self.rpc.call_node_stop_master(master, False)
2627
    result.Raise("Could not disable the master role")
2628

    
2629
    try:
2630
      cluster = self.cfg.GetClusterInfo()
2631
      cluster.cluster_name = clustername
2632
      cluster.master_ip = ip
2633
      self.cfg.Update(cluster, feedback_fn)
2634

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

    
2650
    return clustername
2651

    
2652

    
2653
class LUClusterSetParams(LogicalUnit):
2654
  """Change the parameters of the cluster.
2655

2656
  """
2657
  HPATH = "cluster-modify"
2658
  HTYPE = constants.HTYPE_CLUSTER
2659
  REQ_BGL = False
2660

    
2661
  def CheckArguments(self):
2662
    """Check parameters
2663

2664
    """
2665
    if self.op.uid_pool:
2666
      uidpool.CheckUidPool(self.op.uid_pool)
2667

    
2668
    if self.op.add_uids:
2669
      uidpool.CheckUidPool(self.op.add_uids)
2670

    
2671
    if self.op.remove_uids:
2672
      uidpool.CheckUidPool(self.op.remove_uids)
2673

    
2674
  def ExpandNames(self):
2675
    # FIXME: in the future maybe other cluster params won't require checking on
2676
    # all nodes to be modified.
2677
    self.needed_locks = {
2678
      locking.LEVEL_NODE: locking.ALL_SET,
2679
    }
2680
    self.share_locks[locking.LEVEL_NODE] = 1
2681

    
2682
  def BuildHooksEnv(self):
2683
    """Build hooks env.
2684

2685
    """
2686
    env = {
2687
      "OP_TARGET": self.cfg.GetClusterName(),
2688
      "NEW_VG_NAME": self.op.vg_name,
2689
      }
2690
    mn = self.cfg.GetMasterNode()
2691
    return env, [mn], [mn]
2692

    
2693
  def CheckPrereq(self):
2694
    """Check prerequisites.
2695

2696
    This checks whether the given params don't conflict and
2697
    if the given volume group is valid.
2698

2699
    """
2700
    if self.op.vg_name is not None and not self.op.vg_name:
2701
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2702
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2703
                                   " instances exist", errors.ECODE_INVAL)
2704

    
2705
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2706
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2707
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2708
                                   " drbd-based instances exist",
2709
                                   errors.ECODE_INVAL)
2710

    
2711
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2712

    
2713
    # if vg_name not None, checks given volume group on all nodes
2714
    if self.op.vg_name:
2715
      vglist = self.rpc.call_vg_list(node_list)
2716
      for node in node_list:
2717
        msg = vglist[node].fail_msg
2718
        if msg:
2719
          # ignoring down node
2720
          self.LogWarning("Error while gathering data on node %s"
2721
                          " (ignoring node): %s", node, msg)
2722
          continue
2723
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2724
                                              self.op.vg_name,
2725
                                              constants.MIN_VG_SIZE)
2726
        if vgstatus:
2727
          raise errors.OpPrereqError("Error on node '%s': %s" %
2728
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2729

    
2730
    if self.op.drbd_helper:
2731
      # checks given drbd helper on all nodes
2732
      helpers = self.rpc.call_drbd_helper(node_list)
2733
      for node in node_list:
2734
        ninfo = self.cfg.GetNodeInfo(node)
2735
        if ninfo.offline:
2736
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2737
          continue
2738
        msg = helpers[node].fail_msg
2739
        if msg:
2740
          raise errors.OpPrereqError("Error checking drbd helper on node"
2741
                                     " '%s': %s" % (node, msg),
2742
                                     errors.ECODE_ENVIRON)
2743
        node_helper = helpers[node].payload
2744
        if node_helper != self.op.drbd_helper:
2745
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2746
                                     (node, node_helper), errors.ECODE_ENVIRON)
2747

    
2748
    self.cluster = cluster = self.cfg.GetClusterInfo()
2749
    # validate params changes
2750
    if self.op.beparams:
2751
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2752
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2753

    
2754
    if self.op.ndparams:
2755
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2756
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2757

    
2758
    if self.op.nicparams:
2759
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2760
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2761
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2762
      nic_errors = []
2763

    
2764
      # check all instances for consistency
2765
      for instance in self.cfg.GetAllInstancesInfo().values():
2766
        for nic_idx, nic in enumerate(instance.nics):
2767
          params_copy = copy.deepcopy(nic.nicparams)
2768
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2769

    
2770
          # check parameter syntax
2771
          try:
2772
            objects.NIC.CheckParameterSyntax(params_filled)
2773
          except errors.ConfigurationError, err:
2774
            nic_errors.append("Instance %s, nic/%d: %s" %
2775
                              (instance.name, nic_idx, err))
2776

    
2777
          # if we're moving instances to routed, check that they have an ip
2778
          target_mode = params_filled[constants.NIC_MODE]
2779
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2780
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2781
                              (instance.name, nic_idx))
2782
      if nic_errors:
2783
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2784
                                   "\n".join(nic_errors))
2785

    
2786
    # hypervisor list/parameters
2787
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2788
    if self.op.hvparams:
2789
      for hv_name, hv_dict in self.op.hvparams.items():
2790
        if hv_name not in self.new_hvparams:
2791
          self.new_hvparams[hv_name] = hv_dict
2792
        else:
2793
          self.new_hvparams[hv_name].update(hv_dict)
2794

    
2795
    # os hypervisor parameters
2796
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2797
    if self.op.os_hvp:
2798
      for os_name, hvs in self.op.os_hvp.items():
2799
        if os_name not in self.new_os_hvp:
2800
          self.new_os_hvp[os_name] = hvs
2801
        else:
2802
          for hv_name, hv_dict in hvs.items():
2803
            if hv_name not in self.new_os_hvp[os_name]:
2804
              self.new_os_hvp[os_name][hv_name] = hv_dict
2805
            else:
2806
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2807

    
2808
    # os parameters
2809
    self.new_osp = objects.FillDict(cluster.osparams, {})
2810
    if self.op.osparams:
2811
      for os_name, osp in self.op.osparams.items():
2812
        if os_name not in self.new_osp:
2813
          self.new_osp[os_name] = {}
2814

    
2815
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2816
                                                  use_none=True)
2817

    
2818
        if not self.new_osp[os_name]:
2819
          # we removed all parameters
2820
          del self.new_osp[os_name]
2821
        else:
2822
          # check the parameter validity (remote check)
2823
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2824
                         os_name, self.new_osp[os_name])
2825

    
2826
    # changes to the hypervisor list
2827
    if self.op.enabled_hypervisors is not None:
2828
      self.hv_list = self.op.enabled_hypervisors
2829
      for hv in self.hv_list:
2830
        # if the hypervisor doesn't already exist in the cluster
2831
        # hvparams, we initialize it to empty, and then (in both
2832
        # cases) we make sure to fill the defaults, as we might not
2833
        # have a complete defaults list if the hypervisor wasn't
2834
        # enabled before
2835
        if hv not in new_hvp:
2836
          new_hvp[hv] = {}
2837
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2838
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2839
    else:
2840
      self.hv_list = cluster.enabled_hypervisors
2841

    
2842
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2843
      # either the enabled list has changed, or the parameters have, validate
2844
      for hv_name, hv_params in self.new_hvparams.items():
2845
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2846
            (self.op.enabled_hypervisors and
2847
             hv_name in self.op.enabled_hypervisors)):
2848
          # either this is a new hypervisor, or its parameters have changed
2849
          hv_class = hypervisor.GetHypervisor(hv_name)
2850
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2851
          hv_class.CheckParameterSyntax(hv_params)
2852
          _CheckHVParams(self, node_list, hv_name, hv_params)
2853

    
2854
    if self.op.os_hvp:
2855
      # no need to check any newly-enabled hypervisors, since the
2856
      # defaults have already been checked in the above code-block
2857
      for os_name, os_hvp in self.new_os_hvp.items():
2858
        for hv_name, hv_params in os_hvp.items():
2859
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2860
          # we need to fill in the new os_hvp on top of the actual hv_p
2861
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2862
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2863
          hv_class = hypervisor.GetHypervisor(hv_name)
2864
          hv_class.CheckParameterSyntax(new_osp)
2865
          _CheckHVParams(self, node_list, hv_name, new_osp)
2866

    
2867
    if self.op.default_iallocator:
2868
      alloc_script = utils.FindFile(self.op.default_iallocator,
2869
                                    constants.IALLOCATOR_SEARCH_PATH,
2870
                                    os.path.isfile)
2871
      if alloc_script is None:
2872
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2873
                                   " specified" % self.op.default_iallocator,
2874
                                   errors.ECODE_INVAL)
2875

    
2876
  def Exec(self, feedback_fn):
2877
    """Change the parameters of the cluster.
2878

2879
    """
2880
    if self.op.vg_name is not None:
2881
      new_volume = self.op.vg_name
2882
      if not new_volume:
2883
        new_volume = None
2884
      if new_volume != self.cfg.GetVGName():
2885
        self.cfg.SetVGName(new_volume)
2886
      else:
2887
        feedback_fn("Cluster LVM configuration already in desired"
2888
                    " state, not changing")
2889
    if self.op.drbd_helper is not None:
2890
      new_helper = self.op.drbd_helper
2891
      if not new_helper:
2892
        new_helper = None
2893
      if new_helper != self.cfg.GetDRBDHelper():
2894
        self.cfg.SetDRBDHelper(new_helper)
2895
      else:
2896
        feedback_fn("Cluster DRBD helper already in desired state,"
2897
                    " not changing")
2898
    if self.op.hvparams:
2899
      self.cluster.hvparams = self.new_hvparams
2900
    if self.op.os_hvp:
2901
      self.cluster.os_hvp = self.new_os_hvp
2902
    if self.op.enabled_hypervisors is not None:
2903
      self.cluster.hvparams = self.new_hvparams
2904
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2905
    if self.op.beparams:
2906
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2907
    if self.op.nicparams:
2908
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2909
    if self.op.osparams:
2910
      self.cluster.osparams = self.new_osp
2911
    if self.op.ndparams:
2912
      self.cluster.ndparams = self.new_ndparams
2913

    
2914
    if self.op.candidate_pool_size is not None:
2915
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2916
      # we need to update the pool size here, otherwise the save will fail
2917
      _AdjustCandidatePool(self, [])
2918

    
2919
    if self.op.maintain_node_health is not None:
2920
      self.cluster.maintain_node_health = self.op.maintain_node_health
2921

    
2922
    if self.op.prealloc_wipe_disks is not None:
2923
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2924

    
2925
    if self.op.add_uids is not None:
2926
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2927

    
2928
    if self.op.remove_uids is not None:
2929
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2930

    
2931
    if self.op.uid_pool is not None:
2932
      self.cluster.uid_pool = self.op.uid_pool
2933

    
2934
    if self.op.default_iallocator is not None:
2935
      self.cluster.default_iallocator = self.op.default_iallocator
2936

    
2937
    if self.op.reserved_lvs is not None:
2938
      self.cluster.reserved_lvs = self.op.reserved_lvs
2939

    
2940
    def helper_os(aname, mods, desc):
2941
      desc += " OS list"
2942
      lst = getattr(self.cluster, aname)
2943
      for key, val in mods:
2944
        if key == constants.DDM_ADD:
2945
          if val in lst:
2946
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
2947
          else:
2948
            lst.append(val)
2949
        elif key == constants.DDM_REMOVE:
2950
          if val in lst:
2951
            lst.remove(val)
2952
          else:
2953
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
2954
        else:
2955
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2956

    
2957
    if self.op.hidden_os:
2958
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2959

    
2960
    if self.op.blacklisted_os:
2961
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2962

    
2963
    if self.op.master_netdev:
2964
      master = self.cfg.GetMasterNode()
2965
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
2966
                  self.cluster.master_netdev)
2967
      result = self.rpc.call_node_stop_master(master, False)
2968
      result.Raise("Could not disable the master ip")
2969
      feedback_fn("Changing master_netdev from %s to %s" %
2970
                  (self.cluster.master_netdev, self.op.master_netdev))
2971
      self.cluster.master_netdev = self.op.master_netdev
2972

    
2973
    self.cfg.Update(self.cluster, feedback_fn)
2974

    
2975
    if self.op.master_netdev:
2976
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
2977
                  self.op.master_netdev)
2978
      result = self.rpc.call_node_start_master(master, False, False)
2979
      if result.fail_msg:
2980
        self.LogWarning("Could not re-enable the master ip on"
2981
                        " the master, please restart manually: %s",
2982
                        result.fail_msg)
2983

    
2984

    
2985
def _UploadHelper(lu, nodes, fname):
2986
  """Helper for uploading a file and showing warnings.
2987

2988
  """
2989
  if os.path.exists(fname):
2990
    result = lu.rpc.call_upload_file(nodes, fname)
2991
    for to_node, to_result in result.items():
2992
      msg = to_result.fail_msg
2993
      if msg:
2994
        msg = ("Copy of file %s to node %s failed: %s" %
2995
               (fname, to_node, msg))
2996
        lu.proc.LogWarning(msg)
2997

    
2998

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

3002
  ConfigWriter takes care of distributing the config and ssconf files, but
3003
  there are more files which should be distributed to all nodes. This function
3004
  makes sure those are copied.
3005

3006
  @param lu: calling logical unit
3007
  @param additional_nodes: list of nodes not in the config to distribute to
3008
  @type additional_vm: boolean
3009
  @param additional_vm: whether the additional nodes are vm-capable or not
3010

3011
  """
3012
  # 1. Gather target nodes
3013
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3014
  dist_nodes = lu.cfg.GetOnlineNodeList()
3015
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
3016
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
3017
  if additional_nodes is not None:
3018
    dist_nodes.extend(additional_nodes)
3019
    if additional_vm:
3020
      vm_nodes.extend(additional_nodes)
3021
  if myself.name in dist_nodes:
3022
    dist_nodes.remove(myself.name)
3023
  if myself.name in vm_nodes:
3024
    vm_nodes.remove(myself.name)
3025

    
3026
  # 2. Gather files to distribute
3027
  dist_files = set([constants.ETC_HOSTS,
3028
                    constants.SSH_KNOWN_HOSTS_FILE,
3029
                    constants.RAPI_CERT_FILE,
3030
                    constants.RAPI_USERS_FILE,
3031
                    constants.CONFD_HMAC_KEY,
3032
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
3033
                   ])
3034

    
3035
  vm_files = set()
3036
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
3037
  for hv_name in enabled_hypervisors:
3038
    hv_class = hypervisor.GetHypervisor(hv_name)
3039
    vm_files.update(hv_class.GetAncillaryFiles())
3040

    
3041
  # 3. Perform the files upload
3042
  for fname in dist_files:
3043
    _UploadHelper(lu, dist_nodes, fname)
3044
  for fname in vm_files:
3045
    _UploadHelper(lu, vm_nodes, fname)
3046

    
3047

    
3048
class LUClusterRedistConf(NoHooksLU):
3049
  """Force the redistribution of cluster configuration.
3050

3051
  This is a very simple LU.
3052

3053
  """
3054
  REQ_BGL = False
3055

    
3056
  def ExpandNames(self):
3057
    self.needed_locks = {
3058
      locking.LEVEL_NODE: locking.ALL_SET,
3059
    }
3060
    self.share_locks[locking.LEVEL_NODE] = 1
3061

    
3062
  def Exec(self, feedback_fn):
3063
    """Redistribute the configuration.
3064

3065
    """
3066
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3067
    _RedistributeAncillaryFiles(self)
3068

    
3069

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

3073
  """
3074
  if not instance.disks or disks is not None and not disks:
3075
    return True
3076

    
3077
  disks = _ExpandCheckDisks(instance, disks)
3078

    
3079
  if not oneshot:
3080
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3081

    
3082
  node = instance.primary_node
3083

    
3084
  for dev in disks:
3085
    lu.cfg.SetDiskID(dev, node)
3086

    
3087
  # TODO: Convert to utils.Retry
3088

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

    
3113
      cumul_degraded = (cumul_degraded or
3114
                        (mstat.is_degraded and mstat.sync_percent is None))
3115
      if mstat.sync_percent is not None:
3116
        done = False
3117
        if mstat.estimated_time is not None:
3118
          rem_time = ("%s remaining (estimated)" %
3119
                      utils.FormatSeconds(mstat.estimated_time))
3120
          max_time = mstat.estimated_time
3121
        else:
3122
          rem_time = "no time estimate"
3123
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3124
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3125

    
3126
    # if we're done but degraded, let's do a few small retries, to
3127
    # make sure we see a stable and not transient situation; therefore
3128
    # we force restart of the loop
3129
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3130
      logging.info("Degraded disks found, %d retries left", degr_retries)
3131
      degr_retries -= 1
3132
      time.sleep(1)
3133
      continue
3134

    
3135
    if done or oneshot:
3136
      break
3137

    
3138
    time.sleep(min(60, max_time))
3139

    
3140
  if done:
3141
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3142
  return not cumul_degraded
3143

    
3144

    
3145
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3146
  """Check that mirrors are not degraded.
3147

3148
  The ldisk parameter, if True, will change the test from the
3149
  is_degraded attribute (which represents overall non-ok status for
3150
  the device(s)) to the ldisk (representing the local storage status).
3151

3152
  """
3153
  lu.cfg.SetDiskID(dev, node)
3154

    
3155
  result = True
3156

    
3157
  if on_primary or dev.AssembleOnSecondary():
3158
    rstats = lu.rpc.call_blockdev_find(node, dev)
3159
    msg = rstats.fail_msg
3160
    if msg:
3161
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3162
      result = False
3163
    elif not rstats.payload:
3164
      lu.LogWarning("Can't find disk on node %s", node)
3165
      result = False
3166
    else:
3167
      if ldisk:
3168
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3169
      else:
3170
        result = result and not rstats.payload.is_degraded
3171

    
3172
  if dev.children:
3173
    for child in dev.children:
3174
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3175

    
3176
  return result
3177

    
3178

    
3179
class LUOobCommand(NoHooksLU):
3180
  """Logical unit for OOB handling.
3181

3182
  """
3183
  REG_BGL = False
3184

    
3185
  def CheckPrereq(self):
3186
    """Check prerequisites.
3187

3188
    This checks:
3189
     - the node exists in the configuration
3190
     - OOB is supported
3191

3192
    Any errors are signaled by raising errors.OpPrereqError.
3193

3194
    """
3195
    self.nodes = []
3196
    for node_name in self.op.node_names:
3197
      node = self.cfg.GetNodeInfo(node_name)
3198

    
3199
      if node is None:
3200
        raise errors.OpPrereqError("Node %s not found" % node_name,
3201
                                   errors.ECODE_NOENT)
3202
      else:
3203
        self.nodes.append(node)
3204

    
3205
      if (self.op.command == constants.OOB_POWER_OFF and not node.offline):
3206
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3207
                                    " not marked offline") % node_name,
3208
                                   errors.ECODE_STATE)
3209

    
3210
  def ExpandNames(self):
3211
    """Gather locks we need.
3212

3213
    """
3214
    if self.op.node_names:
3215
      self.op.node_names = [_ExpandNodeName(self.cfg, name)
3216
                            for name in self.op.node_names]
3217
    else:
3218
      self.op.node_names = self.cfg.GetNodeList()
3219

    
3220
    self.needed_locks = {
3221
      locking.LEVEL_NODE: self.op.node_names,
3222
      }
3223

    
3224
  def Exec(self, feedback_fn):
3225
    """Execute OOB and return result if we expect any.
3226

3227
    """
3228
    master_node = self.cfg.GetMasterNode()
3229
    ret = []
3230

    
3231
    for node in self.nodes:
3232
      node_entry = [(constants.RS_NORMAL, node.name)]
3233
      ret.append(node_entry)
3234

    
3235
      oob_program = _SupportsOob(self.cfg, node)
3236

    
3237
      if not oob_program:
3238
        node_entry.append((constants.RS_UNAVAIL, None))
3239
        continue
3240

    
3241
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3242
                   self.op.command, oob_program, node.name)
3243
      result = self.rpc.call_run_oob(master_node, oob_program,
3244
                                     self.op.command, node.name,
3245
                                     self.op.timeout)
3246

    
3247
      if result.fail_msg:
3248
        self.LogWarning("On node '%s' out-of-band RPC failed with: %s",
3249
                        node.name, result.fail_msg)
3250
        node_entry.append((constants.RS_NODATA, None))
3251
      else:
3252
        try:
3253
          self._CheckPayload(result)
3254
        except errors.OpExecError, err:
3255
          self.LogWarning("The payload returned by '%s' is not valid: %s",
3256
                          node.name, err)
3257
          node_entry.append((constants.RS_NODATA, None))
3258
        else:
3259
          if self.op.command == constants.OOB_HEALTH:
3260
            # For health we should log important events
3261
            for item, status in result.payload:
3262
              if status in [constants.OOB_STATUS_WARNING,
3263
                            constants.OOB_STATUS_CRITICAL]:
3264
                self.LogWarning("On node '%s' item '%s' has status '%s'",
3265
                                node.name, item, status)
3266

    
3267
          if self.op.command == constants.OOB_POWER_ON:
3268
            node.powered = True
3269
          elif self.op.command == constants.OOB_POWER_OFF:
3270
            node.powered = False
3271
          elif self.op.command == constants.OOB_POWER_STATUS:
3272
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3273
            if powered != node.powered:
3274
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3275
                               " match actual power state (%s)"), node.powered,
3276
                              node.name, powered)
3277

    
3278
          # For configuration changing commands we should update the node
3279
          if self.op.command in (constants.OOB_POWER_ON,
3280
                                 constants.OOB_POWER_OFF):
3281
            self.cfg.Update(node, feedback_fn)
3282

    
3283
          node_entry.append((constants.RS_NORMAL, result.payload))
3284

    
3285
    return ret
3286

    
3287
  def _CheckPayload(self, result):
3288
    """Checks if the payload is valid.
3289

3290
    @param result: RPC result
3291
    @raises errors.OpExecError: If payload is not valid
3292

3293
    """
3294
    errs = []
3295
    if self.op.command == constants.OOB_HEALTH:
3296
      if not isinstance(result.payload, list):
3297
        errs.append("command 'health' is expected to return a list but got %s" %
3298
                    type(result.payload))
3299
      for item, status in result.payload:
3300
        if status not in constants.OOB_STATUSES:
3301
          errs.append("health item '%s' has invalid status '%s'" %
3302
                      (item, status))
3303

    
3304
    if self.op.command == constants.OOB_POWER_STATUS:
3305
      if not isinstance(result.payload, dict):
3306
        errs.append("power-status is expected to return a dict but got %s" %
3307
                    type(result.payload))
3308

    
3309
    if self.op.command in [
3310
        constants.OOB_POWER_ON,
3311
        constants.OOB_POWER_OFF,
3312
        constants.OOB_POWER_CYCLE,
3313
        ]:
3314
      if result.payload is not None:
3315
        errs.append("%s is expected to not return payload but got '%s'" %
3316
                    (self.op.command, result.payload))
3317

    
3318
    if errs:
3319
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3320
                               utils.CommaJoin(errs))
3321

    
3322

    
3323

    
3324
class LUOsDiagnose(NoHooksLU):
3325
  """Logical unit for OS diagnose/query.
3326

3327
  """
3328
  REQ_BGL = False
3329
  _HID = "hidden"
3330
  _BLK = "blacklisted"
3331
  _VLD = "valid"
3332
  _FIELDS_STATIC = utils.FieldSet()
3333
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3334
                                   "parameters", "api_versions", _HID, _BLK)
3335

    
3336
  def CheckArguments(self):
3337
    if self.op.names:
3338
      raise errors.OpPrereqError("Selective OS query not supported",
3339
                                 errors.ECODE_INVAL)
3340

    
3341
    _CheckOutputFields(static=self._FIELDS_STATIC,
3342
                       dynamic=self._FIELDS_DYNAMIC,
3343
                       selected=self.op.output_fields)
3344

    
3345
  def ExpandNames(self):
3346
    # Lock all nodes, in shared mode
3347
    # Temporary removal of locks, should be reverted later
3348
    # TODO: reintroduce locks when they are lighter-weight
3349
    self.needed_locks = {}
3350
    #self.share_locks[locking.LEVEL_NODE] = 1
3351
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3352

    
3353
  @staticmethod
3354
  def _DiagnoseByOS(rlist):
3355
    """Remaps a per-node return list into an a per-os per-node dictionary
3356

3357
    @param rlist: a map with node names as keys and OS objects as values
3358

3359
    @rtype: dict
3360
    @return: a dictionary with osnames as keys and as value another
3361
        map, with nodes as keys and tuples of (path, status, diagnose,
3362
        variants, parameters, api_versions) as values, eg::
3363

3364
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3365
                                     (/srv/..., False, "invalid api")],
3366
                           "node2": [(/srv/..., True, "", [], [])]}
3367
          }
3368

3369
    """
3370
    all_os = {}
3371
    # we build here the list of nodes that didn't fail the RPC (at RPC
3372
    # level), so that nodes with a non-responding node daemon don't
3373
    # make all OSes invalid
3374
    good_nodes = [node_name for node_name in rlist
3375
                  if not rlist[node_name].fail_msg]
3376
    for node_name, nr in rlist.items():
3377
      if nr.fail_msg or not nr.payload:
3378
        continue
3379
      for (name, path, status, diagnose, variants,
3380
           params, api_versions) in nr.payload:
3381
        if name not in all_os:
3382
          # build a list of nodes for this os containing empty lists
3383
          # for each node in node_list
3384
          all_os[name] = {}
3385
          for nname in good_nodes:
3386
            all_os[name][nname] = []
3387
        # convert params from [name, help] to (name, help)
3388
        params = [tuple(v) for v in params]
3389
        all_os[name][node_name].append((path, status, diagnose,
3390
                                        variants, params, api_versions))
3391
    return all_os
3392

    
3393
  def Exec(self, feedback_fn):
3394
    """Compute the list of OSes.
3395

3396
    """
3397
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3398
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3399
    pol = self._DiagnoseByOS(node_data)
3400
    output = []
3401
    cluster = self.cfg.GetClusterInfo()
3402

    
3403
    for os_name in utils.NiceSort(pol.keys()):
3404
      os_data = pol[os_name]
3405
      row = []
3406
      valid = True
3407
      (variants, params, api_versions) = null_state = (set(), set(), set())
3408
      for idx, osl in enumerate(os_data.values()):
3409
        valid = bool(valid and osl and osl[0][1])
3410
        if not valid:
3411
          (variants, params, api_versions) = null_state
3412
          break
3413
        node_variants, node_params, node_api = osl[0][3:6]
3414
        if idx == 0: # first entry
3415
          variants = set(node_variants)
3416
          params = set(node_params)
3417
          api_versions = set(node_api)
3418
        else: # keep consistency
3419
          variants.intersection_update(node_variants)
3420
          params.intersection_update(node_params)
3421
          api_versions.intersection_update(node_api)
3422

    
3423
      is_hid = os_name in cluster.hidden_os
3424
      is_blk = os_name in cluster.blacklisted_os
3425
      if ((self._HID not in self.op.output_fields and is_hid) or
3426
          (self._BLK not in self.op.output_fields and is_blk) or
3427
          (self._VLD not in self.op.output_fields and not valid)):
3428
        continue
3429

    
3430
      for field in self.op.output_fields:
3431
        if field == "name":
3432
          val = os_name
3433
        elif field == self._VLD:
3434
          val = valid
3435
        elif field == "node_status":
3436
          # this is just a copy of the dict
3437
          val = {}
3438
          for node_name, nos_list in os_data.items():
3439
            val[node_name] = nos_list
3440
        elif field == "variants":
3441
          val = utils.NiceSort(list(variants))
3442
        elif field == "parameters":
3443
          val = list(params)
3444
        elif field == "api_versions":
3445
          val = list(api_versions)
3446
        elif field == self._HID:
3447
          val = is_hid
3448
        elif field == self._BLK:
3449
          val = is_blk
3450
        else:
3451
          raise errors.ParameterError(field)
3452
        row.append(val)
3453
      output.append(row)
3454

    
3455
    return output
3456

    
3457

    
3458
class LUNodeRemove(LogicalUnit):
3459
  """Logical unit for removing a node.
3460

3461
  """
3462
  HPATH = "node-remove"
3463
  HTYPE = constants.HTYPE_NODE
3464

    
3465
  def BuildHooksEnv(self):
3466
    """Build hooks env.
3467

3468
    This doesn't run on the target node in the pre phase as a failed
3469
    node would then be impossible to remove.
3470

3471
    """
3472
    env = {
3473
      "OP_TARGET": self.op.node_name,
3474
      "NODE_NAME": self.op.node_name,
3475
      }
3476
    all_nodes = self.cfg.GetNodeList()
3477
    try:
3478
      all_nodes.remove(self.op.node_name)
3479
    except ValueError:
3480
      logging.warning("Node %s which is about to be removed not found"
3481
                      " in the all nodes list", self.op.node_name)
3482
    return env, all_nodes, all_nodes
3483

    
3484
  def CheckPrereq(self):
3485
    """Check prerequisites.
3486

3487
    This checks:
3488
     - the node exists in the configuration
3489
     - it does not have primary or secondary instances
3490
     - it's not the master
3491

3492
    Any errors are signaled by raising errors.OpPrereqError.
3493

3494
    """
3495
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3496
    node = self.cfg.GetNodeInfo(self.op.node_name)
3497
    assert node is not None
3498

    
3499
    instance_list = self.cfg.GetInstanceList()
3500

    
3501
    masternode = self.cfg.GetMasterNode()
3502
    if node.name == masternode:
3503
      raise errors.OpPrereqError("Node is the master node,"
3504
                                 " you need to failover first.",
3505
                                 errors.ECODE_INVAL)
3506

    
3507
    for instance_name in instance_list:
3508
      instance = self.cfg.GetInstanceInfo(instance_name)
3509
      if node.name in instance.all_nodes:
3510
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3511
                                   " please remove first." % instance_name,
3512
                                   errors.ECODE_INVAL)
3513
    self.op.node_name = node.name
3514
    self.node = node
3515

    
3516
  def Exec(self, feedback_fn):
3517
    """Removes the node from the cluster.
3518

3519
    """
3520
    node = self.node
3521
    logging.info("Stopping the node daemon and removing configs from node %s",
3522
                 node.name)
3523

    
3524
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3525

    
3526
    # Promote nodes to master candidate as needed
3527
    _AdjustCandidatePool(self, exceptions=[node.name])
3528
    self.context.RemoveNode(node.name)
3529

    
3530
    # Run post hooks on the node before it's removed
3531
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3532
    try:
3533
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3534
    except:
3535
      # pylint: disable-msg=W0702
3536
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3537

    
3538
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3539
    msg = result.fail_msg
3540
    if msg:
3541
      self.LogWarning("Errors encountered on the remote node while leaving"
3542
                      " the cluster: %s", msg)
3543

    
3544
    # Remove node from our /etc/hosts
3545
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3546
      master_node = self.cfg.GetMasterNode()
3547
      result = self.rpc.call_etc_hosts_modify(master_node,
3548
                                              constants.ETC_HOSTS_REMOVE,
3549
                                              node.name, None)
3550
      result.Raise("Can't update hosts file with new host data")
3551
      _RedistributeAncillaryFiles(self)
3552

    
3553

    
3554
class _NodeQuery(_QueryBase):
3555
  FIELDS = query.NODE_FIELDS
3556

    
3557
  def ExpandNames(self, lu):
3558
    lu.needed_locks = {}
3559
    lu.share_locks[locking.LEVEL_NODE] = 1
3560

    
3561
    if self.names:
3562
      self.wanted = _GetWantedNodes(lu, self.names)
3563
    else:
3564
      self.wanted = locking.ALL_SET
3565

    
3566
    self.do_locking = (self.use_locking and
3567
                       query.NQ_LIVE in self.requested_data)
3568

    
3569
    if self.do_locking:
3570
      # if we don't request only static fields, we need to lock the nodes
3571
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3572

    
3573
  def DeclareLocks(self, lu, level):
3574
    pass
3575

    
3576
  def _GetQueryData(self, lu):
3577
    """Computes the list of nodes and their attributes.
3578

3579
    """
3580
    all_info = lu.cfg.GetAllNodesInfo()
3581

    
3582
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3583

    
3584
    # Gather data as requested
3585
    if query.NQ_LIVE in self.requested_data:
3586
      node_data = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
3587
                                        lu.cfg.GetHypervisorType())
3588
      live_data = dict((name, nresult.payload)
3589
                       for (name, nresult) in node_data.items()
3590
                       if not nresult.fail_msg and nresult.payload)
3591
    else:
3592
      live_data = None
3593

    
3594
    if query.NQ_INST in self.requested_data:
3595
      node_to_primary = dict([(name, set()) for name in nodenames])
3596
      node_to_secondary = dict([(name, set()) for name in nodenames])
3597

    
3598
      inst_data = lu.cfg.GetAllInstancesInfo()
3599

    
3600
      for inst in inst_data.values():
3601
        if inst.primary_node in node_to_primary:
3602
          node_to_primary[inst.primary_node].add(inst.name)
3603
        for secnode in inst.secondary_nodes:
3604
          if secnode in node_to_secondary:
3605
            node_to_secondary[secnode].add(inst.name)
3606
    else:
3607
      node_to_primary = None
3608
      node_to_secondary = None
3609

    
3610
    if query.NQ_OOB in self.requested_data:
3611
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3612
                         for name, node in all_info.iteritems())
3613
    else:
3614
      oob_support = None
3615

    
3616
    if query.NQ_GROUP in self.requested_data:
3617
      groups = lu.cfg.GetAllNodeGroupsInfo()
3618
    else:
3619
      groups = {}
3620

    
3621
    return query.NodeQueryData([all_info[name] for name in nodenames],
3622
                               live_data, lu.cfg.GetMasterNode(),
3623
                               node_to_primary, node_to_secondary, groups,
3624
                               oob_support, lu.cfg.GetClusterInfo())
3625

    
3626

    
3627
class LUNodeQuery(NoHooksLU):
3628
  """Logical unit for querying nodes.
3629

3630
  """
3631
  # pylint: disable-msg=W0142
3632
  REQ_BGL = False
3633

    
3634
  def CheckArguments(self):
3635
    self.nq = _NodeQuery(self.op.names, self.op.output_fields,
3636
                         self.op.use_locking)
3637

    
3638
  def ExpandNames(self):
3639
    self.nq.ExpandNames(self)
3640

    
3641
  def Exec(self, feedback_fn):
3642
    return self.nq.OldStyleQuery(self)
3643

    
3644

    
3645
class LUNodeQueryvols(NoHooksLU):
3646
  """Logical unit for getting volumes on node(s).
3647

3648
  """
3649
  REQ_BGL = False
3650
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3651
  _FIELDS_STATIC = utils.FieldSet("node")
3652

    
3653
  def CheckArguments(self):
3654
    _CheckOutputFields(static=self._FIELDS_STATIC,
3655
                       dynamic=self._FIELDS_DYNAMIC,
3656
                       selected=self.op.output_fields)
3657

    
3658
  def ExpandNames(self):
3659
    self.needed_locks = {}
3660
    self.share_locks[locking.LEVEL_NODE] = 1
3661
    if not self.op.nodes:
3662
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3663
    else:
3664
      self.needed_locks[locking.LEVEL_NODE] = \
3665
        _GetWantedNodes(self, self.op.nodes)
3666

    
3667
  def Exec(self, feedback_fn):
3668
    """Computes the list of nodes and their attributes.
3669

3670
    """
3671
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3672
    volumes = self.rpc.call_node_volumes(nodenames)
3673

    
3674
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3675
             in self.cfg.GetInstanceList()]
3676

    
3677
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3678

    
3679
    output = []
3680
    for node in nodenames:
3681
      nresult = volumes[node]
3682
      if nresult.offline:
3683
        continue
3684
      msg = nresult.fail_msg
3685
      if msg:
3686
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3687
        continue
3688

    
3689
      node_vols = nresult.payload[:]
3690
      node_vols.sort(key=lambda vol: vol['dev'])
3691

    
3692
      for vol in node_vols:
3693
        node_output = []
3694
        for field in self.op.output_fields:
3695
          if field == "node":
3696
            val = node
3697
          elif field == "phys":
3698
            val = vol['dev']
3699
          elif field == "vg":
3700
            val = vol['vg']
3701
          elif field == "name":
3702
            val = vol['name']
3703
          elif field == "size":
3704
            val = int(float(vol['size']))
3705
          elif field == "instance":
3706
            for inst in ilist:
3707
              if node not in lv_by_node[inst]:
3708
                continue
3709
              if vol['name'] in lv_by_node[inst][node]:
3710
                val = inst.name
3711
                break
3712
            else:
3713
              val = '-'
3714
          else:
3715
            raise errors.ParameterError(field)
3716
          node_output.append(str(val))
3717

    
3718
        output.append(node_output)
3719

    
3720
    return output
3721

    
3722

    
3723
class LUNodeQueryStorage(NoHooksLU):
3724
  """Logical unit for getting information on storage units on node(s).
3725

3726
  """
3727
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3728
  REQ_BGL = False
3729

    
3730
  def CheckArguments(self):
3731
    _CheckOutputFields(static=self._FIELDS_STATIC,
3732
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3733
                       selected=self.op.output_fields)
3734

    
3735
  def ExpandNames(self):
3736
    self.needed_locks = {}
3737
    self.share_locks[locking.LEVEL_NODE] = 1
3738

    
3739
    if self.op.nodes:
3740
      self.needed_locks[locking.LEVEL_NODE] = \
3741
        _GetWantedNodes(self, self.op.nodes)
3742
    else:
3743
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3744

    
3745
  def Exec(self, feedback_fn):
3746
    """Computes the list of nodes and their attributes.
3747

3748
    """
3749
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3750

    
3751
    # Always get name to sort by
3752
    if constants.SF_NAME in self.op.output_fields:
3753
      fields = self.op.output_fields[:]
3754
    else:
3755
      fields = [constants.SF_NAME] + self.op.output_fields
3756

    
3757
    # Never ask for node or type as it's only known to the LU
3758
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3759
      while extra in fields:
3760
        fields.remove(extra)
3761

    
3762
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3763
    name_idx = field_idx[constants.SF_NAME]
3764

    
3765
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3766
    data = self.rpc.call_storage_list(self.nodes,
3767
                                      self.op.storage_type, st_args,
3768
                                      self.op.name, fields)
3769

    
3770
    result = []
3771

    
3772
    for node in utils.NiceSort(self.nodes):
3773
      nresult = data[node]
3774
      if nresult.offline:
3775
        continue
3776

    
3777
      msg = nresult.fail_msg
3778
      if msg:
3779
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3780
        continue
3781

    
3782
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3783

    
3784
      for name in utils.NiceSort(rows.keys()):
3785
        row = rows[name]
3786

    
3787
        out = []
3788

    
3789
        for field in self.op.output_fields:
3790
          if field == constants.SF_NODE:
3791
            val = node
3792
          elif field == constants.SF_TYPE:
3793
            val = self.op.storage_type
3794
          elif field in field_idx:
3795
            val = row[field_idx[field]]
3796
          else:
3797
            raise errors.ParameterError(field)
3798

    
3799
          out.append(val)
3800

    
3801
        result.append(out)
3802

    
3803
    return result
3804

    
3805

    
3806
class _InstanceQuery(_QueryBase):
3807
  FIELDS = query.INSTANCE_FIELDS
3808

    
3809
  def ExpandNames(self, lu):
3810
    lu.needed_locks = {}
3811
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
3812
    lu.share_locks[locking.LEVEL_NODE] = 1
3813

    
3814
    if self.names:
3815
      self.wanted = _GetWantedInstances(lu, self.names)
3816
    else:
3817
      self.wanted = locking.ALL_SET
3818

    
3819
    self.do_locking = (self.use_locking and
3820
                       query.IQ_LIVE in self.requested_data)
3821
    if self.do_locking:
3822
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
3823
      lu.needed_locks[locking.LEVEL_NODE] = []
3824
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3825

    
3826
  def DeclareLocks(self, lu, level):
3827
    if level == locking.LEVEL_NODE and self.do_locking:
3828
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
3829

    
3830
  def _GetQueryData(self, lu):
3831
    """Computes the list of instances and their attributes.
3832

3833
    """
3834
    all_info = lu.cfg.GetAllInstancesInfo()
3835

    
3836
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
3837

    
3838
    instance_list = [all_info[name] for name in instance_names]
3839
    nodes = frozenset([inst.primary_node for inst in instance_list])
3840
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
3841
    bad_nodes = []
3842
    offline_nodes = []
3843

    
3844
    # Gather data as requested
3845
    if query.IQ_LIVE in self.requested_data:
3846
      live_data = {}
3847
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
3848
      for name in nodes:
3849
        result = node_data[name]
3850
        if result.offline:
3851
          # offline nodes will be in both lists
3852
          assert result.fail_msg
3853
          offline_nodes.append(name)
3854
        if result.fail_msg:
3855
          bad_nodes.append(name)
3856
        elif result.payload:
3857
          live_data.update(result.payload)
3858
        # else no instance is alive
3859
    else:
3860
      live_data = {}
3861

    
3862
    if query.IQ_DISKUSAGE in self.requested_data:
3863
      disk_usage = dict((inst.name,
3864
                         _ComputeDiskSize(inst.disk_template,
3865
                                          [{"size": disk.size}
3866
                                           for disk in inst.disks]))
3867
                        for inst in instance_list)
3868
    else:
3869
      disk_usage = None
3870

    
3871
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
3872
                                   disk_usage, offline_nodes, bad_nodes,
3873
                                   live_data)
3874

    
3875

    
3876
class LUQuery(NoHooksLU):
3877
  """Query for resources/items of a certain kind.
3878

3879
  """
3880
  # pylint: disable-msg=W0142
3881
  REQ_BGL = False
3882

    
3883
  def CheckArguments(self):
3884
    qcls = _GetQueryImplementation(self.op.what)
3885
    names = qlang.ReadSimpleFilter("name", self.op.filter)
3886

    
3887
    self.impl = qcls(names, self.op.fields, False)
3888

    
3889
  def ExpandNames(self):
3890
    self.impl.ExpandNames(self)
3891

    
3892
  def DeclareLocks(self, level):
3893
    self.impl.DeclareLocks(self, level)
3894

    
3895
  def Exec(self, feedback_fn):
3896
    return self.impl.NewStyleQuery(self)
3897

    
3898

    
3899
class LUQueryFields(NoHooksLU):
3900
  """Query for resources/items of a certain kind.
3901

3902
  """
3903
  # pylint: disable-msg=W0142
3904
  REQ_BGL = False
3905

    
3906
  def CheckArguments(self):
3907
    self.qcls = _GetQueryImplementation(self.op.what)
3908

    
3909
  def ExpandNames(self):
3910
    self.needed_locks = {}
3911

    
3912
  def Exec(self, feedback_fn):
3913
    return self.qcls.FieldsQuery(self.op.fields)
3914

    
3915

    
3916
class LUNodeModifyStorage(NoHooksLU):
3917
  """Logical unit for modifying a storage volume on a node.
3918

3919
  """
3920
  REQ_BGL = False
3921

    
3922
  def CheckArguments(self):
3923
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3924

    
3925
    storage_type = self.op.storage_type
3926

    
3927
    try:
3928
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3929
    except KeyError:
3930
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3931
                                 " modified" % storage_type,
3932
                                 errors.ECODE_INVAL)
3933

    
3934
    diff = set(self.op.changes.keys()) - modifiable
3935
    if diff:
3936
      raise errors.OpPrereqError("The following fields can not be modified for"
3937
                                 " storage units of type '%s': %r" %
3938
                                 (storage_type, list(diff)),
3939
                                 errors.ECODE_INVAL)
3940

    
3941
  def ExpandNames(self):
3942
    self.needed_locks = {
3943
      locking.LEVEL_NODE: self.op.node_name,
3944
      }
3945

    
3946
  def Exec(self, feedback_fn):
3947
    """Computes the list of nodes and their attributes.
3948

3949
    """
3950
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3951
    result = self.rpc.call_storage_modify(self.op.node_name,
3952
                                          self.op.storage_type, st_args,
3953
                                          self.op.name, self.op.changes)
3954
    result.Raise("Failed to modify storage unit '%s' on %s" %
3955
                 (self.op.name, self.op.node_name))
3956

    
3957

    
3958
class LUNodeAdd(LogicalUnit):
3959
  """Logical unit for adding node to the cluster.
3960

3961
  """
3962
  HPATH = "node-add"
3963
  HTYPE = constants.HTYPE_NODE
3964
  _NFLAGS = ["master_capable", "vm_capable"]
3965

    
3966
  def CheckArguments(self):
3967
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3968
    # validate/normalize the node name
3969
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3970
                                         family=self.primary_ip_family)
3971
    self.op.node_name = self.hostname.name
3972
    if self.op.readd and self.op.group:
3973
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3974
                                 " being readded", errors.ECODE_INVAL)
3975

    
3976
  def BuildHooksEnv(self):
3977
    """Build hooks env.
3978

3979
    This will run on all nodes before, and on all nodes + the new node after.
3980

3981
    """
3982
    env = {
3983
      "OP_TARGET": self.op.node_name,
3984
      "NODE_NAME": self.op.node_name,
3985
      "NODE_PIP": self.op.primary_ip,
3986
      "NODE_SIP": self.op.secondary_ip,
3987
      "MASTER_CAPABLE": str(self.op.master_capable),
3988
      "VM_CAPABLE": str(self.op.vm_capable),
3989
      }
3990
    nodes_0 = self.cfg.GetNodeList()
3991
    nodes_1 = nodes_0 + [self.op.node_name, ]
3992
    return env, nodes_0, nodes_1
3993

    
3994
  def CheckPrereq(self):
3995
    """Check prerequisites.
3996

3997
    This checks:
3998
     - the new node is not already in the config
3999
     - it is resolvable
4000
     - its parameters (single/dual homed) matches the cluster
4001

4002
    Any errors are signaled by raising errors.OpPrereqError.
4003

4004
    """
4005
    cfg = self.cfg
4006
    hostname = self.hostname
4007
    node = hostname.name
4008
    primary_ip = self.op.primary_ip = hostname.ip
4009
    if self.op.secondary_ip is None:
4010
      if self.primary_ip_family == netutils.IP6Address.family:
4011
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4012
                                   " IPv4 address must be given as secondary",
4013
                                   errors.ECODE_INVAL)
4014
      self.op.secondary_ip = primary_ip
4015

    
4016
    secondary_ip = self.op.secondary_ip
4017
    if not netutils.IP4Address.IsValid(secondary_ip):
4018
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4019
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4020

    
4021
    node_list = cfg.GetNodeList()
4022
    if not self.op.readd and node in node_list:
4023
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4024
                                 node, errors.ECODE_EXISTS)
4025
    elif self.op.readd and node not in node_list:
4026
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4027
                                 errors.ECODE_NOENT)
4028

    
4029
    self.changed_primary_ip = False
4030

    
4031
    for existing_node_name in node_list:
4032
      existing_node = cfg.GetNodeInfo(existing_node_name)
4033

    
4034
      if self.op.readd and node == existing_node_name:
4035
        if existing_node.secondary_ip != secondary_ip:
4036
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4037
                                     " address configuration as before",
4038
                                     errors.ECODE_INVAL)
4039
        if existing_node.primary_ip != primary_ip:
4040
          self.changed_primary_ip = True
4041

    
4042
        continue
4043

    
4044
      if (existing_node.primary_ip == primary_ip or
4045
          existing_node.secondary_ip == primary_ip or
4046
          existing_node.primary_ip == secondary_ip or
4047
          existing_node.secondary_ip == secondary_ip):
4048
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4049
                                   " existing node %s" % existing_node.name,
4050
                                   errors.ECODE_NOTUNIQUE)
4051

    
4052
    # After this 'if' block, None is no longer a valid value for the
4053
    # _capable op attributes
4054
    if self.op.readd:
4055
      old_node = self.cfg.GetNodeInfo(node)
4056
      assert old_node is not None, "Can't retrieve locked node %s" % node
4057
      for attr in self._NFLAGS:
4058
        if getattr(self.op, attr) is None:
4059
          setattr(self.op, attr, getattr(old_node, attr))
4060
    else:
4061
      for attr in self._NFLAGS:
4062
        if getattr(self.op, attr) is None:
4063
          setattr(self.op, attr, True)
4064

    
4065
    if self.op.readd and not self.op.vm_capable:
4066
      pri, sec = cfg.GetNodeInstances(node)
4067
      if pri or sec:
4068
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4069
                                   " flag set to false, but it already holds"
4070
                                   " instances" % node,
4071
                                   errors.ECODE_STATE)
4072

    
4073
    # check that the type of the node (single versus dual homed) is the
4074
    # same as for the master
4075
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4076
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4077
    newbie_singlehomed = secondary_ip == primary_ip
4078
    if master_singlehomed != newbie_singlehomed:
4079
      if master_singlehomed:
4080
        raise errors.OpPrereqError("The master has no secondary ip but the"
4081
                                   " new node has one",
4082
                                   errors.ECODE_INVAL)
4083
      else:
4084
        raise errors.OpPrereqError("The master has a secondary ip but the"
4085
                                   " new node doesn't have one",
4086
                                   errors.ECODE_INVAL)
4087

    
4088
    # checks reachability
4089
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4090
      raise errors.OpPrereqError("Node not reachable by ping",
4091
                                 errors.ECODE_ENVIRON)
4092

    
4093
    if not newbie_singlehomed:
4094
      # check reachability from my secondary ip to newbie's secondary ip
4095
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4096
                           source=myself.secondary_ip):
4097
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4098
                                   " based ping to node daemon port",
4099
                                   errors.ECODE_ENVIRON)
4100

    
4101
    if self.op.readd:
4102
      exceptions = [node]
4103
    else:
4104
      exceptions = []
4105

    
4106
    if self.op.master_capable:
4107
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4108
    else:
4109
      self.master_candidate = False
4110

    
4111
    if self.op.readd:
4112
      self.new_node = old_node
4113
    else:
4114
      node_group = cfg.LookupNodeGroup(self.op.group)
4115
      self.new_node = objects.Node(name=node,
4116
                                   primary_ip=primary_ip,
4117
                                   secondary_ip=secondary_ip,
4118
                                   master_candidate=self.master_candidate,
4119
                                   offline=False, drained=False,
4120
                                   group=node_group)
4121

    
4122
    if self.op.ndparams:
4123
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4124

    
4125
  def Exec(self, feedback_fn):
4126
    """Adds the new node to the cluster.
4127

4128
    """
4129
    new_node = self.new_node
4130
    node = new_node.name
4131

    
4132
    # We adding a new node so we assume it's powered
4133
    new_node.powered = True
4134

    
4135
    # for re-adds, reset the offline/drained/master-candidate flags;
4136
    # we need to reset here, otherwise offline would prevent RPC calls
4137
    # later in the procedure; this also means that if the re-add
4138
    # fails, we are left with a non-offlined, broken node
4139
    if self.op.readd:
4140
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4141
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4142
      # if we demote the node, we do cleanup later in the procedure
4143
      new_node.master_candidate = self.master_candidate
4144
      if self.changed_primary_ip:
4145
        new_node.primary_ip = self.op.primary_ip
4146

    
4147
    # copy the master/vm_capable flags
4148
    for attr in self._NFLAGS:
4149
      setattr(new_node, attr, getattr(self.op, attr))
4150

    
4151
    # notify the user about any possible mc promotion
4152
    if new_node.master_candidate:
4153
      self.LogInfo("Node will be a master candidate")
4154

    
4155
    if self.op.ndparams:
4156
      new_node.ndparams = self.op.ndparams
4157
    else:
4158
      new_node.ndparams = {}
4159

    
4160
    # check connectivity
4161
    result = self.rpc.call_version([node])[node]
4162
    result.Raise("Can't get version information from node %s" % node)
4163
    if constants.PROTOCOL_VERSION == result.payload:
4164
      logging.info("Communication to node %s fine, sw version %s match",
4165
                   node, result.payload)
4166
    else:
4167
      raise errors.OpExecError("Version mismatch master version %s,"
4168
                               " node version %s" %
4169
                               (constants.PROTOCOL_VERSION, result.payload))
4170

    
4171
    # Add node to our /etc/hosts, and add key to known_hosts
4172
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4173
      master_node = self.cfg.GetMasterNode()
4174
      result = self.rpc.call_etc_hosts_modify(master_node,
4175
                                              constants.ETC_HOSTS_ADD,
4176
                                              self.hostname.name,
4177
                                              self.hostname.ip)
4178
      result.Raise("Can't update hosts file with new host data")
4179

    
4180
    if new_node.secondary_ip != new_node.primary_ip:
4181
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4182
                               False)
4183

    
4184
    node_verify_list = [self.cfg.GetMasterNode()]
4185
    node_verify_param = {
4186
      constants.NV_NODELIST: [node],
4187
      # TODO: do a node-net-test as well?
4188
    }
4189

    
4190
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4191
                                       self.cfg.GetClusterName())
4192
    for verifier in node_verify_list:
4193
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4194
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4195
      if nl_payload:
4196
        for failed in nl_payload:
4197
          feedback_fn("ssh/hostname verification failed"
4198
                      " (checking from %s): %s" %
4199
                      (verifier, nl_payload[failed]))
4200
        raise errors.OpExecError("ssh/hostname verification failed.")
4201

    
4202
    if self.op.readd:
4203
      _RedistributeAncillaryFiles(self)
4204
      self.context.ReaddNode(new_node)
4205
      # make sure we redistribute the config
4206
      self.cfg.Update(new_node, feedback_fn)
4207
      # and make sure the new node will not have old files around
4208
      if not new_node.master_candidate:
4209
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4210
        msg = result.fail_msg
4211
        if msg:
4212
          self.LogWarning("Node failed to demote itself from master"
4213
                          " candidate status: %s" % msg)
4214
    else:
4215
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4216
                                  additional_vm=self.op.vm_capable)
4217
      self.context.AddNode(new_node, self.proc.GetECId())
4218

    
4219

    
4220
class LUNodeSetParams(LogicalUnit):
4221
  """Modifies the parameters of a node.
4222

4223
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4224
      to the node role (as _ROLE_*)
4225
  @cvar _R2F: a dictionary from node role to tuples of flags
4226
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4227

4228
  """
4229
  HPATH = "node-modify"
4230
  HTYPE = constants.HTYPE_NODE
4231
  REQ_BGL = False
4232
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4233
  _F2R = {
4234
    (True, False, False): _ROLE_CANDIDATE,
4235
    (False, True, False): _ROLE_DRAINED,
4236
    (False, False, True): _ROLE_OFFLINE,
4237
    (False, False, False): _ROLE_REGULAR,
4238
    }
4239
  _R2F = dict((v, k) for k, v in _F2R.items())
4240
  _FLAGS = ["master_candidate", "drained", "offline"]
4241

    
4242
  def CheckArguments(self):
4243
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4244
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4245
                self.op.master_capable, self.op.vm_capable,
4246
                self.op.secondary_ip, self.op.ndparams]
4247
    if all_mods.count(None) == len(all_mods):
4248
      raise errors.OpPrereqError("Please pass at least one modification",
4249
                                 errors.ECODE_INVAL)
4250
    if all_mods.count(True) > 1:
4251
      raise errors.OpPrereqError("Can't set the node into more than one"
4252
                                 " state at the same time",
4253
                                 errors.ECODE_INVAL)
4254

    
4255
    # Boolean value that tells us whether we might be demoting from MC
4256
    self.might_demote = (self.op.master_candidate == False or
4257
                         self.op.offline == True or
4258
                         self.op.drained == True or
4259
                         self.op.master_capable == False)
4260

    
4261
    if self.op.secondary_ip:
4262
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4263
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4264
                                   " address" % self.op.secondary_ip,
4265
                                   errors.ECODE_INVAL)
4266

    
4267
    self.lock_all = self.op.auto_promote and self.might_demote
4268
    self.lock_instances = self.op.secondary_ip is not None
4269

    
4270
  def ExpandNames(self):
4271
    if self.lock_all:
4272
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4273
    else:
4274
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4275

    
4276
    if self.lock_instances:
4277
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4278

    
4279
  def DeclareLocks(self, level):
4280
    # If we have locked all instances, before waiting to lock nodes, release
4281
    # all the ones living on nodes unrelated to the current operation.
4282
    if level == locking.LEVEL_NODE and self.lock_instances:
4283
      instances_release = []
4284
      instances_keep = []
4285
      self.affected_instances = []
4286
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4287
        for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
4288
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4289
          i_mirrored = instance.disk_template in constants.DTS_NET_MIRROR
4290
          if i_mirrored and self.op.node_name in instance.all_nodes:
4291
            instances_keep.append(instance_name)
4292
            self.affected_instances.append(instance)
4293
          else:
4294
            instances_release.append(instance_name)
4295
        if instances_release:
4296
          self.context.glm.release(locking.LEVEL_INSTANCE, instances_release)
4297
          self.acquired_locks[locking.LEVEL_INSTANCE] = instances_keep
4298

    
4299
  def BuildHooksEnv(self):
4300
    """Build hooks env.
4301

4302
    This runs on the master node.
4303

4304
    """
4305
    env = {
4306
      "OP_TARGET": self.op.node_name,
4307
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4308
      "OFFLINE": str(self.op.offline),
4309
      "DRAINED": str(self.op.drained),
4310
      "MASTER_CAPABLE": str(self.op.master_capable),
4311
      "VM_CAPABLE": str(self.op.vm_capable),
4312
      }
4313
    nl = [self.cfg.GetMasterNode(),
4314
          self.op.node_name]
4315
    return env, nl, nl
4316

    
4317
  def CheckPrereq(self):
4318
    """Check prerequisites.
4319

4320
    This only checks the instance list against the existing names.
4321

4322
    """
4323
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4324

    
4325
    if (self.op.master_candidate is not None or
4326
        self.op.drained is not None or
4327
        self.op.offline is not None):
4328
      # we can't change the master's node flags
4329
      if self.op.node_name == self.cfg.GetMasterNode():
4330
        raise errors.OpPrereqError("The master role can be changed"
4331
                                   " only via master-failover",
4332
                                   errors.ECODE_INVAL)
4333

    
4334
    if self.op.master_candidate and not node.master_capable:
4335
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4336
                                 " it a master candidate" % node.name,
4337
                                 errors.ECODE_STATE)
4338

    
4339
    if self.op.vm_capable == False:
4340
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4341
      if ipri or isec:
4342
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4343
                                   " the vm_capable flag" % node.name,
4344
                                   errors.ECODE_STATE)
4345

    
4346
    if node.master_candidate and self.might_demote and not self.lock_all:
4347
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4348
      # check if after removing the current node, we're missing master
4349
      # candidates
4350
      (mc_remaining, mc_should, _) = \
4351
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4352
      if mc_remaining < mc_should:
4353
        raise errors.OpPrereqError("Not enough master candidates, please"
4354
                                   " pass auto_promote to allow promotion",
4355
                                   errors.ECODE_STATE)
4356

    
4357
    self.old_flags = old_flags = (node.master_candidate,
4358
                                  node.drained, node.offline)
4359
    assert old_flags in self._F2R, "Un-handled old flags  %s" % str(old_flags)
4360
    self.old_role = old_role = self._F2R[old_flags]
4361

    
4362
    # Check for ineffective changes
4363
    for attr in self._FLAGS:
4364
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4365
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4366
        setattr(self.op, attr, None)
4367

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

    
4371
    # TODO: We might query the real power state if it supports OOB
4372
    if _SupportsOob(self.cfg, node):
4373
      if self.op.offline is False and not (node.powered or
4374
                                           self.op.powered == True):
4375
        raise errors.OpPrereqError(("Please power on node %s first before you"
4376
                                    " can reset offline state") %
4377
                                   self.op.node_name)
4378
    elif self.op.powered is not None:
4379
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4380
                                  " which does not support out-of-band"
4381
                                  " handling") % self.op.node_name)
4382

    
4383
    # If we're being deofflined/drained, we'll MC ourself if needed
4384
    if (self.op.drained == False or self.op.offline == False or
4385
        (self.op.master_capable and not node.master_capable)):
4386
      if _DecideSelfPromotion(self):
4387
        self.op.master_candidate = True
4388
        self.LogInfo("Auto-promoting node to master candidate")
4389

    
4390
    # If we're no longer master capable, we'll demote ourselves from MC
4391
    if self.op.master_capable == False and node.master_candidate:
4392
      self.LogInfo("Demoting from master candidate")
4393
      self.op.master_candidate = False
4394

    
4395
    # Compute new role
4396
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4397
    if self.op.master_candidate:
4398
      new_role = self._ROLE_CANDIDATE
4399
    elif self.op.drained:
4400
      new_role = self._ROLE_DRAINED
4401
    elif self.op.offline:
4402
      new_role = self._ROLE_OFFLINE
4403
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4404
      # False is still in new flags, which means we're un-setting (the
4405
      # only) True flag
4406
      new_role = self._ROLE_REGULAR
4407
    else: # no new flags, nothing, keep old role
4408
      new_role = old_role
4409

    
4410
    self.new_role = new_role
4411

    
4412
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4413
      # Trying to transition out of offline status
4414
      result = self.rpc.call_version([node.name])[node.name]
4415
      if result.fail_msg:
4416
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4417
                                   " to report its version: %s" %
4418
                                   (node.name, result.fail_msg),
4419
                                   errors.ECODE_STATE)
4420
      else:
4421
        self.LogWarning("Transitioning node from offline to online state"
4422
                        " without using re-add. Please make sure the node"
4423
                        " is healthy!")
4424

    
4425
    if self.op.secondary_ip:
4426
      # Ok even without locking, because this can't be changed by any LU
4427
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4428
      master_singlehomed = master.secondary_ip == master.primary_ip
4429
      if master_singlehomed and self.op.secondary_ip:
4430
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4431
                                   " homed cluster", errors.ECODE_INVAL)
4432

    
4433
      if node.offline:
4434
        if self.affected_instances:
4435
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4436
                                     " node has instances (%s) configured"
4437
                                     " to use it" % self.affected_instances)
4438
      else:
4439
        # On online nodes, check that no instances are running, and that
4440
        # the node has the new ip and we can reach it.
4441
        for instance in self.affected_instances:
4442
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4443

    
4444
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4445
        if master.name != node.name:
4446
          # check reachability from master secondary ip to new secondary ip
4447
          if not netutils.TcpPing(self.op.secondary_ip,
4448
                                  constants.DEFAULT_NODED_PORT,
4449
                                  source=master.secondary_ip):
4450
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4451
                                       " based ping to node daemon port",
4452
                                       errors.ECODE_ENVIRON)
4453

    
4454
    if self.op.ndparams:
4455
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4456
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4457
      self.new_ndparams = new_ndparams
4458

    
4459
  def Exec(self, feedback_fn):
4460
    """Modifies a node.
4461

4462
    """
4463
    node = self.node
4464
    old_role = self.old_role
4465
    new_role = self.new_role
4466

    
4467
    result = []
4468

    
4469
    if self.op.ndparams:
4470
      node.ndparams = self.new_ndparams
4471

    
4472
    if self.op.powered is not None:
4473
      node.powered = self.op.powered
4474

    
4475
    for attr in ["master_capable", "vm_capable"]:
4476
      val = getattr(self.op, attr)
4477
      if val is not None:
4478
        setattr(node, attr, val)
4479
        result.append((attr, str(val)))
4480

    
4481
    if new_role != old_role:
4482
      # Tell the node to demote itself, if no longer MC and not offline
4483
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4484
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4485
        if msg:
4486
          self.LogWarning("Node failed to demote itself: %s", msg)
4487

    
4488
      new_flags = self._R2F[new_role]
4489
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4490
        if of != nf:
4491
          result.append((desc, str(nf)))
4492
      (node.master_candidate, node.drained, node.offline) = new_flags
4493

    
4494
      # we locked all nodes, we adjust the CP before updating this node
4495
      if self.lock_all:
4496
        _AdjustCandidatePool(self, [node.name])
4497

    
4498
    if self.op.secondary_ip:
4499
      node.secondary_ip = self.op.secondary_ip
4500
      result.append(("secondary_ip", self.op.secondary_ip))
4501

    
4502
    # this will trigger configuration file update, if needed
4503
    self.cfg.Update(node, feedback_fn)
4504

    
4505
    # this will trigger job queue propagation or cleanup if the mc
4506
    # flag changed
4507
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4508
      self.context.ReaddNode(node)
4509

    
4510
    return result
4511

    
4512

    
4513
class LUNodePowercycle(NoHooksLU):
4514
  """Powercycles a node.
4515

4516
  """
4517
  REQ_BGL = False
4518

    
4519
  def CheckArguments(self):
4520
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4521
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4522
      raise errors.OpPrereqError("The node is the master and the force"
4523
                                 " parameter was not set",
4524
                                 errors.ECODE_INVAL)
4525

    
4526
  def ExpandNames(self):
4527
    """Locking for PowercycleNode.
4528

4529
    This is a last-resort option and shouldn't block on other
4530
    jobs. Therefore, we grab no locks.
4531

4532
    """
4533
    self.needed_locks = {}
4534

    
4535
  def Exec(self, feedback_fn):
4536
    """Reboots a node.
4537

4538
    """
4539
    result = self.rpc.call_node_powercycle(self.op.node_name,
4540
                                           self.cfg.GetHypervisorType())
4541
    result.Raise("Failed to schedule the reboot")
4542
    return result.payload
4543

    
4544

    
4545
class LUClusterQuery(NoHooksLU):
4546
  """Query cluster configuration.
4547

4548
  """
4549
  REQ_BGL = False
4550

    
4551
  def ExpandNames(self):
4552
    self.needed_locks = {}
4553

    
4554
  def Exec(self, feedback_fn):
4555
    """Return cluster config.
4556

4557
    """
4558
    cluster = self.cfg.GetClusterInfo()
4559
    os_hvp = {}
4560

    
4561
    # Filter just for enabled hypervisors
4562
    for os_name, hv_dict in cluster.os_hvp.items():
4563
      os_hvp[os_name] = {}
4564
      for hv_name, hv_params in hv_dict.items():
4565
        if hv_name in cluster.enabled_hypervisors:
4566
          os_hvp[os_name][hv_name] = hv_params
4567

    
4568
    # Convert ip_family to ip_version
4569
    primary_ip_version = constants.IP4_VERSION
4570
    if cluster.primary_ip_family == netutils.IP6Address.family:
4571
      primary_ip_version = constants.IP6_VERSION
4572

    
4573
    result = {
4574
      "software_version": constants.RELEASE_VERSION,
4575
      "protocol_version": constants.PROTOCOL_VERSION,
4576
      "config_version": constants.CONFIG_VERSION,
4577
      "os_api_version": max(constants.OS_API_VERSIONS),
4578
      "export_version": constants.EXPORT_VERSION,
4579
      "architecture": (platform.architecture()[0], platform.machine()),
4580
      "name": cluster.cluster_name,
4581
      "master": cluster.master_node,
4582
      "default_hypervisor": cluster.enabled_hypervisors[0],
4583
      "enabled_hypervisors": cluster.enabled_hypervisors,
4584
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4585
                        for hypervisor_name in cluster.enabled_hypervisors]),
4586
      "os_hvp": os_hvp,
4587
      "beparams": cluster.beparams,
4588
      "osparams": cluster.osparams,
4589
      "nicparams": cluster.nicparams,
4590
      "ndparams": cluster.ndparams,
4591
      "candidate_pool_size": cluster.candidate_pool_size,
4592
      "master_netdev": cluster.master_netdev,
4593
      "volume_group_name": cluster.volume_group_name,
4594
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4595
      "file_storage_dir": cluster.file_storage_dir,
4596
      "maintain_node_health": cluster.maintain_node_health,
4597
      "ctime": cluster.ctime,
4598
      "mtime": cluster.mtime,
4599
      "uuid": cluster.uuid,
4600
      "tags": list(cluster.GetTags()),
4601
      "uid_pool": cluster.uid_pool,
4602
      "default_iallocator": cluster.default_iallocator,
4603
      "reserved_lvs": cluster.reserved_lvs,
4604
      "primary_ip_version": primary_ip_version,
4605
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
4606
      }
4607

    
4608
    return result
4609

    
4610

    
4611
class LUClusterConfigQuery(NoHooksLU):
4612
  """Return configuration values.
4613

4614
  """
4615
  REQ_BGL = False
4616
  _FIELDS_DYNAMIC = utils.FieldSet()
4617
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4618
                                  "watcher_pause", "volume_group_name")
4619

    
4620
  def CheckArguments(self):
4621
    _CheckOutputFields(static=self._FIELDS_STATIC,
4622
                       dynamic=self._FIELDS_DYNAMIC,
4623
                       selected=self.op.output_fields)
4624

    
4625
  def ExpandNames(self):
4626
    self.needed_locks = {}
4627

    
4628
  def Exec(self, feedback_fn):
4629
    """Dump a representation of the cluster config to the standard output.
4630

4631
    """
4632
    values = []
4633
    for field in self.op.output_fields:
4634
      if field == "cluster_name":
4635
        entry = self.cfg.GetClusterName()
4636
      elif field == "master_node":
4637
        entry = self.cfg.GetMasterNode()
4638
      elif field == "drain_flag":
4639
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4640
      elif field == "watcher_pause":
4641
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4642
      elif field == "volume_group_name":
4643
        entry = self.cfg.GetVGName()
4644
      else:
4645
        raise errors.ParameterError(field)
4646
      values.append(entry)
4647
    return values
4648

    
4649

    
4650
class LUInstanceActivateDisks(NoHooksLU):
4651
  """Bring up an instance's disks.
4652

4653
  """
4654
  REQ_BGL = False
4655

    
4656
  def ExpandNames(self):
4657
    self._ExpandAndLockInstance()
4658
    self.needed_locks[locking.LEVEL_NODE] = []
4659
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4660

    
4661
  def DeclareLocks(self, level):
4662
    if level == locking.LEVEL_NODE:
4663
      self._LockInstancesNodes()
4664

    
4665
  def CheckPrereq(self):
4666
    """Check prerequisites.
4667

4668
    This checks that the instance is in the cluster.
4669

4670
    """
4671
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4672
    assert self.instance is not None, \
4673
      "Cannot retrieve locked instance %s" % self.op.instance_name
4674
    _CheckNodeOnline(self, self.instance.primary_node)
4675

    
4676
  def Exec(self, feedback_fn):
4677
    """Activate the disks.
4678

4679
    """
4680
    disks_ok, disks_info = \
4681
              _AssembleInstanceDisks(self, self.instance,
4682
                                     ignore_size=self.op.ignore_size)
4683
    if not disks_ok:
4684
      raise errors.OpExecError("Cannot activate block devices")
4685

    
4686
    return disks_info
4687

    
4688

    
4689
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4690
                           ignore_size=False):
4691
  """Prepare the block devices for an instance.
4692

4693
  This sets up the block devices on all nodes.
4694

4695
  @type lu: L{LogicalUnit}
4696
  @param lu: the logical unit on whose behalf we execute
4697
  @type instance: L{objects.Instance}
4698
  @param instance: the instance for whose disks we assemble
4699
  @type disks: list of L{objects.Disk} or None
4700
  @param disks: which disks to assemble (or all, if None)
4701
  @type ignore_secondaries: boolean
4702
  @param ignore_secondaries: if true, errors on secondary nodes
4703
      won't result in an error return from the function
4704
  @type ignore_size: boolean
4705
  @param ignore_size: if true, the current known size of the disk
4706
      will not be used during the disk activation, useful for cases
4707
      when the size is wrong
4708
  @return: False if the operation failed, otherwise a list of
4709
      (host, instance_visible_name, node_visible_name)
4710
      with the mapping from node devices to instance devices
4711

4712
  """
4713
  device_info = []
4714
  disks_ok = True
4715
  iname = instance.name
4716
  disks = _ExpandCheckDisks(instance, disks)
4717

    
4718
  # With the two passes mechanism we try to reduce the window of
4719
  # opportunity for the race condition of switching DRBD to primary
4720
  # before handshaking occured, but we do not eliminate it
4721

    
4722
  # The proper fix would be to wait (with some limits) until the
4723
  # connection has been made and drbd transitions from WFConnection
4724
  # into any other network-connected state (Connected, SyncTarget,
4725
  # SyncSource, etc.)
4726

    
4727
  # 1st pass, assemble on all nodes in secondary mode
4728
  for inst_disk in disks:
4729
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4730
      if ignore_size:
4731
        node_disk = node_disk.Copy()
4732
        node_disk.UnsetSize()
4733
      lu.cfg.SetDiskID(node_disk, node)
4734
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4735
      msg = result.fail_msg
4736
      if msg:
4737
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4738
                           " (is_primary=False, pass=1): %s",
4739
                           inst_disk.iv_name, node, msg)
4740
        if not ignore_secondaries:
4741
          disks_ok = False
4742

    
4743
  # FIXME: race condition on drbd migration to primary
4744

    
4745
  # 2nd pass, do only the primary node
4746
  for inst_disk in disks:
4747
    dev_path = None
4748

    
4749
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4750
      if node != instance.primary_node:
4751
        continue
4752
      if ignore_size:
4753
        node_disk = node_disk.Copy()
4754
        node_disk.UnsetSize()
4755
      lu.cfg.SetDiskID(node_disk, node)
4756
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4757
      msg = result.fail_msg
4758
      if msg:
4759
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4760
                           " (is_primary=True, pass=2): %s",
4761
                           inst_disk.iv_name, node, msg)
4762
        disks_ok = False
4763
      else:
4764
        dev_path = result.payload
4765

    
4766
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4767

    
4768
  # leave the disks configured for the primary node
4769
  # this is a workaround that would be fixed better by
4770
  # improving the logical/physical id handling
4771
  for disk in disks:
4772
    lu.cfg.SetDiskID(disk, instance.primary_node)
4773

    
4774
  return disks_ok, device_info
4775

    
4776

    
4777
def _StartInstanceDisks(lu, instance, force):
4778
  """Start the disks of an instance.
4779

4780
  """
4781
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4782
                                           ignore_secondaries=force)
4783
  if not disks_ok:
4784
    _ShutdownInstanceDisks(lu, instance)
4785
    if force is not None and not force:
4786
      lu.proc.LogWarning("", hint="If the message above refers to a"
4787
                         " secondary node,"
4788
                         " you can retry the operation using '--force'.")
4789
    raise errors.OpExecError("Disk consistency error")
4790

    
4791

    
4792
class LUInstanceDeactivateDisks(NoHooksLU):
4793
  """Shutdown an instance's disks.
4794

4795
  """
4796
  REQ_BGL = False
4797

    
4798
  def ExpandNames(self):
4799
    self._ExpandAndLockInstance()
4800
    self.needed_locks[locking.LEVEL_NODE] = []
4801
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4802

    
4803
  def DeclareLocks(self, level):
4804
    if level == locking.LEVEL_NODE:
4805
      self._LockInstancesNodes()
4806

    
4807
  def CheckPrereq(self):
4808
    """Check prerequisites.
4809

4810
    This checks that the instance is in the cluster.
4811

4812
    """
4813
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4814
    assert self.instance is not None, \
4815
      "Cannot retrieve locked instance %s" % self.op.instance_name
4816

    
4817
  def Exec(self, feedback_fn):
4818
    """Deactivate the disks
4819

4820
    """
4821
    instance = self.instance
4822
    _SafeShutdownInstanceDisks(self, instance)
4823

    
4824

    
4825
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4826
  """Shutdown block devices of an instance.
4827

4828
  This function checks if an instance is running, before calling
4829
  _ShutdownInstanceDisks.
4830

4831
  """
4832
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4833
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4834

    
4835

    
4836
def _ExpandCheckDisks(instance, disks):
4837
  """Return the instance disks selected by the disks list
4838

4839
  @type disks: list of L{objects.Disk} or None
4840
  @param disks: selected disks
4841
  @rtype: list of L{objects.Disk}
4842
  @return: selected instance disks to act on
4843

4844
  """
4845
  if disks is None:
4846
    return instance.disks
4847
  else:
4848
    if not set(disks).issubset(instance.disks):
4849
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4850
                                   " target instance")
4851
    return disks
4852

    
4853

    
4854
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4855
  """Shutdown block devices of an instance.
4856

4857
  This does the shutdown on all nodes of the instance.
4858

4859
  If the ignore_primary is false, errors on the primary node are
4860
  ignored.
4861

4862
  """
4863
  all_result = True
4864
  disks = _ExpandCheckDisks(instance, disks)
4865

    
4866
  for disk in disks:
4867
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4868
      lu.cfg.SetDiskID(top_disk, node)
4869
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4870
      msg = result.fail_msg
4871
      if msg:
4872
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4873
                      disk.iv_name, node, msg)
4874
        if ((node == instance.primary_node and not ignore_primary) or
4875
            (node != instance.primary_node and not result.offline)):
4876
          all_result = False
4877
  return all_result
4878

    
4879

    
4880
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4881
  """Checks if a node has enough free memory.
4882

4883
  This function check if a given node has the needed amount of free
4884
  memory. In case the node has less memory or we cannot get the
4885
  information from the node, this function raise an OpPrereqError
4886
  exception.
4887

4888
  @type lu: C{LogicalUnit}
4889
  @param lu: a logical unit from which we get configuration data
4890
  @type node: C{str}
4891
  @param node: the node to check
4892
  @type reason: C{str}
4893
  @param reason: string to use in the error message
4894
  @type requested: C{int}
4895
  @param requested: the amount of memory in MiB to check for
4896
  @type hypervisor_name: C{str}
4897
  @param hypervisor_name: the hypervisor to ask for memory stats
4898
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4899
      we cannot check the node
4900

4901
  """
4902
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
4903
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4904
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4905
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4906
  if not isinstance(free_mem, int):
4907
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4908
                               " was '%s'" % (node, free_mem),
4909
                               errors.ECODE_ENVIRON)
4910
  if requested > free_mem:
4911
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4912
                               " needed %s MiB, available %s MiB" %
4913
                               (node, reason, requested, free_mem),
4914
                               errors.ECODE_NORES)
4915

    
4916

    
4917
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
4918
  """Checks if nodes have enough free disk space in the all VGs.
4919

4920
  This function check if all given nodes have the needed amount of
4921
  free disk. In case any node has less disk or we cannot get the
4922
  information from the node, this function raise an OpPrereqError
4923
  exception.
4924

4925
  @type lu: C{LogicalUnit}
4926
  @param lu: a logical unit from which we get configuration data
4927
  @type nodenames: C{list}
4928
  @param nodenames: the list of node names to check
4929
  @type req_sizes: C{dict}
4930
  @param req_sizes: the hash of vg and corresponding amount of disk in
4931
      MiB to check for
4932
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
4933
      or we cannot check the node
4934

4935
  """
4936
  for vg, req_size in req_sizes.items():
4937
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
4938

    
4939

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

4943
  This function check if all given nodes have the needed amount of
4944
  free disk. In case any node has less disk or we cannot get the
4945
  information from the node, this function raise an OpPrereqError
4946
  exception.
4947

4948
  @type lu: C{LogicalUnit}
4949
  @param lu: a logical unit from which we get configuration data
4950
  @type nodenames: C{list}
4951
  @param nodenames: the list of node names to check
4952
  @type vg: C{str}
4953
  @param vg: the volume group to check
4954
  @type requested: C{int}
4955
  @param requested: the amount of disk in MiB to check for
4956
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
4957
      or we cannot check the node
4958

4959
  """
4960
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
4961
  for node in nodenames:
4962
    info = nodeinfo[node]
4963
    info.Raise("Cannot get current information from node %s" % node,
4964
               prereq=True, ecode=errors.ECODE_ENVIRON)
4965
    vg_free = info.payload.get("vg_free", None)
4966
    if not isinstance(vg_free, int):
4967
      raise errors.OpPrereqError("Can't compute free disk space on node"
4968
                                 " %s for vg %s, result was '%s'" %
4969
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
4970
    if requested > vg_free:
4971
      raise errors.OpPrereqError("Not enough disk space on target node %s"
4972
                                 " vg %s: required %d MiB, available %d MiB" %
4973
                                 (node, vg, requested, vg_free),
4974
                                 errors.ECODE_NORES)
4975

    
4976

    
4977
class LUInstanceStartup(LogicalUnit):
4978
  """Starts an instance.
4979

4980
  """
4981
  HPATH = "instance-start"
4982
  HTYPE = constants.HTYPE_INSTANCE
4983
  REQ_BGL = False
4984

    
4985
  def CheckArguments(self):
4986
    # extra beparams
4987
    if self.op.beparams:
4988
      # fill the beparams dict
4989
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4990

    
4991
  def ExpandNames(self):
4992
    self._ExpandAndLockInstance()
4993

    
4994
  def BuildHooksEnv(self):
4995
    """Build hooks env.
4996

4997
    This runs on master, primary and secondary nodes of the instance.
4998

4999
    """
5000
    env = {
5001
      "FORCE": self.op.force,
5002
      }
5003
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5004
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5005
    return env, nl, nl
5006

    
5007
  def CheckPrereq(self):
5008
    """Check prerequisites.
5009

5010
    This checks that the instance is in the cluster.
5011

5012
    """
5013
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5014
    assert self.instance is not None, \
5015
      "Cannot retrieve locked instance %s" % self.op.instance_name
5016

    
5017
    # extra hvparams
5018
    if self.op.hvparams:
5019
      # check hypervisor parameter syntax (locally)
5020
      cluster = self.cfg.GetClusterInfo()
5021
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5022
      filled_hvp = cluster.FillHV(instance)
5023
      filled_hvp.update(self.op.hvparams)
5024
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5025
      hv_type.CheckParameterSyntax(filled_hvp)
5026
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5027

    
5028
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5029

    
5030
    if self.primary_offline and self.op.ignore_offline_nodes:
5031
      self.proc.LogWarning("Ignoring offline primary node")
5032

    
5033
      if self.op.hvparams or self.op.beparams:
5034
        self.proc.LogWarning("Overridden parameters are ignored")
5035
    else:
5036
      _CheckNodeOnline(self, instance.primary_node)
5037

    
5038
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5039

    
5040
      # check bridges existence
5041
      _CheckInstanceBridgesExist(self, instance)
5042

    
5043
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5044
                                                instance.name,
5045
                                                instance.hypervisor)
5046
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5047
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5048
      if not remote_info.payload: # not running already
5049
        _CheckNodeFreeMemory(self, instance.primary_node,
5050
                             "starting instance %s" % instance.name,
5051
                             bep[constants.BE_MEMORY], instance.hypervisor)
5052

    
5053
  def Exec(self, feedback_fn):
5054
    """Start the instance.
5055

5056
    """
5057
    instance = self.instance
5058
    force = self.op.force
5059

    
5060
    self.cfg.MarkInstanceUp(instance.name)
5061

    
5062
    if self.primary_offline:
5063
      assert self.op.ignore_offline_nodes
5064
      self.proc.LogInfo("Primary node offline, marked instance as started")
5065
    else:
5066
      node_current = instance.primary_node
5067

    
5068
      _StartInstanceDisks(self, instance, force)
5069

    
5070
      result = self.rpc.call_instance_start(node_current, instance,
5071
                                            self.op.hvparams, self.op.beparams)
5072
      msg = result.fail_msg
5073
      if msg:
5074
        _ShutdownInstanceDisks(self, instance)
5075
        raise errors.OpExecError("Could not start instance: %s" % msg)
5076

    
5077

    
5078
class LUInstanceReboot(LogicalUnit):
5079
  """Reboot an instance.
5080

5081
  """
5082
  HPATH = "instance-reboot"
5083
  HTYPE = constants.HTYPE_INSTANCE
5084
  REQ_BGL = False
5085

    
5086
  def ExpandNames(self):
5087
    self._ExpandAndLockInstance()
5088

    
5089
  def BuildHooksEnv(self):
5090
    """Build hooks env.
5091

5092
    This runs on master, primary and secondary nodes of the instance.
5093

5094
    """
5095
    env = {
5096
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5097
      "REBOOT_TYPE": self.op.reboot_type,
5098
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5099
      }
5100
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5101
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5102
    return env, nl, nl
5103

    
5104
  def CheckPrereq(self):
5105
    """Check prerequisites.
5106

5107
    This checks that the instance is in the cluster.
5108

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

    
5114
    _CheckNodeOnline(self, instance.primary_node)
5115

    
5116
    # check bridges existence
5117
    _CheckInstanceBridgesExist(self, instance)
5118

    
5119
  def Exec(self, feedback_fn):
5120
    """Reboot the instance.
5121

5122
    """
5123
    instance = self.instance
5124
    ignore_secondaries = self.op.ignore_secondaries
5125
    reboot_type = self.op.reboot_type
5126

    
5127
    node_current = instance.primary_node
5128

    
5129
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5130
                       constants.INSTANCE_REBOOT_HARD]:
5131
      for disk in instance.disks:
5132
        self.cfg.SetDiskID(disk, node_current)
5133
      result = self.rpc.call_instance_reboot(node_current, instance,
5134
                                             reboot_type,
5135
                                             self.op.shutdown_timeout)
5136
      result.Raise("Could not reboot instance")
5137
    else:
5138
      result = self.rpc.call_instance_shutdown(node_current, instance,
5139
                                               self.op.shutdown_timeout)
5140
      result.Raise("Could not shutdown instance for full reboot")
5141
      _ShutdownInstanceDisks(self, instance)
5142
      _StartInstanceDisks(self, instance, ignore_secondaries)
5143
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5144
      msg = result.fail_msg
5145
      if msg:
5146
        _ShutdownInstanceDisks(self, instance)
5147
        raise errors.OpExecError("Could not start instance for"
5148
                                 " full reboot: %s" % msg)
5149

    
5150
    self.cfg.MarkInstanceUp(instance.name)
5151

    
5152

    
5153
class LUInstanceShutdown(LogicalUnit):
5154
  """Shutdown an instance.
5155

5156
  """
5157
  HPATH = "instance-stop"
5158
  HTYPE = constants.HTYPE_INSTANCE
5159
  REQ_BGL = False
5160

    
5161
  def ExpandNames(self):
5162
    self._ExpandAndLockInstance()
5163

    
5164
  def BuildHooksEnv(self):
5165
    """Build hooks env.
5166

5167
    This runs on master, primary and secondary nodes of the instance.
5168

5169
    """
5170
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5171
    env["TIMEOUT"] = self.op.timeout
5172
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5173
    return env, nl, nl
5174

    
5175
  def CheckPrereq(self):
5176
    """Check prerequisites.
5177

5178
    This checks that the instance is in the cluster.
5179

5180
    """
5181
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5182
    assert self.instance is not None, \
5183
      "Cannot retrieve locked instance %s" % self.op.instance_name
5184

    
5185
    self.primary_offline = \
5186
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5187

    
5188
    if self.primary_offline and self.op.ignore_offline_nodes:
5189
      self.proc.LogWarning("Ignoring offline primary node")
5190
    else:
5191
      _CheckNodeOnline(self, self.instance.primary_node)
5192

    
5193
  def Exec(self, feedback_fn):
5194
    """Shutdown the instance.
5195

5196
    """
5197
    instance = self.instance
5198
    node_current = instance.primary_node
5199
    timeout = self.op.timeout
5200

    
5201
    self.cfg.MarkInstanceDown(instance.name)
5202

    
5203
    if self.primary_offline:
5204
      assert self.op.ignore_offline_nodes
5205
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5206
    else:
5207
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5208
      msg = result.fail_msg
5209
      if msg:
5210
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5211

    
5212
      _ShutdownInstanceDisks(self, instance)
5213

    
5214

    
5215
class LUInstanceReinstall(LogicalUnit):
5216
  """Reinstall an instance.
5217

5218
  """
5219
  HPATH = "instance-reinstall"
5220
  HTYPE = constants.HTYPE_INSTANCE
5221
  REQ_BGL = False
5222

    
5223
  def ExpandNames(self):
5224
    self._ExpandAndLockInstance()
5225

    
5226
  def BuildHooksEnv(self):
5227
    """Build hooks env.
5228

5229
    This runs on master, primary and secondary nodes of the instance.
5230

5231
    """
5232
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5233
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5234
    return env, nl, nl
5235

    
5236
  def CheckPrereq(self):
5237
    """Check prerequisites.
5238

5239
    This checks that the instance is in the cluster and is not running.
5240

5241
    """
5242
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5243
    assert instance is not None, \
5244
      "Cannot retrieve locked instance %s" % self.op.instance_name
5245
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5246
                     " offline, cannot reinstall")
5247
    for node in instance.secondary_nodes:
5248
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5249
                       " cannot reinstall")
5250

    
5251
    if instance.disk_template == constants.DT_DISKLESS:
5252
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5253
                                 self.op.instance_name,
5254
                                 errors.ECODE_INVAL)
5255
    _CheckInstanceDown(self, instance, "cannot reinstall")
5256

    
5257
    if self.op.os_type is not None:
5258
      # OS verification
5259
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5260
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5261
      instance_os = self.op.os_type
5262
    else:
5263
      instance_os = instance.os
5264

    
5265
    nodelist = list(instance.all_nodes)
5266

    
5267
    if self.op.osparams:
5268
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5269
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5270
      self.os_inst = i_osdict # the new dict (without defaults)
5271
    else:
5272
      self.os_inst = None
5273

    
5274
    self.instance = instance
5275

    
5276
  def Exec(self, feedback_fn):
5277
    """Reinstall the instance.
5278

5279
    """
5280
    inst = self.instance
5281

    
5282
    if self.op.os_type is not None:
5283
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5284
      inst.os = self.op.os_type
5285
      # Write to configuration
5286
      self.cfg.Update(inst, feedback_fn)
5287

    
5288
    _StartInstanceDisks(self, inst, None)
5289
    try:
5290
      feedback_fn("Running the instance OS create scripts...")
5291
      # FIXME: pass debug option from opcode to backend
5292
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5293
                                             self.op.debug_level,
5294
                                             osparams=self.os_inst)
5295
      result.Raise("Could not install OS for instance %s on node %s" %
5296
                   (inst.name, inst.primary_node))
5297
    finally:
5298
      _ShutdownInstanceDisks(self, inst)
5299

    
5300

    
5301
class LUInstanceRecreateDisks(LogicalUnit):
5302
  """Recreate an instance's missing disks.
5303

5304
  """
5305
  HPATH = "instance-recreate-disks"
5306
  HTYPE = constants.HTYPE_INSTANCE
5307
  REQ_BGL = False
5308

    
5309
  def ExpandNames(self):
5310
    self._ExpandAndLockInstance()
5311

    
5312
  def BuildHooksEnv(self):
5313
    """Build hooks env.
5314

5315
    This runs on master, primary and secondary nodes of the instance.
5316

5317
    """
5318
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5319
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5320
    return env, nl, nl
5321

    
5322
  def CheckPrereq(self):
5323
    """Check prerequisites.
5324

5325
    This checks that the instance is in the cluster and is not running.
5326

5327
    """
5328
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5329
    assert instance is not None, \
5330
      "Cannot retrieve locked instance %s" % self.op.instance_name
5331
    _CheckNodeOnline(self, instance.primary_node)
5332

    
5333
    if instance.disk_template == constants.DT_DISKLESS:
5334
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5335
                                 self.op.instance_name, errors.ECODE_INVAL)
5336
    _CheckInstanceDown(self, instance, "cannot recreate disks")
5337

    
5338
    if not self.op.disks:
5339
      self.op.disks = range(len(instance.disks))
5340
    else:
5341
      for idx in self.op.disks:
5342
        if idx >= len(instance.disks):
5343
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
5344
                                     errors.ECODE_INVAL)
5345

    
5346
    self.instance = instance
5347

    
5348
  def Exec(self, feedback_fn):
5349
    """Recreate the disks.
5350

5351
    """
5352
    to_skip = []
5353
    for idx, _ in enumerate(self.instance.disks):
5354
      if idx not in self.op.disks: # disk idx has not been passed in
5355
        to_skip.append(idx)
5356
        continue
5357

    
5358
    _CreateDisks(self, self.instance, to_skip=to_skip)
5359

    
5360

    
5361
class LUInstanceRename(LogicalUnit):
5362
  """Rename an instance.
5363

5364
  """
5365
  HPATH = "instance-rename"
5366
  HTYPE = constants.HTYPE_INSTANCE
5367

    
5368
  def CheckArguments(self):
5369
    """Check arguments.
5370

5371
    """
5372
    if self.op.ip_check and not self.op.name_check:
5373
      # TODO: make the ip check more flexible and not depend on the name check
5374
      raise errors.OpPrereqError("Cannot do ip check without a name check",
5375
                                 errors.ECODE_INVAL)
5376

    
5377
  def BuildHooksEnv(self):
5378
    """Build hooks env.
5379

5380
    This runs on master, primary and secondary nodes of the instance.
5381

5382
    """
5383
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5384
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5385
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5386
    return env, nl, nl
5387

    
5388
  def CheckPrereq(self):
5389
    """Check prerequisites.
5390

5391
    This checks that the instance is in the cluster and is not running.
5392

5393
    """
5394
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5395
                                                self.op.instance_name)
5396
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5397
    assert instance is not None
5398
    _CheckNodeOnline(self, instance.primary_node)
5399
    _CheckInstanceDown(self, instance, "cannot rename")
5400
    self.instance = instance
5401

    
5402
    new_name = self.op.new_name
5403
    if self.op.name_check:
5404
      hostname = netutils.GetHostname(name=new_name)
5405
      self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5406
                   hostname.name)
5407
      new_name = self.op.new_name = hostname.name
5408
      if (self.op.ip_check and
5409
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5410
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5411
                                   (hostname.ip, new_name),
5412
                                   errors.ECODE_NOTUNIQUE)
5413

    
5414
    instance_list = self.cfg.GetInstanceList()
5415
    if new_name in instance_list and new_name != instance.name:
5416
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5417
                                 new_name, errors.ECODE_EXISTS)
5418

    
5419
  def Exec(self, feedback_fn):
5420
    """Rename the instance.
5421

5422
    """
5423
    inst = self.instance
5424
    old_name = inst.name
5425

    
5426
    rename_file_storage = False
5427
    if (inst.disk_template == constants.DT_FILE and
5428
        self.op.new_name != inst.name):
5429
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5430
      rename_file_storage = True
5431

    
5432
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5433
    # Change the instance lock. This is definitely safe while we hold the BGL
5434
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
5435
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5436

    
5437
    # re-read the instance from the configuration after rename
5438
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5439

    
5440
    if rename_file_storage:
5441
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5442
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5443
                                                     old_file_storage_dir,
5444
                                                     new_file_storage_dir)
5445
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5446
                   " (but the instance has been renamed in Ganeti)" %
5447
                   (inst.primary_node, old_file_storage_dir,
5448
                    new_file_storage_dir))
5449

    
5450
    _StartInstanceDisks(self, inst, None)
5451
    try:
5452
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5453
                                                 old_name, self.op.debug_level)
5454
      msg = result.fail_msg
5455
      if msg:
5456
        msg = ("Could not run OS rename script for instance %s on node %s"
5457
               " (but the instance has been renamed in Ganeti): %s" %
5458
               (inst.name, inst.primary_node, msg))
5459
        self.proc.LogWarning(msg)
5460
    finally:
5461
      _ShutdownInstanceDisks(self, inst)
5462

    
5463
    return inst.name
5464

    
5465

    
5466
class LUInstanceRemove(LogicalUnit):
5467
  """Remove an instance.
5468

5469
  """
5470
  HPATH = "instance-remove"
5471
  HTYPE = constants.HTYPE_INSTANCE
5472
  REQ_BGL = False
5473

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

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

    
5483
  def BuildHooksEnv(self):
5484
    """Build hooks env.
5485

5486
    This runs on master, primary and secondary nodes of the instance.
5487

5488
    """
5489
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5490
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5491
    nl = [self.cfg.GetMasterNode()]
5492
    nl_post = list(self.instance.all_nodes) + nl
5493
    return env, nl, nl_post
5494

    
5495
  def CheckPrereq(self):
5496
    """Check prerequisites.
5497

5498
    This checks that the instance is in the cluster.
5499

5500
    """
5501
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5502
    assert self.instance is not None, \
5503
      "Cannot retrieve locked instance %s" % self.op.instance_name
5504

    
5505
  def Exec(self, feedback_fn):
5506
    """Remove the instance.
5507

5508
    """
5509
    instance = self.instance
5510
    logging.info("Shutting down instance %s on node %s",
5511
                 instance.name, instance.primary_node)
5512

    
5513
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5514
                                             self.op.shutdown_timeout)
5515
    msg = result.fail_msg
5516
    if msg:
5517
      if self.op.ignore_failures:
5518
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5519
      else:
5520
        raise errors.OpExecError("Could not shutdown instance %s on"
5521
                                 " node %s: %s" %
5522
                                 (instance.name, instance.primary_node, msg))
5523

    
5524
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5525

    
5526

    
5527
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5528
  """Utility function to remove an instance.
5529

5530
  """
5531
  logging.info("Removing block devices for instance %s", instance.name)
5532

    
5533
  if not _RemoveDisks(lu, instance):
5534
    if not ignore_failures:
5535
      raise errors.OpExecError("Can't remove instance's disks")
5536
    feedback_fn("Warning: can't remove instance's disks")
5537

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

    
5540
  lu.cfg.RemoveInstance(instance.name)
5541

    
5542
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5543
    "Instance lock removal conflict"
5544

    
5545
  # Remove lock for the instance
5546
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5547

    
5548

    
5549
class LUInstanceQuery(NoHooksLU):
5550
  """Logical unit for querying instances.
5551

5552
  """
5553
  # pylint: disable-msg=W0142
5554
  REQ_BGL = False
5555

    
5556
  def CheckArguments(self):
5557
    self.iq = _InstanceQuery(self.op.names, self.op.output_fields,
5558
                             self.op.use_locking)
5559

    
5560
  def ExpandNames(self):
5561
    self.iq.ExpandNames(self)
5562

    
5563
  def DeclareLocks(self, level):
5564
    self.iq.DeclareLocks(self, level)
5565

    
5566
  def Exec(self, feedback_fn):
5567
    return self.iq.OldStyleQuery(self)
5568

    
5569

    
5570
class LUInstanceFailover(LogicalUnit):
5571
  """Failover an instance.
5572

5573
  """
5574
  HPATH = "instance-failover"
5575
  HTYPE = constants.HTYPE_INSTANCE
5576
  REQ_BGL = False
5577

    
5578
  def ExpandNames(self):
5579
    self._ExpandAndLockInstance()
5580
    self.needed_locks[locking.LEVEL_NODE] = []
5581
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5582

    
5583
  def DeclareLocks(self, level):
5584
    if level == locking.LEVEL_NODE:
5585
      self._LockInstancesNodes()
5586

    
5587
  def BuildHooksEnv(self):
5588
    """Build hooks env.
5589

5590
    This runs on master, primary and secondary nodes of the instance.
5591

5592
    """
5593
    instance = self.instance
5594
    source_node = instance.primary_node
5595
    target_node = instance.secondary_nodes[0]
5596
    env = {
5597
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5598
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5599
      "OLD_PRIMARY": source_node,
5600
      "OLD_SECONDARY": target_node,
5601
      "NEW_PRIMARY": target_node,
5602
      "NEW_SECONDARY": source_node,
5603
      }
5604
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5605
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5606
    nl_post = list(nl)
5607
    nl_post.append(source_node)
5608
    return env, nl, nl_post
5609

    
5610
  def CheckPrereq(self):
5611
    """Check prerequisites.
5612

5613
    This checks that the instance is in the cluster.
5614

5615
    """
5616
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5617
    assert self.instance is not None, \
5618
      "Cannot retrieve locked instance %s" % self.op.instance_name
5619

    
5620
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5621
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5622
      raise errors.OpPrereqError("Instance's disk layout is not"
5623
                                 " network mirrored, cannot failover.",
5624
                                 errors.ECODE_STATE)
5625

    
5626
    secondary_nodes = instance.secondary_nodes
5627
    if not secondary_nodes:
5628
      raise errors.ProgrammerError("no secondary node but using "
5629
                                   "a mirrored disk template")
5630

    
5631
    target_node = secondary_nodes[0]
5632
    _CheckNodeOnline(self, target_node)
5633
    _CheckNodeNotDrained(self, target_node)
5634
    if instance.admin_up:
5635
      # check memory requirements on the secondary node
5636
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5637
                           instance.name, bep[constants.BE_MEMORY],
5638
                           instance.hypervisor)
5639
    else:
5640
      self.LogInfo("Not checking memory on the secondary node as"
5641
                   " instance will not be started")
5642

    
5643
    # check bridge existance
5644
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5645

    
5646
  def Exec(self, feedback_fn):
5647
    """Failover an instance.
5648

5649
    The failover is done by shutting it down on its present node and
5650
    starting it on the secondary.
5651

5652
    """
5653
    instance = self.instance
5654
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
5655

    
5656
    source_node = instance.primary_node
5657
    target_node = instance.secondary_nodes[0]
5658

    
5659
    if instance.admin_up:
5660
      feedback_fn("* checking disk consistency between source and target")
5661
      for dev in instance.disks:
5662
        # for drbd, these are drbd over lvm
5663
        if not _CheckDiskConsistency(self, dev, target_node, False):
5664
          if not self.op.ignore_consistency:
5665
            raise errors.OpExecError("Disk %s is degraded on target node,"
5666
                                     " aborting failover." % dev.iv_name)
5667
    else:
5668
      feedback_fn("* not checking disk consistency as instance is not running")
5669

    
5670
    feedback_fn("* shutting down instance on source node")
5671
    logging.info("Shutting down instance %s on node %s",
5672
                 instance.name, source_node)
5673

    
5674
    result = self.rpc.call_instance_shutdown(source_node, instance,
5675
                                             self.op.shutdown_timeout)
5676
    msg = result.fail_msg
5677
    if msg:
5678
      if self.op.ignore_consistency or primary_node.offline:
5679
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5680
                             " Proceeding anyway. Please make sure node"
5681
                             " %s is down. Error details: %s",
5682
                             instance.name, source_node, source_node, msg)
5683
      else:
5684
        raise errors.OpExecError("Could not shutdown instance %s on"
5685
                                 " node %s: %s" %
5686
                                 (instance.name, source_node, msg))
5687

    
5688
    feedback_fn("* deactivating the instance's disks on source node")
5689
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5690
      raise errors.OpExecError("Can't shut down the instance's disks.")
5691

    
5692
    instance.primary_node = target_node
5693
    # distribute new instance config to the other nodes
5694
    self.cfg.Update(instance, feedback_fn)
5695

    
5696
    # Only start the instance if it's marked as up
5697
    if instance.admin_up:
5698
      feedback_fn("* activating the instance's disks on target node")
5699
      logging.info("Starting instance %s on node %s",
5700
                   instance.name, target_node)
5701

    
5702
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5703
                                           ignore_secondaries=True)
5704
      if not disks_ok:
5705
        _ShutdownInstanceDisks(self, instance)
5706
        raise errors.OpExecError("Can't activate the instance's disks")
5707

    
5708
      feedback_fn("* starting the instance on the target node")
5709
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5710
      msg = result.fail_msg
5711
      if msg:
5712
        _ShutdownInstanceDisks(self, instance)
5713
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5714
                                 (instance.name, target_node, msg))
5715

    
5716

    
5717
class LUInstanceMigrate(LogicalUnit):
5718
  """Migrate an instance.
5719

5720
  This is migration without shutting down, compared to the failover,
5721
  which is done with shutdown.
5722

5723
  """
5724
  HPATH = "instance-migrate"
5725
  HTYPE = constants.HTYPE_INSTANCE
5726
  REQ_BGL = False
5727

    
5728
  def ExpandNames(self):
5729
    self._ExpandAndLockInstance()
5730

    
5731
    self.needed_locks[locking.LEVEL_NODE] = []
5732
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5733

    
5734
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5735
                                       self.op.cleanup)
5736
    self.tasklets = [self._migrater]
5737

    
5738
  def DeclareLocks(self, level):
5739
    if level == locking.LEVEL_NODE:
5740
      self._LockInstancesNodes()
5741

    
5742
  def BuildHooksEnv(self):
5743
    """Build hooks env.
5744

5745
    This runs on master, primary and secondary nodes of the instance.
5746

5747
    """
5748
    instance = self._migrater.instance
5749
    source_node = instance.primary_node
5750
    target_node = instance.secondary_nodes[0]
5751
    env = _BuildInstanceHookEnvByObject(self, instance)
5752
    env["MIGRATE_LIVE"] = self._migrater.live
5753
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5754
    env.update({
5755
        "OLD_PRIMARY": source_node,
5756
        "OLD_SECONDARY": target_node,
5757
        "NEW_PRIMARY": target_node,
5758
        "NEW_SECONDARY": source_node,
5759
        })
5760
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5761
    nl_post = list(nl)
5762
    nl_post.append(source_node)
5763
    return env, nl, nl_post
5764

    
5765

    
5766
class LUInstanceMove(LogicalUnit):
5767
  """Move an instance by data-copying.
5768

5769
  """
5770
  HPATH = "instance-move"
5771
  HTYPE = constants.HTYPE_INSTANCE
5772
  REQ_BGL = False
5773

    
5774
  def ExpandNames(self):
5775
    self._ExpandAndLockInstance()
5776
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5777
    self.op.target_node = target_node
5778
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5779
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5780

    
5781
  def DeclareLocks(self, level):
5782
    if level == locking.LEVEL_NODE:
5783
      self._LockInstancesNodes(primary_only=True)
5784

    
5785
  def BuildHooksEnv(self):
5786
    """Build hooks env.
5787

5788
    This runs on master, primary and secondary nodes of the instance.
5789

5790
    """
5791
    env = {
5792
      "TARGET_NODE": self.op.target_node,
5793
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5794
      }
5795
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5796
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5797
                                       self.op.target_node]
5798
    return env, nl, nl
5799

    
5800
  def CheckPrereq(self):
5801
    """Check prerequisites.
5802

5803
    This checks that the instance is in the cluster.
5804

5805
    """
5806
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5807
    assert self.instance is not None, \
5808
      "Cannot retrieve locked instance %s" % self.op.instance_name
5809

    
5810
    node = self.cfg.GetNodeInfo(self.op.target_node)
5811
    assert node is not None, \
5812
      "Cannot retrieve locked node %s" % self.op.target_node
5813

    
5814
    self.target_node = target_node = node.name
5815

    
5816
    if target_node == instance.primary_node:
5817
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5818
                                 (instance.name, target_node),
5819
                                 errors.ECODE_STATE)
5820

    
5821
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5822

    
5823
    for idx, dsk in enumerate(instance.disks):
5824
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5825
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5826
                                   " cannot copy" % idx, errors.ECODE_STATE)
5827

    
5828
    _CheckNodeOnline(self, target_node)
5829
    _CheckNodeNotDrained(self, target_node)
5830
    _CheckNodeVmCapable(self, target_node)
5831

    
5832
    if instance.admin_up:
5833
      # check memory requirements on the secondary node
5834
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5835
                           instance.name, bep[constants.BE_MEMORY],
5836
                           instance.hypervisor)
5837
    else:
5838
      self.LogInfo("Not checking memory on the secondary node as"
5839
                   " instance will not be started")
5840

    
5841
    # check bridge existance
5842
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5843

    
5844
  def Exec(self, feedback_fn):
5845
    """Move an instance.
5846

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

5850
    """
5851
    instance = self.instance
5852

    
5853
    source_node = instance.primary_node
5854
    target_node = self.target_node
5855

    
5856
    self.LogInfo("Shutting down instance %s on source node %s",
5857
                 instance.name, source_node)
5858

    
5859
    result = self.rpc.call_instance_shutdown(source_node, instance,
5860
                                             self.op.shutdown_timeout)
5861
    msg = result.fail_msg
5862
    if msg:
5863
      if self.op.ignore_consistency:
5864
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5865
                             " Proceeding anyway. Please make sure node"
5866
                             " %s is down. Error details: %s",
5867
                             instance.name, source_node, source_node, msg)
5868
      else:
5869
        raise errors.OpExecError("Could not shutdown instance %s on"
5870
                                 " node %s: %s" %
5871
                                 (instance.name, source_node, msg))
5872

    
5873
    # create the target disks
5874
    try:
5875
      _CreateDisks(self, instance, target_node=target_node)
5876
    except errors.OpExecError:
5877
      self.LogWarning("Device creation failed, reverting...")
5878
      try:
5879
        _RemoveDisks(self, instance, target_node=target_node)
5880
      finally:
5881
        self.cfg.ReleaseDRBDMinors(instance.name)
5882
        raise
5883

    
5884
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5885

    
5886
    errs = []
5887
    # activate, get path, copy the data over
5888
    for idx, disk in enumerate(instance.disks):
5889
      self.LogInfo("Copying data for disk %d", idx)
5890
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5891
                                               instance.name, True)
5892
      if result.fail_msg:
5893
        self.LogWarning("Can't assemble newly created disk %d: %s",
5894
                        idx, result.fail_msg)
5895
        errs.append(result.fail_msg)
5896
        break
5897
      dev_path = result.payload
5898
      result = self.rpc.call_blockdev_export(source_node, disk,
5899
                                             target_node, dev_path,
5900
                                             cluster_name)
5901
      if result.fail_msg:
5902
        self.LogWarning("Can't copy data over for disk %d: %s",
5903
                        idx, result.fail_msg)
5904
        errs.append(result.fail_msg)
5905
        break
5906

    
5907
    if errs:
5908
      self.LogWarning("Some disks failed to copy, aborting")
5909
      try:
5910
        _RemoveDisks(self, instance, target_node=target_node)
5911
      finally:
5912
        self.cfg.ReleaseDRBDMinors(instance.name)
5913
        raise errors.OpExecError("Errors during disk copy: %s" %
5914
                                 (",".join(errs),))
5915

    
5916
    instance.primary_node = target_node
5917
    self.cfg.Update(instance, feedback_fn)
5918

    
5919
    self.LogInfo("Removing the disks on the original node")
5920
    _RemoveDisks(self, instance, target_node=source_node)
5921

    
5922
    # Only start the instance if it's marked as up
5923
    if instance.admin_up:
5924
      self.LogInfo("Starting instance %s on node %s",
5925
                   instance.name, target_node)
5926

    
5927
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5928
                                           ignore_secondaries=True)
5929
      if not disks_ok:
5930
        _ShutdownInstanceDisks(self, instance)
5931
        raise errors.OpExecError("Can't activate the instance's disks")
5932

    
5933
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5934
      msg = result.fail_msg
5935
      if msg:
5936
        _ShutdownInstanceDisks(self, instance)
5937
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5938
                                 (instance.name, target_node, msg))
5939

    
5940

    
5941
class LUNodeMigrate(LogicalUnit):
5942
  """Migrate all instances from a node.
5943

5944
  """
5945
  HPATH = "node-migrate"
5946
  HTYPE = constants.HTYPE_NODE
5947
  REQ_BGL = False
5948

    
5949
  def ExpandNames(self):
5950
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5951

    
5952
    self.needed_locks = {
5953
      locking.LEVEL_NODE: [self.op.node_name],
5954
      }
5955

    
5956
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5957

    
5958
    # Create tasklets for migrating instances for all instances on this node
5959
    names = []
5960
    tasklets = []
5961

    
5962
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5963
      logging.debug("Migrating instance %s", inst.name)
5964
      names.append(inst.name)
5965

    
5966
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5967

    
5968
    self.tasklets = tasklets
5969

    
5970
    # Declare instance locks
5971
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5972

    
5973
  def DeclareLocks(self, level):
5974
    if level == locking.LEVEL_NODE:
5975
      self._LockInstancesNodes()
5976

    
5977
  def BuildHooksEnv(self):
5978
    """Build hooks env.
5979

5980
    This runs on the master, the primary and all the secondaries.
5981

5982
    """
5983
    env = {
5984
      "NODE_NAME": self.op.node_name,
5985
      }
5986

    
5987
    nl = [self.cfg.GetMasterNode()]
5988

    
5989
    return (env, nl, nl)
5990

    
5991

    
5992
class TLMigrateInstance(Tasklet):
5993
  """Tasklet class for instance migration.
5994

5995
  @type live: boolean
5996
  @ivar live: whether the migration will be done live or non-live;
5997
      this variable is initalized only after CheckPrereq has run
5998

5999
  """
6000
  def __init__(self, lu, instance_name, cleanup):
6001
    """Initializes this class.
6002

6003
    """
6004
    Tasklet.__init__(self, lu)
6005

    
6006
    # Parameters
6007
    self.instance_name = instance_name
6008
    self.cleanup = cleanup
6009
    self.live = False # will be overridden later
6010

    
6011
  def CheckPrereq(self):
6012
    """Check prerequisites.
6013

6014
    This checks that the instance is in the cluster.
6015

6016
    """
6017
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6018
    instance = self.cfg.GetInstanceInfo(instance_name)
6019
    assert instance is not None
6020

    
6021
    if instance.disk_template != constants.DT_DRBD8:
6022
      raise errors.OpPrereqError("Instance's disk layout is not"
6023
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
6024

    
6025
    secondary_nodes = instance.secondary_nodes
6026
    if not secondary_nodes:
6027
      raise errors.ConfigurationError("No secondary node but using"
6028
                                      " drbd8 disk template")
6029

    
6030
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6031

    
6032
    target_node = secondary_nodes[0]
6033
    # check memory requirements on the secondary node
6034
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6035
                         instance.name, i_be[constants.BE_MEMORY],
6036
                         instance.hypervisor)
6037

    
6038
    # check bridge existance
6039
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6040

    
6041
    if not self.cleanup:
6042
      _CheckNodeNotDrained(self.lu, target_node)
6043
      result = self.rpc.call_instance_migratable(instance.primary_node,
6044
                                                 instance)
6045
      result.Raise("Can't migrate, please use failover",
6046
                   prereq=True, ecode=errors.ECODE_STATE)
6047

    
6048
    self.instance = instance
6049

    
6050
    if self.lu.op.live is not None and self.lu.op.mode is not None:
6051
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6052
                                 " parameters are accepted",
6053
                                 errors.ECODE_INVAL)
6054
    if self.lu.op.live is not None:
6055
      if self.lu.op.live:
6056
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
6057
      else:
6058
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6059
      # reset the 'live' parameter to None so that repeated
6060
      # invocations of CheckPrereq do not raise an exception
6061
      self.lu.op.live = None
6062
    elif self.lu.op.mode is None:
6063
      # read the default value from the hypervisor
6064
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
6065
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6066

    
6067
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6068

    
6069
  def _WaitUntilSync(self):
6070
    """Poll with custom rpc for disk sync.
6071

6072
    This uses our own step-based rpc call.
6073

6074
    """
6075
    self.feedback_fn("* wait until resync is done")
6076
    all_done = False
6077
    while not all_done:
6078
      all_done = True
6079
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6080
                                            self.nodes_ip,
6081
                                            self.instance.disks)
6082
      min_percent = 100
6083
      for node, nres in result.items():
6084
        nres.Raise("Cannot resync disks on node %s" % node)
6085
        node_done, node_percent = nres.payload
6086
        all_done = all_done and node_done
6087
        if node_percent is not None:
6088
          min_percent = min(min_percent, node_percent)
6089
      if not all_done:
6090
        if min_percent < 100:
6091
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6092
        time.sleep(2)
6093

    
6094
  def _EnsureSecondary(self, node):
6095
    """Demote a node to secondary.
6096

6097
    """
6098
    self.feedback_fn("* switching node %s to secondary mode" % node)
6099

    
6100
    for dev in self.instance.disks:
6101
      self.cfg.SetDiskID(dev, node)
6102

    
6103
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6104
                                          self.instance.disks)
6105
    result.Raise("Cannot change disk to secondary on node %s" % node)
6106

    
6107
  def _GoStandalone(self):
6108
    """Disconnect from the network.
6109

6110
    """
6111
    self.feedback_fn("* changing into standalone mode")
6112
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6113
                                               self.instance.disks)
6114
    for node, nres in result.items():
6115
      nres.Raise("Cannot disconnect disks node %s" % node)
6116

    
6117
  def _GoReconnect(self, multimaster):
6118
    """Reconnect to the network.
6119

6120
    """
6121
    if multimaster:
6122
      msg = "dual-master"
6123
    else:
6124
      msg = "single-master"
6125
    self.feedback_fn("* changing disks into %s mode" % msg)
6126
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6127
                                           self.instance.disks,
6128
                                           self.instance.name, multimaster)
6129
    for node, nres in result.items():
6130
      nres.Raise("Cannot change disks config on node %s" % node)
6131

    
6132
  def _ExecCleanup(self):
6133
    """Try to cleanup after a failed migration.
6134

6135
    The cleanup is done by:
6136
      - check that the instance is running only on one node
6137
        (and update the config if needed)
6138
      - change disks on its secondary node to secondary
6139
      - wait until disks are fully synchronized
6140
      - disconnect from the network
6141
      - change disks into single-master mode
6142
      - wait again until disks are fully synchronized
6143

6144
    """
6145
    instance = self.instance
6146
    target_node = self.target_node
6147
    source_node = self.source_node
6148

    
6149
    # check running on only one node
6150
    self.feedback_fn("* checking where the instance actually runs"
6151
                     " (if this hangs, the hypervisor might be in"
6152
                     " a bad state)")
6153
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6154
    for node, result in ins_l.items():
6155
      result.Raise("Can't contact node %s" % node)
6156

    
6157
    runningon_source = instance.name in ins_l[source_node].payload
6158
    runningon_target = instance.name in ins_l[target_node].payload
6159

    
6160
    if runningon_source and runningon_target:
6161
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6162
                               " or the hypervisor is confused. You will have"
6163
                               " to ensure manually that it runs only on one"
6164
                               " and restart this operation.")
6165

    
6166
    if not (runningon_source or runningon_target):
6167
      raise errors.OpExecError("Instance does not seem to be running at all."
6168
                               " In this case, it's safer to repair by"
6169
                               " running 'gnt-instance stop' to ensure disk"
6170
                               " shutdown, and then restarting it.")
6171

    
6172
    if runningon_target:
6173
      # the migration has actually succeeded, we need to update the config
6174
      self.feedback_fn("* instance running on secondary node (%s),"
6175
                       " updating config" % target_node)
6176
      instance.primary_node = target_node
6177
      self.cfg.Update(instance, self.feedback_fn)
6178
      demoted_node = source_node
6179
    else:
6180
      self.feedback_fn("* instance confirmed to be running on its"
6181
                       " primary node (%s)" % source_node)
6182
      demoted_node = target_node
6183

    
6184
    self._EnsureSecondary(demoted_node)
6185
    try:
6186
      self._WaitUntilSync()
6187
    except errors.OpExecError:
6188
      # we ignore here errors, since if the device is standalone, it
6189
      # won't be able to sync
6190
      pass
6191
    self._GoStandalone()
6192
    self._GoReconnect(False)
6193
    self._WaitUntilSync()
6194

    
6195
    self.feedback_fn("* done")
6196

    
6197
  def _RevertDiskStatus(self):
6198
    """Try to revert the disk status after a failed migration.
6199

6200
    """
6201
    target_node = self.target_node
6202
    try:
6203
      self._EnsureSecondary(target_node)
6204
      self._GoStandalone()
6205
      self._GoReconnect(False)
6206
      self._WaitUntilSync()
6207
    except errors.OpExecError, err:
6208
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6209
                         " drives: error '%s'\n"
6210
                         "Please look and recover the instance status" %
6211
                         str(err))
6212

    
6213
  def _AbortMigration(self):
6214
    """Call the hypervisor code to abort a started migration.
6215

6216
    """
6217
    instance = self.instance
6218
    target_node = self.target_node
6219
    migration_info = self.migration_info
6220

    
6221
    abort_result = self.rpc.call_finalize_migration(target_node,
6222
                                                    instance,
6223
                                                    migration_info,
6224
                                                    False)
6225
    abort_msg = abort_result.fail_msg
6226
    if abort_msg:
6227
      logging.error("Aborting migration failed on target node %s: %s",
6228
                    target_node, abort_msg)
6229
      # Don't raise an exception here, as we stil have to try to revert the
6230
      # disk status, even if this step failed.
6231

    
6232
  def _ExecMigration(self):
6233
    """Migrate an instance.
6234

6235
    The migrate is done by:
6236
      - change the disks into dual-master mode
6237
      - wait until disks are fully synchronized again
6238
      - migrate the instance
6239
      - change disks on the new secondary node (the old primary) to secondary
6240
      - wait until disks are fully synchronized
6241
      - change disks into single-master mode
6242

6243
    """
6244
    instance = self.instance
6245
    target_node = self.target_node
6246
    source_node = self.source_node
6247

    
6248
    self.feedback_fn("* checking disk consistency between source and target")
6249
    for dev in instance.disks:
6250
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6251
        raise errors.OpExecError("Disk %s is degraded or not fully"
6252
                                 " synchronized on target node,"
6253
                                 " aborting migrate." % dev.iv_name)
6254

    
6255
    # First get the migration information from the remote node
6256
    result = self.rpc.call_migration_info(source_node, instance)
6257
    msg = result.fail_msg
6258
    if msg:
6259
      log_err = ("Failed fetching source migration information from %s: %s" %
6260
                 (source_node, msg))
6261
      logging.error(log_err)
6262
      raise errors.OpExecError(log_err)
6263

    
6264
    self.migration_info = migration_info = result.payload
6265

    
6266
    # Then switch the disks to master/master mode
6267
    self._EnsureSecondary(target_node)
6268
    self._GoStandalone()
6269
    self._GoReconnect(True)
6270
    self._WaitUntilSync()
6271

    
6272
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6273
    result = self.rpc.call_accept_instance(target_node,
6274
                                           instance,
6275
                                           migration_info,
6276
                                           self.nodes_ip[target_node])
6277

    
6278
    msg = result.fail_msg
6279
    if msg:
6280
      logging.error("Instance pre-migration failed, trying to revert"
6281
                    " disk status: %s", msg)
6282
      self.feedback_fn("Pre-migration failed, aborting")
6283
      self._AbortMigration()
6284
      self._RevertDiskStatus()
6285
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6286
                               (instance.name, msg))
6287

    
6288
    self.feedback_fn("* migrating instance to %s" % target_node)
6289
    time.sleep(10)
6290
    result = self.rpc.call_instance_migrate(source_node, instance,
6291
                                            self.nodes_ip[target_node],
6292
                                            self.live)
6293
    msg = result.fail_msg
6294
    if msg:
6295
      logging.error("Instance migration failed, trying to revert"
6296
                    " disk status: %s", msg)
6297
      self.feedback_fn("Migration failed, aborting")
6298
      self._AbortMigration()
6299
      self._RevertDiskStatus()
6300
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6301
                               (instance.name, msg))
6302
    time.sleep(10)
6303

    
6304
    instance.primary_node = target_node
6305
    # distribute new instance config to the other nodes
6306
    self.cfg.Update(instance, self.feedback_fn)
6307

    
6308
    result = self.rpc.call_finalize_migration(target_node,
6309
                                              instance,
6310
                                              migration_info,
6311
                                              True)
6312
    msg = result.fail_msg
6313
    if msg:
6314
      logging.error("Instance migration succeeded, but finalization failed:"
6315
                    " %s", msg)
6316
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6317
                               msg)
6318

    
6319
    self._EnsureSecondary(source_node)
6320
    self._WaitUntilSync()
6321
    self._GoStandalone()
6322
    self._GoReconnect(False)
6323
    self._WaitUntilSync()
6324

    
6325
    self.feedback_fn("* done")
6326

    
6327
  def Exec(self, feedback_fn):
6328
    """Perform the migration.
6329

6330
    """
6331
    feedback_fn("Migrating instance %s" % self.instance.name)
6332

    
6333
    self.feedback_fn = feedback_fn
6334

    
6335
    self.source_node = self.instance.primary_node
6336
    self.target_node = self.instance.secondary_nodes[0]
6337
    self.all_nodes = [self.source_node, self.target_node]
6338
    self.nodes_ip = {
6339
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6340
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6341
      }
6342

    
6343
    if self.cleanup:
6344
      return self._ExecCleanup()
6345
    else:
6346
      return self._ExecMigration()
6347

    
6348

    
6349
def _CreateBlockDev(lu, node, instance, device, force_create,
6350
                    info, force_open):
6351
  """Create a tree of block devices on a given node.
6352

6353
  If this device type has to be created on secondaries, create it and
6354
  all its children.
6355

6356
  If not, just recurse to children keeping the same 'force' value.
6357

6358
  @param lu: the lu on whose behalf we execute
6359
  @param node: the node on which to create the device
6360
  @type instance: L{objects.Instance}
6361
  @param instance: the instance which owns the device
6362
  @type device: L{objects.Disk}
6363
  @param device: the device to create
6364
  @type force_create: boolean
6365
  @param force_create: whether to force creation of this device; this
6366
      will be change to True whenever we find a device which has
6367
      CreateOnSecondary() attribute
6368
  @param info: the extra 'metadata' we should attach to the device
6369
      (this will be represented as a LVM tag)
6370
  @type force_open: boolean
6371
  @param force_open: this parameter will be passes to the
6372
      L{backend.BlockdevCreate} function where it specifies
6373
      whether we run on primary or not, and it affects both
6374
      the child assembly and the device own Open() execution
6375

6376
  """
6377
  if device.CreateOnSecondary():
6378
    force_create = True
6379

    
6380
  if device.children:
6381
    for child in device.children:
6382
      _CreateBlockDev(lu, node, instance, child, force_create,
6383
                      info, force_open)
6384

    
6385
  if not force_create:
6386
    return
6387

    
6388
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6389

    
6390

    
6391
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6392
  """Create a single block device on a given node.
6393

6394
  This will not recurse over children of the device, so they must be
6395
  created in advance.
6396

6397
  @param lu: the lu on whose behalf we execute
6398
  @param node: the node on which to create the device
6399
  @type instance: L{objects.Instance}
6400
  @param instance: the instance which owns the device
6401
  @type device: L{objects.Disk}
6402
  @param device: the device to create
6403
  @param info: the extra 'metadata' we should attach to the device
6404
      (this will be represented as a LVM tag)
6405
  @type force_open: boolean
6406
  @param force_open: this parameter will be passes to the
6407
      L{backend.BlockdevCreate} function where it specifies
6408
      whether we run on primary or not, and it affects both
6409
      the child assembly and the device own Open() execution
6410

6411
  """
6412
  lu.cfg.SetDiskID(device, node)
6413
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6414
                                       instance.name, force_open, info)
6415
  result.Raise("Can't create block device %s on"
6416
               " node %s for instance %s" % (device, node, instance.name))
6417
  if device.physical_id is None:
6418
    device.physical_id = result.payload
6419

    
6420

    
6421
def _GenerateUniqueNames(lu, exts):
6422
  """Generate a suitable LV name.
6423

6424
  This will generate a logical volume name for the given instance.
6425

6426
  """
6427
  results = []
6428
  for val in exts:
6429
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6430
    results.append("%s%s" % (new_id, val))
6431
  return results
6432

    
6433

    
6434
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgname, names, iv_name,
6435
                         p_minor, s_minor):
6436
  """Generate a drbd8 device complete with its children.
6437

6438
  """
6439
  port = lu.cfg.AllocatePort()
6440
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6441
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6442
                          logical_id=(vgname, names[0]))
6443
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6444
                          logical_id=(vgname, names[1]))
6445
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6446
                          logical_id=(primary, secondary, port,
6447
                                      p_minor, s_minor,
6448
                                      shared_secret),
6449
                          children=[dev_data, dev_meta],
6450
                          iv_name=iv_name)
6451
  return drbd_dev
6452

    
6453

    
6454
def _GenerateDiskTemplate(lu, template_name,
6455
                          instance_name, primary_node,
6456
                          secondary_nodes, disk_info,
6457
                          file_storage_dir, file_driver,
6458
                          base_index, feedback_fn):
6459
  """Generate the entire disk layout for a given template type.
6460

6461
  """
6462
  #TODO: compute space requirements
6463

    
6464
  vgname = lu.cfg.GetVGName()
6465
  disk_count = len(disk_info)
6466
  disks = []
6467
  if template_name == constants.DT_DISKLESS:
6468
    pass
6469
  elif template_name == constants.DT_PLAIN:
6470
    if len(secondary_nodes) != 0:
6471
      raise errors.ProgrammerError("Wrong template configuration")
6472

    
6473
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6474
                                      for i in range(disk_count)])
6475
    for idx, disk in enumerate(disk_info):
6476
      disk_index = idx + base_index
6477
      vg = disk.get("vg", vgname)
6478
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
6479
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6480
                              logical_id=(vg, names[idx]),
6481
                              iv_name="disk/%d" % disk_index,
6482
                              mode=disk["mode"])
6483
      disks.append(disk_dev)
6484
  elif template_name == constants.DT_DRBD8:
6485
    if len(secondary_nodes) != 1:
6486
      raise errors.ProgrammerError("Wrong template configuration")
6487
    remote_node = secondary_nodes[0]
6488
    minors = lu.cfg.AllocateDRBDMinor(
6489
      [primary_node, remote_node] * len(disk_info), instance_name)
6490

    
6491
    names = []
6492
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6493
                                               for i in range(disk_count)]):
6494
      names.append(lv_prefix + "_data")
6495
      names.append(lv_prefix + "_meta")
6496
    for idx, disk in enumerate(disk_info):
6497
      disk_index = idx + base_index
6498
      vg = disk.get("vg", vgname)
6499
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6500
                                      disk["size"], vg, names[idx*2:idx*2+2],
6501
                                      "disk/%d" % disk_index,
6502
                                      minors[idx*2], minors[idx*2+1])
6503
      disk_dev.mode = disk["mode"]
6504
      disks.append(disk_dev)
6505
  elif template_name == constants.DT_FILE:
6506
    if len(secondary_nodes) != 0:
6507
      raise errors.ProgrammerError("Wrong template configuration")
6508

    
6509
    opcodes.RequireFileStorage()
6510

    
6511
    for idx, disk in enumerate(disk_info):
6512
      disk_index = idx + base_index
6513
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6514
                              iv_name="disk/%d" % disk_index,
6515
                              logical_id=(file_driver,
6516
                                          "%s/disk%d" % (file_storage_dir,
6517
                                                         disk_index)),
6518
                              mode=disk["mode"])
6519
      disks.append(disk_dev)
6520
  else:
6521
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6522
  return disks
6523

    
6524

    
6525
def _GetInstanceInfoText(instance):
6526
  """Compute that text that should be added to the disk's metadata.
6527

6528
  """
6529
  return "originstname+%s" % instance.name
6530

    
6531

    
6532
def _CalcEta(time_taken, written, total_size):
6533
  """Calculates the ETA based on size written and total size.
6534

6535
  @param time_taken: The time taken so far
6536
  @param written: amount written so far
6537
  @param total_size: The total size of data to be written
6538
  @return: The remaining time in seconds
6539

6540
  """
6541
  avg_time = time_taken / float(written)
6542
  return (total_size - written) * avg_time
6543

    
6544

    
6545
def _WipeDisks(lu, instance):
6546
  """Wipes instance disks.
6547

6548
  @type lu: L{LogicalUnit}
6549
  @param lu: the logical unit on whose behalf we execute
6550
  @type instance: L{objects.Instance}
6551
  @param instance: the instance whose disks we should create
6552
  @return: the success of the wipe
6553

6554
  """
6555
  node = instance.primary_node
6556
  logging.info("Pause sync of instance %s disks", instance.name)
6557
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
6558

    
6559
  for idx, success in enumerate(result.payload):
6560
    if not success:
6561
      logging.warn("pause-sync of instance %s for disks %d failed",
6562
                   instance.name, idx)
6563

    
6564
  try:
6565
    for idx, device in enumerate(instance.disks):
6566
      lu.LogInfo("* Wiping disk %d", idx)
6567
      logging.info("Wiping disk %d for instance %s", idx, instance.name)
6568

    
6569
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
6570
      # MAX_WIPE_CHUNK at max
6571
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
6572
                            constants.MIN_WIPE_CHUNK_PERCENT)
6573

    
6574
      offset = 0
6575
      size = device.size
6576
      last_output = 0
6577
      start_time = time.time()
6578

    
6579
      while offset < size:
6580
        wipe_size = min(wipe_chunk_size, size - offset)
6581
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
6582
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
6583
                     (idx, offset, wipe_size))
6584
        now = time.time()
6585
        offset += wipe_size
6586
        if now - last_output >= 60:
6587
          eta = _CalcEta(now - start_time, offset, size)
6588
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
6589
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
6590
          last_output = now
6591
  finally:
6592
    logging.info("Resume sync of instance %s disks", instance.name)
6593

    
6594
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
6595

    
6596
    for idx, success in enumerate(result.payload):
6597
      if not success:
6598
        lu.LogWarning("Warning: Resume sync of disk %d failed. Please have a"
6599
                      " look at the status and troubleshoot the issue.", idx)
6600
        logging.warn("resume-sync of instance %s for disks %d failed",
6601
                     instance.name, idx)
6602

    
6603

    
6604
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6605
  """Create all disks for an instance.
6606

6607
  This abstracts away some work from AddInstance.
6608

6609
  @type lu: L{LogicalUnit}
6610
  @param lu: the logical unit on whose behalf we execute
6611
  @type instance: L{objects.Instance}
6612
  @param instance: the instance whose disks we should create
6613
  @type to_skip: list
6614
  @param to_skip: list of indices to skip
6615
  @type target_node: string
6616
  @param target_node: if passed, overrides the target node for creation
6617
  @rtype: boolean
6618
  @return: the success of the creation
6619

6620
  """
6621
  info = _GetInstanceInfoText(instance)
6622
  if target_node is None:
6623
    pnode = instance.primary_node
6624
    all_nodes = instance.all_nodes
6625
  else:
6626
    pnode = target_node
6627
    all_nodes = [pnode]
6628

    
6629
  if instance.disk_template == constants.DT_FILE:
6630
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6631
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6632

    
6633
    result.Raise("Failed to create directory '%s' on"
6634
                 " node %s" % (file_storage_dir, pnode))
6635

    
6636
  # Note: this needs to be kept in sync with adding of disks in
6637
  # LUInstanceSetParams
6638
  for idx, device in enumerate(instance.disks):
6639
    if to_skip and idx in to_skip:
6640
      continue
6641
    logging.info("Creating volume %s for instance %s",
6642
                 device.iv_name, instance.name)
6643
    #HARDCODE
6644
    for node in all_nodes:
6645
      f_create = node == pnode
6646
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6647

    
6648

    
6649
def _RemoveDisks(lu, instance, target_node=None):
6650
  """Remove all disks for an instance.
6651

6652
  This abstracts away some work from `AddInstance()` and
6653
  `RemoveInstance()`. Note that in case some of the devices couldn't
6654
  be removed, the removal will continue with the other ones (compare
6655
  with `_CreateDisks()`).
6656

6657
  @type lu: L{LogicalUnit}
6658
  @param lu: the logical unit on whose behalf we execute
6659
  @type instance: L{objects.Instance}
6660
  @param instance: the instance whose disks we should remove
6661
  @type target_node: string
6662
  @param target_node: used to override the node on which to remove the disks
6663
  @rtype: boolean
6664
  @return: the success of the removal
6665

6666
  """
6667
  logging.info("Removing block devices for instance %s", instance.name)
6668

    
6669
  all_result = True
6670
  for device in instance.disks:
6671
    if target_node:
6672
      edata = [(target_node, device)]
6673
    else:
6674
      edata = device.ComputeNodeTree(instance.primary_node)
6675
    for node, disk in edata:
6676
      lu.cfg.SetDiskID(disk, node)
6677
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6678
      if msg:
6679
        lu.LogWarning("Could not remove block device %s on node %s,"
6680
                      " continuing anyway: %s", device.iv_name, node, msg)
6681
        all_result = False
6682

    
6683
  if instance.disk_template == constants.DT_FILE:
6684
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6685
    if target_node:
6686
      tgt = target_node
6687
    else:
6688
      tgt = instance.primary_node
6689
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6690
    if result.fail_msg:
6691
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6692
                    file_storage_dir, instance.primary_node, result.fail_msg)
6693
      all_result = False
6694

    
6695
  return all_result
6696

    
6697

    
6698
def _ComputeDiskSizePerVG(disk_template, disks):
6699
  """Compute disk size requirements in the volume group
6700

6701
  """
6702
  def _compute(disks, payload):
6703
    """Universal algorithm
6704

6705
    """
6706
    vgs = {}
6707
    for disk in disks:
6708
      vgs[disk["vg"]] = vgs.get("vg", 0) + disk["size"] + payload
6709

    
6710
    return vgs
6711

    
6712
  # Required free disk space as a function of disk and swap space
6713
  req_size_dict = {
6714
    constants.DT_DISKLESS: {},
6715
    constants.DT_PLAIN: _compute(disks, 0),
6716
    # 128 MB are added for drbd metadata for each disk
6717
    constants.DT_DRBD8: _compute(disks, 128),
6718
    constants.DT_FILE: {},
6719
  }
6720

    
6721
  if disk_template not in req_size_dict:
6722
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6723
                                 " is unknown" %  disk_template)
6724

    
6725
  return req_size_dict[disk_template]
6726

    
6727

    
6728
def _ComputeDiskSize(disk_template, disks):
6729
  """Compute disk size requirements in the volume group
6730

6731
  """
6732
  # Required free disk space as a function of disk and swap space
6733
  req_size_dict = {
6734
    constants.DT_DISKLESS: None,
6735
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6736
    # 128 MB are added for drbd metadata for each disk
6737
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6738
    constants.DT_FILE: None,
6739
  }
6740

    
6741
  if disk_template not in req_size_dict:
6742
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6743
                                 " is unknown" %  disk_template)
6744

    
6745
  return req_size_dict[disk_template]
6746

    
6747

    
6748
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6749
  """Hypervisor parameter validation.
6750

6751
  This function abstract the hypervisor parameter validation to be
6752
  used in both instance create and instance modify.
6753

6754
  @type lu: L{LogicalUnit}
6755
  @param lu: the logical unit for which we check
6756
  @type nodenames: list
6757
  @param nodenames: the list of nodes on which we should check
6758
  @type hvname: string
6759
  @param hvname: the name of the hypervisor we should use
6760
  @type hvparams: dict
6761
  @param hvparams: the parameters which we need to check
6762
  @raise errors.OpPrereqError: if the parameters are not valid
6763

6764
  """
6765
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6766
                                                  hvname,
6767
                                                  hvparams)
6768
  for node in nodenames:
6769
    info = hvinfo[node]
6770
    if info.offline:
6771
      continue
6772
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6773

    
6774

    
6775
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6776
  """OS parameters validation.
6777

6778
  @type lu: L{LogicalUnit}
6779
  @param lu: the logical unit for which we check
6780
  @type required: boolean
6781
  @param required: whether the validation should fail if the OS is not
6782
      found
6783
  @type nodenames: list
6784
  @param nodenames: the list of nodes on which we should check
6785
  @type osname: string
6786
  @param osname: the name of the hypervisor we should use
6787
  @type osparams: dict
6788
  @param osparams: the parameters which we need to check
6789
  @raise errors.OpPrereqError: if the parameters are not valid
6790

6791
  """
6792
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6793
                                   [constants.OS_VALIDATE_PARAMETERS],
6794
                                   osparams)
6795
  for node, nres in result.items():
6796
    # we don't check for offline cases since this should be run only
6797
    # against the master node and/or an instance's nodes
6798
    nres.Raise("OS Parameters validation failed on node %s" % node)
6799
    if not nres.payload:
6800
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6801
                 osname, node)
6802

    
6803

    
6804
class LUInstanceCreate(LogicalUnit):
6805
  """Create an instance.
6806

6807
  """
6808
  HPATH = "instance-add"
6809
  HTYPE = constants.HTYPE_INSTANCE
6810
  REQ_BGL = False
6811

    
6812
  def CheckArguments(self):
6813
    """Check arguments.
6814

6815
    """
6816
    # do not require name_check to ease forward/backward compatibility
6817
    # for tools
6818
    if self.op.no_install and self.op.start:
6819
      self.LogInfo("No-installation mode selected, disabling startup")
6820
      self.op.start = False
6821
    # validate/normalize the instance name
6822
    self.op.instance_name = \
6823
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
6824

    
6825
    if self.op.ip_check and not self.op.name_check:
6826
      # TODO: make the ip check more flexible and not depend on the name check
6827
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6828
                                 errors.ECODE_INVAL)
6829

    
6830
    # check nics' parameter names
6831
    for nic in self.op.nics:
6832
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6833

    
6834
    # check disks. parameter names and consistent adopt/no-adopt strategy
6835
    has_adopt = has_no_adopt = False
6836
    for disk in self.op.disks:
6837
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6838
      if "adopt" in disk:
6839
        has_adopt = True
6840
      else:
6841
        has_no_adopt = True
6842
    if has_adopt and has_no_adopt:
6843
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6844
                                 errors.ECODE_INVAL)
6845
    if has_adopt:
6846
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6847
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6848
                                   " '%s' disk template" %
6849
                                   self.op.disk_template,
6850
                                   errors.ECODE_INVAL)
6851
      if self.op.iallocator is not None:
6852
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6853
                                   " iallocator script", errors.ECODE_INVAL)
6854
      if self.op.mode == constants.INSTANCE_IMPORT:
6855
        raise errors.OpPrereqError("Disk adoption not allowed for"
6856
                                   " instance import", errors.ECODE_INVAL)
6857

    
6858
    self.adopt_disks = has_adopt
6859

    
6860
    # instance name verification
6861
    if self.op.name_check:
6862
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
6863
      self.op.instance_name = self.hostname1.name
6864
      # used in CheckPrereq for ip ping check
6865
      self.check_ip = self.hostname1.ip
6866
    else:
6867
      self.check_ip = None
6868

    
6869
    # file storage checks
6870
    if (self.op.file_driver and
6871
        not self.op.file_driver in constants.FILE_DRIVER):
6872
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6873
                                 self.op.file_driver, errors.ECODE_INVAL)
6874

    
6875
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6876
      raise errors.OpPrereqError("File storage directory path not absolute",
6877
                                 errors.ECODE_INVAL)
6878

    
6879
    ### Node/iallocator related checks
6880
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6881

    
6882
    if self.op.pnode is not None:
6883
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6884
        if self.op.snode is None:
6885
          raise errors.OpPrereqError("The networked disk templates need"
6886
                                     " a mirror node", errors.ECODE_INVAL)
6887
      elif self.op.snode:
6888
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6889
                        " template")
6890
        self.op.snode = None
6891

    
6892
    self._cds = _GetClusterDomainSecret()
6893

    
6894
    if self.op.mode == constants.INSTANCE_IMPORT:
6895
      # On import force_variant must be True, because if we forced it at
6896
      # initial install, our only chance when importing it back is that it
6897
      # works again!
6898
      self.op.force_variant = True
6899

    
6900
      if self.op.no_install:
6901
        self.LogInfo("No-installation mode has no effect during import")
6902

    
6903
    elif self.op.mode == constants.INSTANCE_CREATE:
6904
      if self.op.os_type is None:
6905
        raise errors.OpPrereqError("No guest OS specified",
6906
                                   errors.ECODE_INVAL)
6907
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
6908
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6909
                                   " installation" % self.op.os_type,
6910
                                   errors.ECODE_STATE)
6911
      if self.op.disk_template is None:
6912
        raise errors.OpPrereqError("No disk template specified",
6913
                                   errors.ECODE_INVAL)
6914

    
6915
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6916
      # Check handshake to ensure both clusters have the same domain secret
6917
      src_handshake = self.op.source_handshake
6918
      if not src_handshake:
6919
        raise errors.OpPrereqError("Missing source handshake",
6920
                                   errors.ECODE_INVAL)
6921

    
6922
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6923
                                                           src_handshake)
6924
      if errmsg:
6925
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6926
                                   errors.ECODE_INVAL)
6927

    
6928
      # Load and check source CA
6929
      self.source_x509_ca_pem = self.op.source_x509_ca
6930
      if not self.source_x509_ca_pem:
6931
        raise errors.OpPrereqError("Missing source X509 CA",
6932
                                   errors.ECODE_INVAL)
6933

    
6934
      try:
6935
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6936
                                                    self._cds)
6937
      except OpenSSL.crypto.Error, err:
6938
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6939
                                   (err, ), errors.ECODE_INVAL)
6940

    
6941
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6942
      if errcode is not None:
6943
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6944
                                   errors.ECODE_INVAL)
6945

    
6946
      self.source_x509_ca = cert
6947

    
6948
      src_instance_name = self.op.source_instance_name
6949
      if not src_instance_name:
6950
        raise errors.OpPrereqError("Missing source instance name",
6951
                                   errors.ECODE_INVAL)
6952

    
6953
      self.source_instance_name = \
6954
          netutils.GetHostname(name=src_instance_name).name
6955

    
6956
    else:
6957
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6958
                                 self.op.mode, errors.ECODE_INVAL)
6959

    
6960
  def ExpandNames(self):
6961
    """ExpandNames for CreateInstance.
6962

6963
    Figure out the right locks for instance creation.
6964

6965
    """
6966
    self.needed_locks = {}
6967

    
6968
    instance_name = self.op.instance_name
6969
    # this is just a preventive check, but someone might still add this
6970
    # instance in the meantime, and creation will fail at lock-add time
6971
    if instance_name in self.cfg.GetInstanceList():
6972
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6973
                                 instance_name, errors.ECODE_EXISTS)
6974

    
6975
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6976

    
6977
    if self.op.iallocator:
6978
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6979
    else:
6980
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6981
      nodelist = [self.op.pnode]
6982
      if self.op.snode is not None:
6983
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6984
        nodelist.append(self.op.snode)
6985
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6986

    
6987
    # in case of import lock the source node too
6988
    if self.op.mode == constants.INSTANCE_IMPORT:
6989
      src_node = self.op.src_node
6990
      src_path = self.op.src_path
6991

    
6992
      if src_path is None:
6993
        self.op.src_path = src_path = self.op.instance_name
6994

    
6995
      if src_node is None:
6996
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6997
        self.op.src_node = None
6998
        if os.path.isabs(src_path):
6999
          raise errors.OpPrereqError("Importing an instance from an absolute"
7000
                                     " path requires a source node option.",
7001
                                     errors.ECODE_INVAL)
7002
      else:
7003
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7004
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7005
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7006
        if not os.path.isabs(src_path):
7007
          self.op.src_path = src_path = \
7008
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7009

    
7010
  def _RunAllocator(self):
7011
    """Run the allocator based on input opcode.
7012

7013
    """
7014
    nics = [n.ToDict() for n in self.nics]
7015
    ial = IAllocator(self.cfg, self.rpc,
7016
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7017
                     name=self.op.instance_name,
7018
                     disk_template=self.op.disk_template,
7019
                     tags=[],
7020
                     os=self.op.os_type,
7021
                     vcpus=self.be_full[constants.BE_VCPUS],
7022
                     mem_size=self.be_full[constants.BE_MEMORY],
7023
                     disks=self.disks,
7024
                     nics=nics,
7025
                     hypervisor=self.op.hypervisor,
7026
                     )
7027

    
7028
    ial.Run(self.op.iallocator)
7029

    
7030
    if not ial.success:
7031
      raise errors.OpPrereqError("Can't compute nodes using"
7032
                                 " iallocator '%s': %s" %
7033
                                 (self.op.iallocator, ial.info),
7034
                                 errors.ECODE_NORES)
7035
    if len(ial.result) != ial.required_nodes:
7036
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7037
                                 " of nodes (%s), required %s" %
7038
                                 (self.op.iallocator, len(ial.result),
7039
                                  ial.required_nodes), errors.ECODE_FAULT)
7040
    self.op.pnode = ial.result[0]
7041
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7042
                 self.op.instance_name, self.op.iallocator,
7043
                 utils.CommaJoin(ial.result))
7044
    if ial.required_nodes == 2:
7045
      self.op.snode = ial.result[1]
7046

    
7047
  def BuildHooksEnv(self):
7048
    """Build hooks env.
7049

7050
    This runs on master, primary and secondary nodes of the instance.
7051

7052
    """
7053
    env = {
7054
      "ADD_MODE": self.op.mode,
7055
      }
7056
    if self.op.mode == constants.INSTANCE_IMPORT:
7057
      env["SRC_NODE"] = self.op.src_node
7058
      env["SRC_PATH"] = self.op.src_path
7059
      env["SRC_IMAGES"] = self.src_images
7060

    
7061
    env.update(_BuildInstanceHookEnv(
7062
      name=self.op.instance_name,
7063
      primary_node=self.op.pnode,
7064
      secondary_nodes=self.secondaries,
7065
      status=self.op.start,
7066
      os_type=self.op.os_type,
7067
      memory=self.be_full[constants.BE_MEMORY],
7068
      vcpus=self.be_full[constants.BE_VCPUS],
7069
      nics=_NICListToTuple(self, self.nics),
7070
      disk_template=self.op.disk_template,
7071
      disks=[(d["size"], d["mode"]) for d in self.disks],
7072
      bep=self.be_full,
7073
      hvp=self.hv_full,
7074
      hypervisor_name=self.op.hypervisor,
7075
    ))
7076

    
7077
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
7078
          self.secondaries)
7079
    return env, nl, nl
7080

    
7081
  def _ReadExportInfo(self):
7082
    """Reads the export information from disk.
7083

7084
    It will override the opcode source node and path with the actual
7085
    information, if these two were not specified before.
7086

7087
    @return: the export information
7088

7089
    """
7090
    assert self.op.mode == constants.INSTANCE_IMPORT
7091

    
7092
    src_node = self.op.src_node
7093
    src_path = self.op.src_path
7094

    
7095
    if src_node is None:
7096
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
7097
      exp_list = self.rpc.call_export_list(locked_nodes)
7098
      found = False
7099
      for node in exp_list:
7100
        if exp_list[node].fail_msg:
7101
          continue
7102
        if src_path in exp_list[node].payload:
7103
          found = True
7104
          self.op.src_node = src_node = node
7105
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7106
                                                       src_path)
7107
          break
7108
      if not found:
7109
        raise errors.OpPrereqError("No export found for relative path %s" %
7110
                                    src_path, errors.ECODE_INVAL)
7111

    
7112
    _CheckNodeOnline(self, src_node)
7113
    result = self.rpc.call_export_info(src_node, src_path)
7114
    result.Raise("No export or invalid export found in dir %s" % src_path)
7115

    
7116
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7117
    if not export_info.has_section(constants.INISECT_EXP):
7118
      raise errors.ProgrammerError("Corrupted export config",
7119
                                   errors.ECODE_ENVIRON)
7120

    
7121
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7122
    if (int(ei_version) != constants.EXPORT_VERSION):
7123
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7124
                                 (ei_version, constants.EXPORT_VERSION),
7125
                                 errors.ECODE_ENVIRON)
7126
    return export_info
7127

    
7128
  def _ReadExportParams(self, einfo):
7129
    """Use export parameters as defaults.
7130

7131
    In case the opcode doesn't specify (as in override) some instance
7132
    parameters, then try to use them from the export information, if
7133
    that declares them.
7134

7135
    """
7136
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7137

    
7138
    if self.op.disk_template is None:
7139
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7140
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7141
                                          "disk_template")
7142
      else:
7143
        raise errors.OpPrereqError("No disk template specified and the export"
7144
                                   " is missing the disk_template information",
7145
                                   errors.ECODE_INVAL)
7146

    
7147
    if not self.op.disks:
7148
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7149
        disks = []
7150
        # TODO: import the disk iv_name too
7151
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7152
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7153
          disks.append({"size": disk_sz})
7154
        self.op.disks = disks
7155
      else:
7156
        raise errors.OpPrereqError("No disk info specified and the export"
7157
                                   " is missing the disk information",
7158
                                   errors.ECODE_INVAL)
7159

    
7160
    if (not self.op.nics and
7161
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7162
      nics = []
7163
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7164
        ndict = {}
7165
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7166
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7167
          ndict[name] = v
7168
        nics.append(ndict)
7169
      self.op.nics = nics
7170

    
7171
    if (self.op.hypervisor is None and
7172
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7173
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7174
    if einfo.has_section(constants.INISECT_HYP):
7175
      # use the export parameters but do not override the ones
7176
      # specified by the user
7177
      for name, value in einfo.items(constants.INISECT_HYP):
7178
        if name not in self.op.hvparams:
7179
          self.op.hvparams[name] = value
7180

    
7181
    if einfo.has_section(constants.INISECT_BEP):
7182
      # use the parameters, without overriding
7183
      for name, value in einfo.items(constants.INISECT_BEP):
7184
        if name not in self.op.beparams:
7185
          self.op.beparams[name] = value
7186
    else:
7187
      # try to read the parameters old style, from the main section
7188
      for name in constants.BES_PARAMETERS:
7189
        if (name not in self.op.beparams and
7190
            einfo.has_option(constants.INISECT_INS, name)):
7191
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7192

    
7193
    if einfo.has_section(constants.INISECT_OSP):
7194
      # use the parameters, without overriding
7195
      for name, value in einfo.items(constants.INISECT_OSP):
7196
        if name not in self.op.osparams:
7197
          self.op.osparams[name] = value
7198

    
7199
  def _RevertToDefaults(self, cluster):
7200
    """Revert the instance parameters to the default values.
7201

7202
    """
7203
    # hvparams
7204
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
7205
    for name in self.op.hvparams.keys():
7206
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
7207
        del self.op.hvparams[name]
7208
    # beparams
7209
    be_defs = cluster.SimpleFillBE({})
7210
    for name in self.op.beparams.keys():
7211
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
7212
        del self.op.beparams[name]
7213
    # nic params
7214
    nic_defs = cluster.SimpleFillNIC({})
7215
    for nic in self.op.nics:
7216
      for name in constants.NICS_PARAMETERS:
7217
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
7218
          del nic[name]
7219
    # osparams
7220
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
7221
    for name in self.op.osparams.keys():
7222
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
7223
        del self.op.osparams[name]
7224

    
7225
  def CheckPrereq(self):
7226
    """Check prerequisites.
7227

7228
    """
7229
    if self.op.mode == constants.INSTANCE_IMPORT:
7230
      export_info = self._ReadExportInfo()
7231
      self._ReadExportParams(export_info)
7232

    
7233
    if (not self.cfg.GetVGName() and
7234
        self.op.disk_template not in constants.DTS_NOT_LVM):
7235
      raise errors.OpPrereqError("Cluster does not support lvm-based"
7236
                                 " instances", errors.ECODE_STATE)
7237

    
7238
    if self.op.hypervisor is None:
7239
      self.op.hypervisor = self.cfg.GetHypervisorType()
7240

    
7241
    cluster = self.cfg.GetClusterInfo()
7242
    enabled_hvs = cluster.enabled_hypervisors
7243
    if self.op.hypervisor not in enabled_hvs:
7244
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7245
                                 " cluster (%s)" % (self.op.hypervisor,
7246
                                  ",".join(enabled_hvs)),
7247
                                 errors.ECODE_STATE)
7248

    
7249
    # check hypervisor parameter syntax (locally)
7250
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7251
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7252
                                      self.op.hvparams)
7253
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7254
    hv_type.CheckParameterSyntax(filled_hvp)
7255
    self.hv_full = filled_hvp
7256
    # check that we don't specify global parameters on an instance
7257
    _CheckGlobalHvParams(self.op.hvparams)
7258

    
7259
    # fill and remember the beparams dict
7260
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7261
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7262

    
7263
    # build os parameters
7264
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7265

    
7266
    # now that hvp/bep are in final format, let's reset to defaults,
7267
    # if told to do so
7268
    if self.op.identify_defaults:
7269
      self._RevertToDefaults(cluster)
7270

    
7271
    # NIC buildup
7272
    self.nics = []
7273
    for idx, nic in enumerate(self.op.nics):
7274
      nic_mode_req = nic.get("mode", None)
7275
      nic_mode = nic_mode_req
7276
      if nic_mode is None:
7277
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7278

    
7279
      # in routed mode, for the first nic, the default ip is 'auto'
7280
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7281
        default_ip_mode = constants.VALUE_AUTO
7282
      else:
7283
        default_ip_mode = constants.VALUE_NONE
7284

    
7285
      # ip validity checks
7286
      ip = nic.get("ip", default_ip_mode)
7287
      if ip is None or ip.lower() == constants.VALUE_NONE:
7288
        nic_ip = None
7289
      elif ip.lower() == constants.VALUE_AUTO:
7290
        if not self.op.name_check:
7291
          raise errors.OpPrereqError("IP address set to auto but name checks"
7292
                                     " have been skipped",
7293
                                     errors.ECODE_INVAL)
7294
        nic_ip = self.hostname1.ip
7295
      else:
7296
        if not netutils.IPAddress.IsValid(ip):
7297
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
7298
                                     errors.ECODE_INVAL)
7299
        nic_ip = ip
7300

    
7301
      # TODO: check the ip address for uniqueness
7302
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7303
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7304
                                   errors.ECODE_INVAL)
7305

    
7306
      # MAC address verification
7307
      mac = nic.get("mac", constants.VALUE_AUTO)
7308
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7309
        mac = utils.NormalizeAndValidateMac(mac)
7310

    
7311
        try:
7312
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7313
        except errors.ReservationError:
7314
          raise errors.OpPrereqError("MAC address %s already in use"
7315
                                     " in cluster" % mac,
7316
                                     errors.ECODE_NOTUNIQUE)
7317

    
7318
      # bridge verification
7319
      bridge = nic.get("bridge", None)
7320
      link = nic.get("link", None)
7321
      if bridge and link:
7322
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7323
                                   " at the same time", errors.ECODE_INVAL)
7324
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7325
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7326
                                   errors.ECODE_INVAL)
7327
      elif bridge:
7328
        link = bridge
7329

    
7330
      nicparams = {}
7331
      if nic_mode_req:
7332
        nicparams[constants.NIC_MODE] = nic_mode_req
7333
      if link:
7334
        nicparams[constants.NIC_LINK] = link
7335

    
7336
      check_params = cluster.SimpleFillNIC(nicparams)
7337
      objects.NIC.CheckParameterSyntax(check_params)
7338
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7339

    
7340
    # disk checks/pre-build
7341
    self.disks = []
7342
    for disk in self.op.disks:
7343
      mode = disk.get("mode", constants.DISK_RDWR)
7344
      if mode not in constants.DISK_ACCESS_SET:
7345
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7346
                                   mode, errors.ECODE_INVAL)
7347
      size = disk.get("size", None)
7348
      if size is None:
7349
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7350
      try:
7351
        size = int(size)
7352
      except (TypeError, ValueError):
7353
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7354
                                   errors.ECODE_INVAL)
7355
      vg = disk.get("vg", self.cfg.GetVGName())
7356
      new_disk = {"size": size, "mode": mode, "vg": vg}
7357
      if "adopt" in disk:
7358
        new_disk["adopt"] = disk["adopt"]
7359
      self.disks.append(new_disk)
7360

    
7361
    if self.op.mode == constants.INSTANCE_IMPORT:
7362

    
7363
      # Check that the new instance doesn't have less disks than the export
7364
      instance_disks = len(self.disks)
7365
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7366
      if instance_disks < export_disks:
7367
        raise errors.OpPrereqError("Not enough disks to import."
7368
                                   " (instance: %d, export: %d)" %
7369
                                   (instance_disks, export_disks),
7370
                                   errors.ECODE_INVAL)
7371

    
7372
      disk_images = []
7373
      for idx in range(export_disks):
7374
        option = 'disk%d_dump' % idx
7375
        if export_info.has_option(constants.INISECT_INS, option):
7376
          # FIXME: are the old os-es, disk sizes, etc. useful?
7377
          export_name = export_info.get(constants.INISECT_INS, option)
7378
          image = utils.PathJoin(self.op.src_path, export_name)
7379
          disk_images.append(image)
7380
        else:
7381
          disk_images.append(False)
7382

    
7383
      self.src_images = disk_images
7384

    
7385
      old_name = export_info.get(constants.INISECT_INS, 'name')
7386
      try:
7387
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7388
      except (TypeError, ValueError), err:
7389
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7390
                                   " an integer: %s" % str(err),
7391
                                   errors.ECODE_STATE)
7392
      if self.op.instance_name == old_name:
7393
        for idx, nic in enumerate(self.nics):
7394
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7395
            nic_mac_ini = 'nic%d_mac' % idx
7396
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7397

    
7398
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7399

    
7400
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7401
    if self.op.ip_check:
7402
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7403
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7404
                                   (self.check_ip, self.op.instance_name),
7405
                                   errors.ECODE_NOTUNIQUE)
7406

    
7407
    #### mac address generation
7408
    # By generating here the mac address both the allocator and the hooks get
7409
    # the real final mac address rather than the 'auto' or 'generate' value.
7410
    # There is a race condition between the generation and the instance object
7411
    # creation, which means that we know the mac is valid now, but we're not
7412
    # sure it will be when we actually add the instance. If things go bad
7413
    # adding the instance will abort because of a duplicate mac, and the
7414
    # creation job will fail.
7415
    for nic in self.nics:
7416
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7417
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7418

    
7419
    #### allocator run
7420

    
7421
    if self.op.iallocator is not None:
7422
      self._RunAllocator()
7423

    
7424
    #### node related checks
7425

    
7426
    # check primary node
7427
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7428
    assert self.pnode is not None, \
7429
      "Cannot retrieve locked node %s" % self.op.pnode
7430
    if pnode.offline:
7431
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7432
                                 pnode.name, errors.ECODE_STATE)
7433
    if pnode.drained:
7434
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7435
                                 pnode.name, errors.ECODE_STATE)
7436
    if not pnode.vm_capable:
7437
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
7438
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
7439

    
7440
    self.secondaries = []
7441

    
7442
    # mirror node verification
7443
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7444
      if self.op.snode == pnode.name:
7445
        raise errors.OpPrereqError("The secondary node cannot be the"
7446
                                   " primary node.", errors.ECODE_INVAL)
7447
      _CheckNodeOnline(self, self.op.snode)
7448
      _CheckNodeNotDrained(self, self.op.snode)
7449
      _CheckNodeVmCapable(self, self.op.snode)
7450
      self.secondaries.append(self.op.snode)
7451

    
7452
    nodenames = [pnode.name] + self.secondaries
7453

    
7454
    if not self.adopt_disks:
7455
      # Check lv size requirements, if not adopting
7456
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
7457
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
7458

    
7459
    else: # instead, we must check the adoption data
7460
      all_lvs = set([i["vg"] + "/" + i["adopt"] for i in self.disks])
7461
      if len(all_lvs) != len(self.disks):
7462
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7463
                                   errors.ECODE_INVAL)
7464
      for lv_name in all_lvs:
7465
        try:
7466
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
7467
          # to ReserveLV uses the same syntax
7468
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7469
        except errors.ReservationError:
7470
          raise errors.OpPrereqError("LV named %s used by another instance" %
7471
                                     lv_name, errors.ECODE_NOTUNIQUE)
7472

    
7473
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
7474
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
7475

    
7476
      node_lvs = self.rpc.call_lv_list([pnode.name],
7477
                                       vg_names.payload.keys())[pnode.name]
7478
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7479
      node_lvs = node_lvs.payload
7480

    
7481
      delta = all_lvs.difference(node_lvs.keys())
7482
      if delta:
7483
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7484
                                   utils.CommaJoin(delta),
7485
                                   errors.ECODE_INVAL)
7486
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7487
      if online_lvs:
7488
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7489
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7490
                                   errors.ECODE_STATE)
7491
      # update the size of disk based on what is found
7492
      for dsk in self.disks:
7493
        dsk["size"] = int(float(node_lvs[dsk["vg"] + "/" + dsk["adopt"]][0]))
7494

    
7495
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7496

    
7497
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7498
    # check OS parameters (remotely)
7499
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7500

    
7501
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7502

    
7503
    # memory check on primary node
7504
    if self.op.start:
7505
      _CheckNodeFreeMemory(self, self.pnode.name,
7506
                           "creating instance %s" % self.op.instance_name,
7507
                           self.be_full[constants.BE_MEMORY],
7508
                           self.op.hypervisor)
7509

    
7510
    self.dry_run_result = list(nodenames)
7511

    
7512
  def Exec(self, feedback_fn):
7513
    """Create and add the instance to the cluster.
7514

7515
    """
7516
    instance = self.op.instance_name
7517
    pnode_name = self.pnode.name
7518

    
7519
    ht_kind = self.op.hypervisor
7520
    if ht_kind in constants.HTS_REQ_PORT:
7521
      network_port = self.cfg.AllocatePort()
7522
    else:
7523
      network_port = None
7524

    
7525
    if constants.ENABLE_FILE_STORAGE:
7526
      # this is needed because os.path.join does not accept None arguments
7527
      if self.op.file_storage_dir is None:
7528
        string_file_storage_dir = ""
7529
      else:
7530
        string_file_storage_dir = self.op.file_storage_dir
7531

    
7532
      # build the full file storage dir path
7533
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7534
                                        string_file_storage_dir, instance)
7535
    else:
7536
      file_storage_dir = ""
7537

    
7538
    disks = _GenerateDiskTemplate(self,
7539
                                  self.op.disk_template,
7540
                                  instance, pnode_name,
7541
                                  self.secondaries,
7542
                                  self.disks,
7543
                                  file_storage_dir,
7544
                                  self.op.file_driver,
7545
                                  0,
7546
                                  feedback_fn)
7547

    
7548
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7549
                            primary_node=pnode_name,
7550
                            nics=self.nics, disks=disks,
7551
                            disk_template=self.op.disk_template,
7552
                            admin_up=False,
7553
                            network_port=network_port,
7554
                            beparams=self.op.beparams,
7555
                            hvparams=self.op.hvparams,
7556
                            hypervisor=self.op.hypervisor,
7557
                            osparams=self.op.osparams,
7558
                            )
7559

    
7560
    if self.adopt_disks:
7561
      # rename LVs to the newly-generated names; we need to construct
7562
      # 'fake' LV disks with the old data, plus the new unique_id
7563
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7564
      rename_to = []
7565
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7566
        rename_to.append(t_dsk.logical_id)
7567
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7568
        self.cfg.SetDiskID(t_dsk, pnode_name)
7569
      result = self.rpc.call_blockdev_rename(pnode_name,
7570
                                             zip(tmp_disks, rename_to))
7571
      result.Raise("Failed to rename adoped LVs")
7572
    else:
7573
      feedback_fn("* creating instance disks...")
7574
      try:
7575
        _CreateDisks(self, iobj)
7576
      except errors.OpExecError:
7577
        self.LogWarning("Device creation failed, reverting...")
7578
        try:
7579
          _RemoveDisks(self, iobj)
7580
        finally:
7581
          self.cfg.ReleaseDRBDMinors(instance)
7582
          raise
7583

    
7584
      if self.cfg.GetClusterInfo().prealloc_wipe_disks:
7585
        feedback_fn("* wiping instance disks...")
7586
        try:
7587
          _WipeDisks(self, iobj)
7588
        except errors.OpExecError:
7589
          self.LogWarning("Device wiping failed, reverting...")
7590
          try:
7591
            _RemoveDisks(self, iobj)
7592
          finally:
7593
            self.cfg.ReleaseDRBDMinors(instance)
7594
            raise
7595

    
7596
    feedback_fn("adding instance %s to cluster config" % instance)
7597

    
7598
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7599

    
7600
    # Declare that we don't want to remove the instance lock anymore, as we've
7601
    # added the instance to the config
7602
    del self.remove_locks[locking.LEVEL_INSTANCE]
7603
    # Unlock all the nodes
7604
    if self.op.mode == constants.INSTANCE_IMPORT:
7605
      nodes_keep = [self.op.src_node]
7606
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7607
                       if node != self.op.src_node]
7608
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7609
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7610
    else:
7611
      self.context.glm.release(locking.LEVEL_NODE)
7612
      del self.acquired_locks[locking.LEVEL_NODE]
7613

    
7614
    if self.op.wait_for_sync:
7615
      disk_abort = not _WaitForSync(self, iobj)
7616
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7617
      # make sure the disks are not degraded (still sync-ing is ok)
7618
      time.sleep(15)
7619
      feedback_fn("* checking mirrors status")
7620
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7621
    else:
7622
      disk_abort = False
7623

    
7624
    if disk_abort:
7625
      _RemoveDisks(self, iobj)
7626
      self.cfg.RemoveInstance(iobj.name)
7627
      # Make sure the instance lock gets removed
7628
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7629
      raise errors.OpExecError("There are some degraded disks for"
7630
                               " this instance")
7631

    
7632
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7633
      if self.op.mode == constants.INSTANCE_CREATE:
7634
        if not self.op.no_install:
7635
          feedback_fn("* running the instance OS create scripts...")
7636
          # FIXME: pass debug option from opcode to backend
7637
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7638
                                                 self.op.debug_level)
7639
          result.Raise("Could not add os for instance %s"
7640
                       " on node %s" % (instance, pnode_name))
7641

    
7642
      elif self.op.mode == constants.INSTANCE_IMPORT:
7643
        feedback_fn("* running the instance OS import scripts...")
7644

    
7645
        transfers = []
7646

    
7647
        for idx, image in enumerate(self.src_images):
7648
          if not image:
7649
            continue
7650

    
7651
          # FIXME: pass debug option from opcode to backend
7652
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7653
                                             constants.IEIO_FILE, (image, ),
7654
                                             constants.IEIO_SCRIPT,
7655
                                             (iobj.disks[idx], idx),
7656
                                             None)
7657
          transfers.append(dt)
7658

    
7659
        import_result = \
7660
          masterd.instance.TransferInstanceData(self, feedback_fn,
7661
                                                self.op.src_node, pnode_name,
7662
                                                self.pnode.secondary_ip,
7663
                                                iobj, transfers)
7664
        if not compat.all(import_result):
7665
          self.LogWarning("Some disks for instance %s on node %s were not"
7666
                          " imported successfully" % (instance, pnode_name))
7667

    
7668
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7669
        feedback_fn("* preparing remote import...")
7670
        # The source cluster will stop the instance before attempting to make a
7671
        # connection. In some cases stopping an instance can take a long time,
7672
        # hence the shutdown timeout is added to the connection timeout.
7673
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
7674
                           self.op.source_shutdown_timeout)
7675
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7676

    
7677
        assert iobj.primary_node == self.pnode.name
7678
        disk_results = \
7679
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
7680
                                        self.source_x509_ca,
7681
                                        self._cds, timeouts)
7682
        if not compat.all(disk_results):
7683
          # TODO: Should the instance still be started, even if some disks
7684
          # failed to import (valid for local imports, too)?
7685
          self.LogWarning("Some disks for instance %s on node %s were not"
7686
                          " imported successfully" % (instance, pnode_name))
7687

    
7688
        # Run rename script on newly imported instance
7689
        assert iobj.name == instance
7690
        feedback_fn("Running rename script for %s" % instance)
7691
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7692
                                                   self.source_instance_name,
7693
                                                   self.op.debug_level)
7694
        if result.fail_msg:
7695
          self.LogWarning("Failed to run rename script for %s on node"
7696
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7697

    
7698
      else:
7699
        # also checked in the prereq part
7700
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7701
                                     % self.op.mode)
7702

    
7703
    if self.op.start:
7704
      iobj.admin_up = True
7705
      self.cfg.Update(iobj, feedback_fn)
7706
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7707
      feedback_fn("* starting instance...")
7708
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7709
      result.Raise("Could not start instance")
7710

    
7711
    return list(iobj.all_nodes)
7712

    
7713

    
7714
class LUInstanceConsole(NoHooksLU):
7715
  """Connect to an instance's console.
7716

7717
  This is somewhat special in that it returns the command line that
7718
  you need to run on the master node in order to connect to the
7719
  console.
7720

7721
  """
7722
  REQ_BGL = False
7723

    
7724
  def ExpandNames(self):
7725
    self._ExpandAndLockInstance()
7726

    
7727
  def CheckPrereq(self):
7728
    """Check prerequisites.
7729

7730
    This checks that the instance is in the cluster.
7731

7732
    """
7733
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7734
    assert self.instance is not None, \
7735
      "Cannot retrieve locked instance %s" % self.op.instance_name
7736
    _CheckNodeOnline(self, self.instance.primary_node)
7737

    
7738
  def Exec(self, feedback_fn):
7739
    """Connect to the console of an instance
7740

7741
    """
7742
    instance = self.instance
7743
    node = instance.primary_node
7744

    
7745
    node_insts = self.rpc.call_instance_list([node],
7746
                                             [instance.hypervisor])[node]
7747
    node_insts.Raise("Can't get node information from %s" % node)
7748

    
7749
    if instance.name not in node_insts.payload:
7750
      if instance.admin_up:
7751
        state = "ERROR_down"
7752
      else:
7753
        state = "ADMIN_down"
7754
      raise errors.OpExecError("Instance %s is not running (state %s)" %
7755
                               (instance.name, state))
7756

    
7757
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7758

    
7759
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7760
    cluster = self.cfg.GetClusterInfo()
7761
    # beparams and hvparams are passed separately, to avoid editing the
7762
    # instance and then saving the defaults in the instance itself.
7763
    hvparams = cluster.FillHV(instance)
7764
    beparams = cluster.FillBE(instance)
7765
    console = hyper.GetInstanceConsole(instance, hvparams, beparams)
7766

    
7767
    assert console.instance == instance.name
7768
    assert console.Validate()
7769

    
7770
    return console.ToDict()
7771

    
7772

    
7773
class LUInstanceReplaceDisks(LogicalUnit):
7774
  """Replace the disks of an instance.
7775

7776
  """
7777
  HPATH = "mirrors-replace"
7778
  HTYPE = constants.HTYPE_INSTANCE
7779
  REQ_BGL = False
7780

    
7781
  def CheckArguments(self):
7782
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7783
                                  self.op.iallocator)
7784

    
7785
  def ExpandNames(self):
7786
    self._ExpandAndLockInstance()
7787

    
7788
    if self.op.iallocator is not None:
7789
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7790

    
7791
    elif self.op.remote_node is not None:
7792
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7793
      self.op.remote_node = remote_node
7794

    
7795
      # Warning: do not remove the locking of the new secondary here
7796
      # unless DRBD8.AddChildren is changed to work in parallel;
7797
      # currently it doesn't since parallel invocations of
7798
      # FindUnusedMinor will conflict
7799
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7800
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7801

    
7802
    else:
7803
      self.needed_locks[locking.LEVEL_NODE] = []
7804
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7805

    
7806
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7807
                                   self.op.iallocator, self.op.remote_node,
7808
                                   self.op.disks, False, self.op.early_release)
7809

    
7810
    self.tasklets = [self.replacer]
7811

    
7812
  def DeclareLocks(self, level):
7813
    # If we're not already locking all nodes in the set we have to declare the
7814
    # instance's primary/secondary nodes.
7815
    if (level == locking.LEVEL_NODE and
7816
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7817
      self._LockInstancesNodes()
7818

    
7819
  def BuildHooksEnv(self):
7820
    """Build hooks env.
7821

7822
    This runs on the master, the primary and all the secondaries.
7823

7824
    """
7825
    instance = self.replacer.instance
7826
    env = {
7827
      "MODE": self.op.mode,
7828
      "NEW_SECONDARY": self.op.remote_node,
7829
      "OLD_SECONDARY": instance.secondary_nodes[0],
7830
      }
7831
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7832
    nl = [
7833
      self.cfg.GetMasterNode(),
7834
      instance.primary_node,
7835
      ]
7836
    if self.op.remote_node is not None:
7837
      nl.append(self.op.remote_node)
7838
    return env, nl, nl
7839

    
7840

    
7841
class TLReplaceDisks(Tasklet):
7842
  """Replaces disks for an instance.
7843

7844
  Note: Locking is not within the scope of this class.
7845

7846
  """
7847
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7848
               disks, delay_iallocator, early_release):
7849
    """Initializes this class.
7850

7851
    """
7852
    Tasklet.__init__(self, lu)
7853

    
7854
    # Parameters
7855
    self.instance_name = instance_name
7856
    self.mode = mode
7857
    self.iallocator_name = iallocator_name
7858
    self.remote_node = remote_node
7859
    self.disks = disks
7860
    self.delay_iallocator = delay_iallocator
7861
    self.early_release = early_release
7862

    
7863
    # Runtime data
7864
    self.instance = None
7865
    self.new_node = None
7866
    self.target_node = None
7867
    self.other_node = None
7868
    self.remote_node_info = None
7869
    self.node_secondary_ip = None
7870

    
7871
  @staticmethod
7872
  def CheckArguments(mode, remote_node, iallocator):
7873
    """Helper function for users of this class.
7874

7875
    """
7876
    # check for valid parameter combination
7877
    if mode == constants.REPLACE_DISK_CHG:
7878
      if remote_node is None and iallocator is None:
7879
        raise errors.OpPrereqError("When changing the secondary either an"
7880
                                   " iallocator script must be used or the"
7881
                                   " new node given", errors.ECODE_INVAL)
7882

    
7883
      if remote_node is not None and iallocator is not None:
7884
        raise errors.OpPrereqError("Give either the iallocator or the new"
7885
                                   " secondary, not both", errors.ECODE_INVAL)
7886

    
7887
    elif remote_node is not None or iallocator is not None:
7888
      # Not replacing the secondary
7889
      raise errors.OpPrereqError("The iallocator and new node options can"
7890
                                 " only be used when changing the"
7891
                                 " secondary node", errors.ECODE_INVAL)
7892

    
7893
  @staticmethod
7894
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7895
    """Compute a new secondary node using an IAllocator.
7896

7897
    """
7898
    ial = IAllocator(lu.cfg, lu.rpc,
7899
                     mode=constants.IALLOCATOR_MODE_RELOC,
7900
                     name=instance_name,
7901
                     relocate_from=relocate_from)
7902

    
7903
    ial.Run(iallocator_name)
7904

    
7905
    if not ial.success:
7906
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7907
                                 " %s" % (iallocator_name, ial.info),
7908
                                 errors.ECODE_NORES)
7909

    
7910
    if len(ial.result) != ial.required_nodes:
7911
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7912
                                 " of nodes (%s), required %s" %
7913
                                 (iallocator_name,
7914
                                  len(ial.result), ial.required_nodes),
7915
                                 errors.ECODE_FAULT)
7916

    
7917
    remote_node_name = ial.result[0]
7918

    
7919
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7920
               instance_name, remote_node_name)
7921

    
7922
    return remote_node_name
7923

    
7924
  def _FindFaultyDisks(self, node_name):
7925
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7926
                                    node_name, True)
7927

    
7928
  def CheckPrereq(self):
7929
    """Check prerequisites.
7930

7931
    This checks that the instance is in the cluster.
7932

7933
    """
7934
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7935
    assert instance is not None, \
7936
      "Cannot retrieve locked instance %s" % self.instance_name
7937

    
7938
    if instance.disk_template != constants.DT_DRBD8:
7939
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7940
                                 " instances", errors.ECODE_INVAL)
7941

    
7942
    if len(instance.secondary_nodes) != 1:
7943
      raise errors.OpPrereqError("The instance has a strange layout,"
7944
                                 " expected one secondary but found %d" %
7945
                                 len(instance.secondary_nodes),
7946
                                 errors.ECODE_FAULT)
7947

    
7948
    if not self.delay_iallocator:
7949
      self._CheckPrereq2()
7950

    
7951
  def _CheckPrereq2(self):
7952
    """Check prerequisites, second part.
7953

7954
    This function should always be part of CheckPrereq. It was separated and is
7955
    now called from Exec because during node evacuation iallocator was only
7956
    called with an unmodified cluster model, not taking planned changes into
7957
    account.
7958

7959
    """
7960
    instance = self.instance
7961
    secondary_node = instance.secondary_nodes[0]
7962

    
7963
    if self.iallocator_name is None:
7964
      remote_node = self.remote_node
7965
    else:
7966
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7967
                                       instance.name, instance.secondary_nodes)
7968

    
7969
    if remote_node is not None:
7970
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7971
      assert self.remote_node_info is not None, \
7972
        "Cannot retrieve locked node %s" % remote_node
7973
    else:
7974
      self.remote_node_info = None
7975

    
7976
    if remote_node == self.instance.primary_node:
7977
      raise errors.OpPrereqError("The specified node is the primary node of"
7978
                                 " the instance.", errors.ECODE_INVAL)
7979

    
7980
    if remote_node == secondary_node:
7981
      raise errors.OpPrereqError("The specified node is already the"
7982
                                 " secondary node of the instance.",
7983
                                 errors.ECODE_INVAL)
7984

    
7985
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7986
                                    constants.REPLACE_DISK_CHG):
7987
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7988
                                 errors.ECODE_INVAL)
7989

    
7990
    if self.mode == constants.REPLACE_DISK_AUTO:
7991
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7992
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7993

    
7994
      if faulty_primary and faulty_secondary:
7995
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7996
                                   " one node and can not be repaired"
7997
                                   " automatically" % self.instance_name,
7998
                                   errors.ECODE_STATE)
7999

    
8000
      if faulty_primary:
8001
        self.disks = faulty_primary
8002
        self.target_node = instance.primary_node
8003
        self.other_node = secondary_node
8004
        check_nodes = [self.target_node, self.other_node]
8005
      elif faulty_secondary:
8006
        self.disks = faulty_secondary
8007
        self.target_node = secondary_node
8008
        self.other_node = instance.primary_node
8009
        check_nodes = [self.target_node, self.other_node]
8010
      else:
8011
        self.disks = []
8012
        check_nodes = []
8013

    
8014
    else:
8015
      # Non-automatic modes
8016
      if self.mode == constants.REPLACE_DISK_PRI:
8017
        self.target_node = instance.primary_node
8018
        self.other_node = secondary_node
8019
        check_nodes = [self.target_node, self.other_node]
8020

    
8021
      elif self.mode == constants.REPLACE_DISK_SEC:
8022
        self.target_node = secondary_node
8023
        self.other_node = instance.primary_node
8024
        check_nodes = [self.target_node, self.other_node]
8025

    
8026
      elif self.mode == constants.REPLACE_DISK_CHG:
8027
        self.new_node = remote_node
8028
        self.other_node = instance.primary_node
8029
        self.target_node = secondary_node
8030
        check_nodes = [self.new_node, self.other_node]
8031

    
8032
        _CheckNodeNotDrained(self.lu, remote_node)
8033
        _CheckNodeVmCapable(self.lu, remote_node)
8034

    
8035
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8036
        assert old_node_info is not None
8037
        if old_node_info.offline and not self.early_release:
8038
          # doesn't make sense to delay the release
8039
          self.early_release = True
8040
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8041
                          " early-release mode", secondary_node)
8042

    
8043
      else:
8044
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8045
                                     self.mode)
8046

    
8047
      # If not specified all disks should be replaced
8048
      if not self.disks:
8049
        self.disks = range(len(self.instance.disks))
8050

    
8051
    for node in check_nodes:
8052
      _CheckNodeOnline(self.lu, node)
8053

    
8054
    # Check whether disks are valid
8055
    for disk_idx in self.disks:
8056
      instance.FindDisk(disk_idx)
8057

    
8058
    # Get secondary node IP addresses
8059
    node_2nd_ip = {}
8060

    
8061
    for node_name in [self.target_node, self.other_node, self.new_node]:
8062
      if node_name is not None:
8063
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
8064

    
8065
    self.node_secondary_ip = node_2nd_ip
8066

    
8067
  def Exec(self, feedback_fn):
8068
    """Execute disk replacement.
8069

8070
    This dispatches the disk replacement to the appropriate handler.
8071

8072
    """
8073
    if self.delay_iallocator:
8074
      self._CheckPrereq2()
8075

    
8076
    if not self.disks:
8077
      feedback_fn("No disks need replacement")
8078
      return
8079

    
8080
    feedback_fn("Replacing disk(s) %s for %s" %
8081
                (utils.CommaJoin(self.disks), self.instance.name))
8082

    
8083
    activate_disks = (not self.instance.admin_up)
8084

    
8085
    # Activate the instance disks if we're replacing them on a down instance
8086
    if activate_disks:
8087
      _StartInstanceDisks(self.lu, self.instance, True)
8088

    
8089
    try:
8090
      # Should we replace the secondary node?
8091
      if self.new_node is not None:
8092
        fn = self._ExecDrbd8Secondary
8093
      else:
8094
        fn = self._ExecDrbd8DiskOnly
8095

    
8096
      return fn(feedback_fn)
8097

    
8098
    finally:
8099
      # Deactivate the instance disks if we're replacing them on a
8100
      # down instance
8101
      if activate_disks:
8102
        _SafeShutdownInstanceDisks(self.lu, self.instance)
8103

    
8104
  def _CheckVolumeGroup(self, nodes):
8105
    self.lu.LogInfo("Checking volume groups")
8106

    
8107
    vgname = self.cfg.GetVGName()
8108

    
8109
    # Make sure volume group exists on all involved nodes
8110
    results = self.rpc.call_vg_list(nodes)
8111
    if not results:
8112
      raise errors.OpExecError("Can't list volume groups on the nodes")
8113

    
8114
    for node in nodes:
8115
      res = results[node]
8116
      res.Raise("Error checking node %s" % node)
8117
      if vgname not in res.payload:
8118
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
8119
                                 (vgname, node))
8120

    
8121
  def _CheckDisksExistence(self, nodes):
8122
    # Check disk existence
8123
    for idx, dev in enumerate(self.instance.disks):
8124
      if idx not in self.disks:
8125
        continue
8126

    
8127
      for node in nodes:
8128
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
8129
        self.cfg.SetDiskID(dev, node)
8130

    
8131
        result = self.rpc.call_blockdev_find(node, dev)
8132

    
8133
        msg = result.fail_msg
8134
        if msg or not result.payload:
8135
          if not msg:
8136
            msg = "disk not found"
8137
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
8138
                                   (idx, node, msg))
8139

    
8140
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
8141
    for idx, dev in enumerate(self.instance.disks):
8142
      if idx not in self.disks:
8143
        continue
8144

    
8145
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
8146
                      (idx, node_name))
8147

    
8148
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
8149
                                   ldisk=ldisk):
8150
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
8151
                                 " replace disks for instance %s" %
8152
                                 (node_name, self.instance.name))
8153

    
8154
  def _CreateNewStorage(self, node_name):
8155
    vgname = self.cfg.GetVGName()
8156
    iv_names = {}
8157

    
8158
    for idx, dev in enumerate(self.instance.disks):
8159
      if idx not in self.disks:
8160
        continue
8161

    
8162
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
8163

    
8164
      self.cfg.SetDiskID(dev, node_name)
8165

    
8166
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
8167
      names = _GenerateUniqueNames(self.lu, lv_names)
8168

    
8169
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
8170
                             logical_id=(vgname, names[0]))
8171
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
8172
                             logical_id=(vgname, names[1]))
8173

    
8174
      new_lvs = [lv_data, lv_meta]
8175
      old_lvs = dev.children
8176
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
8177

    
8178
      # we pass force_create=True to force the LVM creation
8179
      for new_lv in new_lvs:
8180
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
8181
                        _GetInstanceInfoText(self.instance), False)
8182

    
8183
    return iv_names
8184

    
8185
  def _CheckDevices(self, node_name, iv_names):
8186
    for name, (dev, _, _) in iv_names.iteritems():
8187
      self.cfg.SetDiskID(dev, node_name)
8188

    
8189
      result = self.rpc.call_blockdev_find(node_name, dev)
8190

    
8191
      msg = result.fail_msg
8192
      if msg or not result.payload:
8193
        if not msg:
8194
          msg = "disk not found"
8195
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
8196
                                 (name, msg))
8197

    
8198
      if result.payload.is_degraded:
8199
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
8200

    
8201
  def _RemoveOldStorage(self, node_name, iv_names):
8202
    for name, (_, old_lvs, _) in iv_names.iteritems():
8203
      self.lu.LogInfo("Remove logical volumes for %s" % name)
8204

    
8205
      for lv in old_lvs:
8206
        self.cfg.SetDiskID(lv, node_name)
8207

    
8208
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
8209
        if msg:
8210
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
8211
                             hint="remove unused LVs manually")
8212

    
8213
  def _ReleaseNodeLock(self, node_name):
8214
    """Releases the lock for a given node."""
8215
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
8216

    
8217
  def _ExecDrbd8DiskOnly(self, feedback_fn):
8218
    """Replace a disk on the primary or secondary for DRBD 8.
8219

8220
    The algorithm for replace is quite complicated:
8221

8222
      1. for each disk to be replaced:
8223

8224
        1. create new LVs on the target node with unique names
8225
        1. detach old LVs from the drbd device
8226
        1. rename old LVs to name_replaced.<time_t>
8227
        1. rename new LVs to old LVs
8228
        1. attach the new LVs (with the old names now) to the drbd device
8229

8230
      1. wait for sync across all devices
8231

8232
      1. for each modified disk:
8233

8234
        1. remove old LVs (which have the name name_replaces.<time_t>)
8235

8236
    Failures are not very well handled.
8237

8238
    """
8239
    steps_total = 6
8240

    
8241
    # Step: check device activation
8242
    self.lu.LogStep(1, steps_total, "Check device existence")
8243
    self._CheckDisksExistence([self.other_node, self.target_node])
8244
    self._CheckVolumeGroup([self.target_node, self.other_node])
8245

    
8246
    # Step: check other node consistency
8247
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8248
    self._CheckDisksConsistency(self.other_node,
8249
                                self.other_node == self.instance.primary_node,
8250
                                False)
8251

    
8252
    # Step: create new storage
8253
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8254
    iv_names = self._CreateNewStorage(self.target_node)
8255

    
8256
    # Step: for each lv, detach+rename*2+attach
8257
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8258
    for dev, old_lvs, new_lvs in iv_names.itervalues():
8259
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
8260

    
8261
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
8262
                                                     old_lvs)
8263
      result.Raise("Can't detach drbd from local storage on node"
8264
                   " %s for device %s" % (self.target_node, dev.iv_name))
8265
      #dev.children = []
8266
      #cfg.Update(instance)
8267

    
8268
      # ok, we created the new LVs, so now we know we have the needed
8269
      # storage; as such, we proceed on the target node to rename
8270
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8271
      # using the assumption that logical_id == physical_id (which in
8272
      # turn is the unique_id on that node)
8273

    
8274
      # FIXME(iustin): use a better name for the replaced LVs
8275
      temp_suffix = int(time.time())
8276
      ren_fn = lambda d, suff: (d.physical_id[0],
8277
                                d.physical_id[1] + "_replaced-%s" % suff)
8278

    
8279
      # Build the rename list based on what LVs exist on the node
8280
      rename_old_to_new = []
8281
      for to_ren in old_lvs:
8282
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8283
        if not result.fail_msg and result.payload:
8284
          # device exists
8285
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8286

    
8287
      self.lu.LogInfo("Renaming the old LVs on the target node")
8288
      result = self.rpc.call_blockdev_rename(self.target_node,
8289
                                             rename_old_to_new)
8290
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8291

    
8292
      # Now we rename the new LVs to the old LVs
8293
      self.lu.LogInfo("Renaming the new LVs on the target node")
8294
      rename_new_to_old = [(new, old.physical_id)
8295
                           for old, new in zip(old_lvs, new_lvs)]
8296
      result = self.rpc.call_blockdev_rename(self.target_node,
8297
                                             rename_new_to_old)
8298
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8299

    
8300
      for old, new in zip(old_lvs, new_lvs):
8301
        new.logical_id = old.logical_id
8302
        self.cfg.SetDiskID(new, self.target_node)
8303

    
8304
      for disk in old_lvs:
8305
        disk.logical_id = ren_fn(disk, temp_suffix)
8306
        self.cfg.SetDiskID(disk, self.target_node)
8307

    
8308
      # Now that the new lvs have the old name, we can add them to the device
8309
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8310
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8311
                                                  new_lvs)
8312
      msg = result.fail_msg
8313
      if msg:
8314
        for new_lv in new_lvs:
8315
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8316
                                               new_lv).fail_msg
8317
          if msg2:
8318
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8319
                               hint=("cleanup manually the unused logical"
8320
                                     "volumes"))
8321
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8322

    
8323
      dev.children = new_lvs
8324

    
8325
      self.cfg.Update(self.instance, feedback_fn)
8326

    
8327
    cstep = 5
8328
    if self.early_release:
8329
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8330
      cstep += 1
8331
      self._RemoveOldStorage(self.target_node, iv_names)
8332
      # WARNING: we release both node locks here, do not do other RPCs
8333
      # than WaitForSync to the primary node
8334
      self._ReleaseNodeLock([self.target_node, self.other_node])
8335

    
8336
    # Wait for sync
8337
    # This can fail as the old devices are degraded and _WaitForSync
8338
    # does a combined result over all disks, so we don't check its return value
8339
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8340
    cstep += 1
8341
    _WaitForSync(self.lu, self.instance)
8342

    
8343
    # Check all devices manually
8344
    self._CheckDevices(self.instance.primary_node, iv_names)
8345

    
8346
    # Step: remove old storage
8347
    if not self.early_release:
8348
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8349
      cstep += 1
8350
      self._RemoveOldStorage(self.target_node, iv_names)
8351

    
8352
  def _ExecDrbd8Secondary(self, feedback_fn):
8353
    """Replace the secondary node for DRBD 8.
8354

8355
    The algorithm for replace is quite complicated:
8356
      - for all disks of the instance:
8357
        - create new LVs on the new node with same names
8358
        - shutdown the drbd device on the old secondary
8359
        - disconnect the drbd network on the primary
8360
        - create the drbd device on the new secondary
8361
        - network attach the drbd on the primary, using an artifice:
8362
          the drbd code for Attach() will connect to the network if it
8363
          finds a device which is connected to the good local disks but
8364
          not network enabled
8365
      - wait for sync across all devices
8366
      - remove all disks from the old secondary
8367

8368
    Failures are not very well handled.
8369

8370
    """
8371
    steps_total = 6
8372

    
8373
    # Step: check device activation
8374
    self.lu.LogStep(1, steps_total, "Check device existence")
8375
    self._CheckDisksExistence([self.instance.primary_node])
8376
    self._CheckVolumeGroup([self.instance.primary_node])
8377

    
8378
    # Step: check other node consistency
8379
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8380
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8381

    
8382
    # Step: create new storage
8383
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8384
    for idx, dev in enumerate(self.instance.disks):
8385
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8386
                      (self.new_node, idx))
8387
      # we pass force_create=True to force LVM creation
8388
      for new_lv in dev.children:
8389
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8390
                        _GetInstanceInfoText(self.instance), False)
8391

    
8392
    # Step 4: dbrd minors and drbd setups changes
8393
    # after this, we must manually remove the drbd minors on both the
8394
    # error and the success paths
8395
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8396
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8397
                                         for dev in self.instance.disks],
8398
                                        self.instance.name)
8399
    logging.debug("Allocated minors %r", minors)
8400

    
8401
    iv_names = {}
8402
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8403
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8404
                      (self.new_node, idx))
8405
      # create new devices on new_node; note that we create two IDs:
8406
      # one without port, so the drbd will be activated without
8407
      # networking information on the new node at this stage, and one
8408
      # with network, for the latter activation in step 4
8409
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8410
      if self.instance.primary_node == o_node1:
8411
        p_minor = o_minor1
8412
      else:
8413
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8414
        p_minor = o_minor2
8415

    
8416
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8417
                      p_minor, new_minor, o_secret)
8418
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8419
                    p_minor, new_minor, o_secret)
8420

    
8421
      iv_names[idx] = (dev, dev.children, new_net_id)
8422
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8423
                    new_net_id)
8424
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8425
                              logical_id=new_alone_id,
8426
                              children=dev.children,
8427
                              size=dev.size)
8428
      try:
8429
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8430
                              _GetInstanceInfoText(self.instance), False)
8431
      except errors.GenericError:
8432
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8433
        raise
8434

    
8435
    # We have new devices, shutdown the drbd on the old secondary
8436
    for idx, dev in enumerate(self.instance.disks):
8437
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8438
      self.cfg.SetDiskID(dev, self.target_node)
8439
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8440
      if msg:
8441
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8442
                           "node: %s" % (idx, msg),
8443
                           hint=("Please cleanup this device manually as"
8444
                                 " soon as possible"))
8445

    
8446
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8447
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8448
                                               self.node_secondary_ip,
8449
                                               self.instance.disks)\
8450
                                              [self.instance.primary_node]
8451

    
8452
    msg = result.fail_msg
8453
    if msg:
8454
      # detaches didn't succeed (unlikely)
8455
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8456
      raise errors.OpExecError("Can't detach the disks from the network on"
8457
                               " old node: %s" % (msg,))
8458

    
8459
    # if we managed to detach at least one, we update all the disks of
8460
    # the instance to point to the new secondary
8461
    self.lu.LogInfo("Updating instance configuration")
8462
    for dev, _, new_logical_id in iv_names.itervalues():
8463
      dev.logical_id = new_logical_id
8464
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8465

    
8466
    self.cfg.Update(self.instance, feedback_fn)
8467

    
8468
    # and now perform the drbd attach
8469
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8470
                    " (standalone => connected)")
8471
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8472
                                            self.new_node],
8473
                                           self.node_secondary_ip,
8474
                                           self.instance.disks,
8475
                                           self.instance.name,
8476
                                           False)
8477
    for to_node, to_result in result.items():
8478
      msg = to_result.fail_msg
8479
      if msg:
8480
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8481
                           to_node, msg,
8482
                           hint=("please do a gnt-instance info to see the"
8483
                                 " status of disks"))
8484
    cstep = 5
8485
    if self.early_release:
8486
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8487
      cstep += 1
8488
      self._RemoveOldStorage(self.target_node, iv_names)
8489
      # WARNING: we release all node locks here, do not do other RPCs
8490
      # than WaitForSync to the primary node
8491
      self._ReleaseNodeLock([self.instance.primary_node,
8492
                             self.target_node,
8493
                             self.new_node])
8494

    
8495
    # Wait for sync
8496
    # This can fail as the old devices are degraded and _WaitForSync
8497
    # does a combined result over all disks, so we don't check its return value
8498
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8499
    cstep += 1
8500
    _WaitForSync(self.lu, self.instance)
8501

    
8502
    # Check all devices manually
8503
    self._CheckDevices(self.instance.primary_node, iv_names)
8504

    
8505
    # Step: remove old storage
8506
    if not self.early_release:
8507
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8508
      self._RemoveOldStorage(self.target_node, iv_names)
8509

    
8510

    
8511
class LURepairNodeStorage(NoHooksLU):
8512
  """Repairs the volume group on a node.
8513

8514
  """
8515
  REQ_BGL = False
8516

    
8517
  def CheckArguments(self):
8518
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8519

    
8520
    storage_type = self.op.storage_type
8521

    
8522
    if (constants.SO_FIX_CONSISTENCY not in
8523
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8524
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8525
                                 " repaired" % storage_type,
8526
                                 errors.ECODE_INVAL)
8527

    
8528
  def ExpandNames(self):
8529
    self.needed_locks = {
8530
      locking.LEVEL_NODE: [self.op.node_name],
8531
      }
8532

    
8533
  def _CheckFaultyDisks(self, instance, node_name):
8534
    """Ensure faulty disks abort the opcode or at least warn."""
8535
    try:
8536
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8537
                                  node_name, True):
8538
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8539
                                   " node '%s'" % (instance.name, node_name),
8540
                                   errors.ECODE_STATE)
8541
    except errors.OpPrereqError, err:
8542
      if self.op.ignore_consistency:
8543
        self.proc.LogWarning(str(err.args[0]))
8544
      else:
8545
        raise
8546

    
8547
  def CheckPrereq(self):
8548
    """Check prerequisites.
8549

8550
    """
8551
    # Check whether any instance on this node has faulty disks
8552
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8553
      if not inst.admin_up:
8554
        continue
8555
      check_nodes = set(inst.all_nodes)
8556
      check_nodes.discard(self.op.node_name)
8557
      for inst_node_name in check_nodes:
8558
        self._CheckFaultyDisks(inst, inst_node_name)
8559

    
8560
  def Exec(self, feedback_fn):
8561
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8562
                (self.op.name, self.op.node_name))
8563

    
8564
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8565
    result = self.rpc.call_storage_execute(self.op.node_name,
8566
                                           self.op.storage_type, st_args,
8567
                                           self.op.name,
8568
                                           constants.SO_FIX_CONSISTENCY)
8569
    result.Raise("Failed to repair storage unit '%s' on %s" %
8570
                 (self.op.name, self.op.node_name))
8571

    
8572

    
8573
class LUNodeEvacStrategy(NoHooksLU):
8574
  """Computes the node evacuation strategy.
8575

8576
  """
8577
  REQ_BGL = False
8578

    
8579
  def CheckArguments(self):
8580
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8581

    
8582
  def ExpandNames(self):
8583
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8584
    self.needed_locks = locks = {}
8585
    if self.op.remote_node is None:
8586
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8587
    else:
8588
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8589
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8590

    
8591
  def Exec(self, feedback_fn):
8592
    if self.op.remote_node is not None:
8593
      instances = []
8594
      for node in self.op.nodes:
8595
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8596
      result = []
8597
      for i in instances:
8598
        if i.primary_node == self.op.remote_node:
8599
          raise errors.OpPrereqError("Node %s is the primary node of"
8600
                                     " instance %s, cannot use it as"
8601
                                     " secondary" %
8602
                                     (self.op.remote_node, i.name),
8603
                                     errors.ECODE_INVAL)
8604
        result.append([i.name, self.op.remote_node])
8605
    else:
8606
      ial = IAllocator(self.cfg, self.rpc,
8607
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8608
                       evac_nodes=self.op.nodes)
8609
      ial.Run(self.op.iallocator, validate=True)
8610
      if not ial.success:
8611
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8612
                                 errors.ECODE_NORES)
8613
      result = ial.result
8614
    return result
8615

    
8616

    
8617
class LUInstanceGrowDisk(LogicalUnit):
8618
  """Grow a disk of an instance.
8619

8620
  """
8621
  HPATH = "disk-grow"
8622
  HTYPE = constants.HTYPE_INSTANCE
8623
  REQ_BGL = False
8624

    
8625
  def ExpandNames(self):
8626
    self._ExpandAndLockInstance()
8627
    self.needed_locks[locking.LEVEL_NODE] = []
8628
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8629

    
8630
  def DeclareLocks(self, level):
8631
    if level == locking.LEVEL_NODE:
8632
      self._LockInstancesNodes()
8633

    
8634
  def BuildHooksEnv(self):
8635
    """Build hooks env.
8636

8637
    This runs on the master, the primary and all the secondaries.
8638

8639
    """
8640
    env = {
8641
      "DISK": self.op.disk,
8642
      "AMOUNT": self.op.amount,
8643
      }
8644
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8645
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8646
    return env, nl, nl
8647

    
8648
  def CheckPrereq(self):
8649
    """Check prerequisites.
8650

8651
    This checks that the instance is in the cluster.
8652

8653
    """
8654
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8655
    assert instance is not None, \
8656
      "Cannot retrieve locked instance %s" % self.op.instance_name
8657
    nodenames = list(instance.all_nodes)
8658
    for node in nodenames:
8659
      _CheckNodeOnline(self, node)
8660

    
8661
    self.instance = instance
8662

    
8663
    if instance.disk_template not in constants.DTS_GROWABLE:
8664
      raise errors.OpPrereqError("Instance's disk layout does not support"
8665
                                 " growing.", errors.ECODE_INVAL)
8666

    
8667
    self.disk = instance.FindDisk(self.op.disk)
8668

    
8669
    if instance.disk_template != constants.DT_FILE:
8670
      # TODO: check the free disk space for file, when that feature
8671
      # will be supported
8672
      _CheckNodesFreeDiskPerVG(self, nodenames,
8673
                               self.disk.ComputeGrowth(self.op.amount))
8674

    
8675
  def Exec(self, feedback_fn):
8676
    """Execute disk grow.
8677

8678
    """
8679
    instance = self.instance
8680
    disk = self.disk
8681

    
8682
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8683
    if not disks_ok:
8684
      raise errors.OpExecError("Cannot activate block device to grow")
8685

    
8686
    for node in instance.all_nodes:
8687
      self.cfg.SetDiskID(disk, node)
8688
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8689
      result.Raise("Grow request failed to node %s" % node)
8690

    
8691
      # TODO: Rewrite code to work properly
8692
      # DRBD goes into sync mode for a short amount of time after executing the
8693
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8694
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8695
      # time is a work-around.
8696
      time.sleep(5)
8697

    
8698
    disk.RecordGrow(self.op.amount)
8699
    self.cfg.Update(instance, feedback_fn)
8700
    if self.op.wait_for_sync:
8701
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8702
      if disk_abort:
8703
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8704
                             " status.\nPlease check the instance.")
8705
      if not instance.admin_up:
8706
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8707
    elif not instance.admin_up:
8708
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8709
                           " not supposed to be running because no wait for"
8710
                           " sync mode was requested.")
8711

    
8712

    
8713
class LUInstanceQueryData(NoHooksLU):
8714
  """Query runtime instance data.
8715

8716
  """
8717
  REQ_BGL = False
8718

    
8719
  def ExpandNames(self):
8720
    self.needed_locks = {}
8721
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8722

    
8723
    if self.op.instances:
8724
      self.wanted_names = []
8725
      for name in self.op.instances:
8726
        full_name = _ExpandInstanceName(self.cfg, name)
8727
        self.wanted_names.append(full_name)
8728
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8729
    else:
8730
      self.wanted_names = None
8731
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8732

    
8733
    self.needed_locks[locking.LEVEL_NODE] = []
8734
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8735

    
8736
  def DeclareLocks(self, level):
8737
    if level == locking.LEVEL_NODE:
8738
      self._LockInstancesNodes()
8739

    
8740
  def CheckPrereq(self):
8741
    """Check prerequisites.
8742

8743
    This only checks the optional instance list against the existing names.
8744

8745
    """
8746
    if self.wanted_names is None:
8747
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8748

    
8749
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8750
                             in self.wanted_names]
8751

    
8752
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8753
    """Returns the status of a block device
8754

8755
    """
8756
    if self.op.static or not node:
8757
      return None
8758

    
8759
    self.cfg.SetDiskID(dev, node)
8760

    
8761
    result = self.rpc.call_blockdev_find(node, dev)
8762
    if result.offline:
8763
      return None
8764

    
8765
    result.Raise("Can't compute disk status for %s" % instance_name)
8766

    
8767
    status = result.payload
8768
    if status is None:
8769
      return None
8770

    
8771
    return (status.dev_path, status.major, status.minor,
8772
            status.sync_percent, status.estimated_time,
8773
            status.is_degraded, status.ldisk_status)
8774

    
8775
  def _ComputeDiskStatus(self, instance, snode, dev):
8776
    """Compute block device status.
8777

8778
    """
8779
    if dev.dev_type in constants.LDS_DRBD:
8780
      # we change the snode then (otherwise we use the one passed in)
8781
      if dev.logical_id[0] == instance.primary_node:
8782
        snode = dev.logical_id[1]
8783
      else:
8784
        snode = dev.logical_id[0]
8785

    
8786
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8787
                                              instance.name, dev)
8788
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8789

    
8790
    if dev.children:
8791
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8792
                      for child in dev.children]
8793
    else:
8794
      dev_children = []
8795

    
8796
    data = {
8797
      "iv_name": dev.iv_name,
8798
      "dev_type": dev.dev_type,
8799
      "logical_id": dev.logical_id,
8800
      "physical_id": dev.physical_id,
8801
      "pstatus": dev_pstatus,
8802
      "sstatus": dev_sstatus,
8803
      "children": dev_children,
8804
      "mode": dev.mode,
8805
      "size": dev.size,
8806
      }
8807

    
8808
    return data
8809

    
8810
  def Exec(self, feedback_fn):
8811
    """Gather and return data"""
8812
    result = {}
8813

    
8814
    cluster = self.cfg.GetClusterInfo()
8815

    
8816
    for instance in self.wanted_instances:
8817
      if not self.op.static:
8818
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8819
                                                  instance.name,
8820
                                                  instance.hypervisor)
8821
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8822
        remote_info = remote_info.payload
8823
        if remote_info and "state" in remote_info:
8824
          remote_state = "up"
8825
        else:
8826
          remote_state = "down"
8827
      else:
8828
        remote_state = None
8829
      if instance.admin_up:
8830
        config_state = "up"
8831
      else:
8832
        config_state = "down"
8833

    
8834
      disks = [self._ComputeDiskStatus(instance, None, device)
8835
               for device in instance.disks]
8836

    
8837
      idict = {
8838
        "name": instance.name,
8839
        "config_state": config_state,
8840
        "run_state": remote_state,
8841
        "pnode": instance.primary_node,
8842
        "snodes": instance.secondary_nodes,
8843
        "os": instance.os,
8844
        # this happens to be the same format used for hooks
8845
        "nics": _NICListToTuple(self, instance.nics),
8846
        "disk_template": instance.disk_template,
8847
        "disks": disks,
8848
        "hypervisor": instance.hypervisor,
8849
        "network_port": instance.network_port,
8850
        "hv_instance": instance.hvparams,
8851
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8852
        "be_instance": instance.beparams,
8853
        "be_actual": cluster.FillBE(instance),
8854
        "os_instance": instance.osparams,
8855
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8856
        "serial_no": instance.serial_no,
8857
        "mtime": instance.mtime,
8858
        "ctime": instance.ctime,
8859
        "uuid": instance.uuid,
8860
        }
8861

    
8862
      result[instance.name] = idict
8863

    
8864
    return result
8865

    
8866

    
8867
class LUInstanceSetParams(LogicalUnit):
8868
  """Modifies an instances's parameters.
8869

8870
  """
8871
  HPATH = "instance-modify"
8872
  HTYPE = constants.HTYPE_INSTANCE
8873
  REQ_BGL = False
8874

    
8875
  def CheckArguments(self):
8876
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8877
            self.op.hvparams or self.op.beparams or self.op.os_name):
8878
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8879

    
8880
    if self.op.hvparams:
8881
      _CheckGlobalHvParams(self.op.hvparams)
8882

    
8883
    # Disk validation
8884
    disk_addremove = 0
8885
    for disk_op, disk_dict in self.op.disks:
8886
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8887
      if disk_op == constants.DDM_REMOVE:
8888
        disk_addremove += 1
8889
        continue
8890
      elif disk_op == constants.DDM_ADD:
8891
        disk_addremove += 1
8892
      else:
8893
        if not isinstance(disk_op, int):
8894
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8895
        if not isinstance(disk_dict, dict):
8896
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8897
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8898

    
8899
      if disk_op == constants.DDM_ADD:
8900
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8901
        if mode not in constants.DISK_ACCESS_SET:
8902
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8903
                                     errors.ECODE_INVAL)
8904
        size = disk_dict.get('size', None)
8905
        if size is None:
8906
          raise errors.OpPrereqError("Required disk parameter size missing",
8907
                                     errors.ECODE_INVAL)
8908
        try:
8909
          size = int(size)
8910
        except (TypeError, ValueError), err:
8911
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8912
                                     str(err), errors.ECODE_INVAL)
8913
        disk_dict['size'] = size
8914
      else:
8915
        # modification of disk
8916
        if 'size' in disk_dict:
8917
          raise errors.OpPrereqError("Disk size change not possible, use"
8918
                                     " grow-disk", errors.ECODE_INVAL)
8919

    
8920
    if disk_addremove > 1:
8921
      raise errors.OpPrereqError("Only one disk add or remove operation"
8922
                                 " supported at a time", errors.ECODE_INVAL)
8923

    
8924
    if self.op.disks and self.op.disk_template is not None:
8925
      raise errors.OpPrereqError("Disk template conversion and other disk"
8926
                                 " changes not supported at the same time",
8927
                                 errors.ECODE_INVAL)
8928

    
8929
    if (self.op.disk_template and
8930
        self.op.disk_template in constants.DTS_NET_MIRROR and
8931
        self.op.remote_node is None):
8932
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
8933
                                 " one requires specifying a secondary node",
8934
                                 errors.ECODE_INVAL)
8935

    
8936
    # NIC validation
8937
    nic_addremove = 0
8938
    for nic_op, nic_dict in self.op.nics:
8939
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8940
      if nic_op == constants.DDM_REMOVE:
8941
        nic_addremove += 1
8942
        continue
8943
      elif nic_op == constants.DDM_ADD:
8944
        nic_addremove += 1
8945
      else:
8946
        if not isinstance(nic_op, int):
8947
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8948
        if not isinstance(nic_dict, dict):
8949
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8950
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8951

    
8952
      # nic_dict should be a dict
8953
      nic_ip = nic_dict.get('ip', None)
8954
      if nic_ip is not None:
8955
        if nic_ip.lower() == constants.VALUE_NONE:
8956
          nic_dict['ip'] = None
8957
        else:
8958
          if not netutils.IPAddress.IsValid(nic_ip):
8959
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8960
                                       errors.ECODE_INVAL)
8961

    
8962
      nic_bridge = nic_dict.get('bridge', None)
8963
      nic_link = nic_dict.get('link', None)
8964
      if nic_bridge and nic_link:
8965
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8966
                                   " at the same time", errors.ECODE_INVAL)
8967
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8968
        nic_dict['bridge'] = None
8969
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8970
        nic_dict['link'] = None
8971

    
8972
      if nic_op == constants.DDM_ADD:
8973
        nic_mac = nic_dict.get('mac', None)
8974
        if nic_mac is None:
8975
          nic_dict['mac'] = constants.VALUE_AUTO
8976

    
8977
      if 'mac' in nic_dict:
8978
        nic_mac = nic_dict['mac']
8979
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8980
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8981

    
8982
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8983
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8984
                                     " modifying an existing nic",
8985
                                     errors.ECODE_INVAL)
8986

    
8987
    if nic_addremove > 1:
8988
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8989
                                 " supported at a time", errors.ECODE_INVAL)
8990

    
8991
  def ExpandNames(self):
8992
    self._ExpandAndLockInstance()
8993
    self.needed_locks[locking.LEVEL_NODE] = []
8994
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8995

    
8996
  def DeclareLocks(self, level):
8997
    if level == locking.LEVEL_NODE:
8998
      self._LockInstancesNodes()
8999
      if self.op.disk_template and self.op.remote_node:
9000
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9001
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9002

    
9003
  def BuildHooksEnv(self):
9004
    """Build hooks env.
9005

9006
    This runs on the master, primary and secondaries.
9007

9008
    """
9009
    args = dict()
9010
    if constants.BE_MEMORY in self.be_new:
9011
      args['memory'] = self.be_new[constants.BE_MEMORY]
9012
    if constants.BE_VCPUS in self.be_new:
9013
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9014
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9015
    # information at all.
9016
    if self.op.nics:
9017
      args['nics'] = []
9018
      nic_override = dict(self.op.nics)
9019
      for idx, nic in enumerate(self.instance.nics):
9020
        if idx in nic_override:
9021
          this_nic_override = nic_override[idx]
9022
        else:
9023
          this_nic_override = {}
9024
        if 'ip' in this_nic_override:
9025
          ip = this_nic_override['ip']
9026
        else:
9027
          ip = nic.ip
9028
        if 'mac' in this_nic_override:
9029
          mac = this_nic_override['mac']
9030
        else:
9031
          mac = nic.mac
9032
        if idx in self.nic_pnew:
9033
          nicparams = self.nic_pnew[idx]
9034
        else:
9035
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
9036
        mode = nicparams[constants.NIC_MODE]
9037
        link = nicparams[constants.NIC_LINK]
9038
        args['nics'].append((ip, mac, mode, link))
9039
      if constants.DDM_ADD in nic_override:
9040
        ip = nic_override[constants.DDM_ADD].get('ip', None)
9041
        mac = nic_override[constants.DDM_ADD]['mac']
9042
        nicparams = self.nic_pnew[constants.DDM_ADD]
9043
        mode = nicparams[constants.NIC_MODE]
9044
        link = nicparams[constants.NIC_LINK]
9045
        args['nics'].append((ip, mac, mode, link))
9046
      elif constants.DDM_REMOVE in nic_override:
9047
        del args['nics'][-1]
9048

    
9049
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
9050
    if self.op.disk_template:
9051
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
9052
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9053
    return env, nl, nl
9054

    
9055
  def CheckPrereq(self):
9056
    """Check prerequisites.
9057

9058
    This only checks the instance list against the existing names.
9059

9060
    """
9061
    # checking the new params on the primary/secondary nodes
9062

    
9063
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9064
    cluster = self.cluster = self.cfg.GetClusterInfo()
9065
    assert self.instance is not None, \
9066
      "Cannot retrieve locked instance %s" % self.op.instance_name
9067
    pnode = instance.primary_node
9068
    nodelist = list(instance.all_nodes)
9069

    
9070
    # OS change
9071
    if self.op.os_name and not self.op.force:
9072
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
9073
                      self.op.force_variant)
9074
      instance_os = self.op.os_name
9075
    else:
9076
      instance_os = instance.os
9077

    
9078
    if self.op.disk_template:
9079
      if instance.disk_template == self.op.disk_template:
9080
        raise errors.OpPrereqError("Instance already has disk template %s" %
9081
                                   instance.disk_template, errors.ECODE_INVAL)
9082

    
9083
      if (instance.disk_template,
9084
          self.op.disk_template) not in self._DISK_CONVERSIONS:
9085
        raise errors.OpPrereqError("Unsupported disk template conversion from"
9086
                                   " %s to %s" % (instance.disk_template,
9087
                                                  self.op.disk_template),
9088
                                   errors.ECODE_INVAL)
9089
      _CheckInstanceDown(self, instance, "cannot change disk template")
9090
      if self.op.disk_template in constants.DTS_NET_MIRROR:
9091
        if self.op.remote_node == pnode:
9092
          raise errors.OpPrereqError("Given new secondary node %s is the same"
9093
                                     " as the primary node of the instance" %
9094
                                     self.op.remote_node, errors.ECODE_STATE)
9095
        _CheckNodeOnline(self, self.op.remote_node)
9096
        _CheckNodeNotDrained(self, self.op.remote_node)
9097
        # FIXME: here we assume that the old instance type is DT_PLAIN
9098
        assert instance.disk_template == constants.DT_PLAIN
9099
        disks = [{"size": d.size, "vg": d.logical_id[0]}
9100
                 for d in instance.disks]
9101
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
9102
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
9103

    
9104
    # hvparams processing
9105
    if self.op.hvparams:
9106
      hv_type = instance.hypervisor
9107
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
9108
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
9109
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
9110

    
9111
      # local check
9112
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
9113
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
9114
      self.hv_new = hv_new # the new actual values
9115
      self.hv_inst = i_hvdict # the new dict (without defaults)
9116
    else:
9117
      self.hv_new = self.hv_inst = {}
9118

    
9119
    # beparams processing
9120
    if self.op.beparams:
9121
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
9122
                                   use_none=True)
9123
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
9124
      be_new = cluster.SimpleFillBE(i_bedict)
9125
      self.be_new = be_new # the new actual values
9126
      self.be_inst = i_bedict # the new dict (without defaults)
9127
    else:
9128
      self.be_new = self.be_inst = {}
9129

    
9130
    # osparams processing
9131
    if self.op.osparams:
9132
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
9133
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
9134
      self.os_inst = i_osdict # the new dict (without defaults)
9135
    else:
9136
      self.os_inst = {}
9137

    
9138
    self.warn = []
9139

    
9140
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
9141
      mem_check_list = [pnode]
9142
      if be_new[constants.BE_AUTO_BALANCE]:
9143
        # either we changed auto_balance to yes or it was from before
9144
        mem_check_list.extend(instance.secondary_nodes)
9145
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
9146
                                                  instance.hypervisor)
9147
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
9148
                                         instance.hypervisor)
9149
      pninfo = nodeinfo[pnode]
9150
      msg = pninfo.fail_msg
9151
      if msg:
9152
        # Assume the primary node is unreachable and go ahead
9153
        self.warn.append("Can't get info from primary node %s: %s" %
9154
                         (pnode,  msg))
9155
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
9156
        self.warn.append("Node data from primary node %s doesn't contain"
9157
                         " free memory information" % pnode)
9158
      elif instance_info.fail_msg:
9159
        self.warn.append("Can't get instance runtime information: %s" %
9160
                        instance_info.fail_msg)
9161
      else:
9162
        if instance_info.payload:
9163
          current_mem = int(instance_info.payload['memory'])
9164
        else:
9165
          # Assume instance not running
9166
          # (there is a slight race condition here, but it's not very probable,
9167
          # and we have no other way to check)
9168
          current_mem = 0
9169
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
9170
                    pninfo.payload['memory_free'])
9171
        if miss_mem > 0:
9172
          raise errors.OpPrereqError("This change will prevent the instance"
9173
                                     " from starting, due to %d MB of memory"
9174
                                     " missing on its primary node" % miss_mem,
9175
                                     errors.ECODE_NORES)
9176

    
9177
      if be_new[constants.BE_AUTO_BALANCE]:
9178
        for node, nres in nodeinfo.items():
9179
          if node not in instance.secondary_nodes:
9180
            continue
9181
          msg = nres.fail_msg
9182
          if msg:
9183
            self.warn.append("Can't get info from secondary node %s: %s" %
9184
                             (node, msg))
9185
          elif not isinstance(nres.payload.get('memory_free', None), int):
9186
            self.warn.append("Secondary node %s didn't return free"
9187
                             " memory information" % node)
9188
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
9189
            self.warn.append("Not enough memory to failover instance to"
9190
                             " secondary node %s" % node)
9191

    
9192
    # NIC processing
9193
    self.nic_pnew = {}
9194
    self.nic_pinst = {}
9195
    for nic_op, nic_dict in self.op.nics:
9196
      if nic_op == constants.DDM_REMOVE:
9197
        if not instance.nics:
9198
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
9199
                                     errors.ECODE_INVAL)
9200
        continue
9201
      if nic_op != constants.DDM_ADD:
9202
        # an existing nic
9203
        if not instance.nics:
9204
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
9205
                                     " no NICs" % nic_op,
9206
                                     errors.ECODE_INVAL)
9207
        if nic_op < 0 or nic_op >= len(instance.nics):
9208
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
9209
                                     " are 0 to %d" %
9210
                                     (nic_op, len(instance.nics) - 1),
9211
                                     errors.ECODE_INVAL)
9212
        old_nic_params = instance.nics[nic_op].nicparams
9213
        old_nic_ip = instance.nics[nic_op].ip
9214
      else:
9215
        old_nic_params = {}
9216
        old_nic_ip = None
9217

    
9218
      update_params_dict = dict([(key, nic_dict[key])
9219
                                 for key in constants.NICS_PARAMETERS
9220
                                 if key in nic_dict])
9221

    
9222
      if 'bridge' in nic_dict:
9223
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
9224

    
9225
      new_nic_params = _GetUpdatedParams(old_nic_params,
9226
                                         update_params_dict)
9227
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
9228
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
9229
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
9230
      self.nic_pinst[nic_op] = new_nic_params
9231
      self.nic_pnew[nic_op] = new_filled_nic_params
9232
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9233

    
9234
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9235
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9236
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9237
        if msg:
9238
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9239
          if self.op.force:
9240
            self.warn.append(msg)
9241
          else:
9242
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9243
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9244
        if 'ip' in nic_dict:
9245
          nic_ip = nic_dict['ip']
9246
        else:
9247
          nic_ip = old_nic_ip
9248
        if nic_ip is None:
9249
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9250
                                     ' on a routed nic', errors.ECODE_INVAL)
9251
      if 'mac' in nic_dict:
9252
        nic_mac = nic_dict['mac']
9253
        if nic_mac is None:
9254
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9255
                                     errors.ECODE_INVAL)
9256
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9257
          # otherwise generate the mac
9258
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9259
        else:
9260
          # or validate/reserve the current one
9261
          try:
9262
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9263
          except errors.ReservationError:
9264
            raise errors.OpPrereqError("MAC address %s already in use"
9265
                                       " in cluster" % nic_mac,
9266
                                       errors.ECODE_NOTUNIQUE)
9267

    
9268
    # DISK processing
9269
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9270
      raise errors.OpPrereqError("Disk operations not supported for"
9271
                                 " diskless instances",
9272
                                 errors.ECODE_INVAL)
9273
    for disk_op, _ in self.op.disks:
9274
      if disk_op == constants.DDM_REMOVE:
9275
        if len(instance.disks) == 1:
9276
          raise errors.OpPrereqError("Cannot remove the last disk of"
9277
                                     " an instance", errors.ECODE_INVAL)
9278
        _CheckInstanceDown(self, instance, "cannot remove disks")
9279

    
9280
      if (disk_op == constants.DDM_ADD and
9281
          len(instance.disks) >= constants.MAX_DISKS):
9282
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9283
                                   " add more" % constants.MAX_DISKS,
9284
                                   errors.ECODE_STATE)
9285
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9286
        # an existing disk
9287
        if disk_op < 0 or disk_op >= len(instance.disks):
9288
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9289
                                     " are 0 to %d" %
9290
                                     (disk_op, len(instance.disks)),
9291
                                     errors.ECODE_INVAL)
9292

    
9293
    return
9294

    
9295
  def _ConvertPlainToDrbd(self, feedback_fn):
9296
    """Converts an instance from plain to drbd.
9297

9298
    """
9299
    feedback_fn("Converting template to drbd")
9300
    instance = self.instance
9301
    pnode = instance.primary_node
9302
    snode = self.op.remote_node
9303

    
9304
    # create a fake disk info for _GenerateDiskTemplate
9305
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9306
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9307
                                      instance.name, pnode, [snode],
9308
                                      disk_info, None, None, 0, feedback_fn)
9309
    info = _GetInstanceInfoText(instance)
9310
    feedback_fn("Creating aditional volumes...")
9311
    # first, create the missing data and meta devices
9312
    for disk in new_disks:
9313
      # unfortunately this is... not too nice
9314
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9315
                            info, True)
9316
      for child in disk.children:
9317
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9318
    # at this stage, all new LVs have been created, we can rename the
9319
    # old ones
9320
    feedback_fn("Renaming original volumes...")
9321
    rename_list = [(o, n.children[0].logical_id)
9322
                   for (o, n) in zip(instance.disks, new_disks)]
9323
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9324
    result.Raise("Failed to rename original LVs")
9325

    
9326
    feedback_fn("Initializing DRBD devices...")
9327
    # all child devices are in place, we can now create the DRBD devices
9328
    for disk in new_disks:
9329
      for node in [pnode, snode]:
9330
        f_create = node == pnode
9331
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9332

    
9333
    # at this point, the instance has been modified
9334
    instance.disk_template = constants.DT_DRBD8
9335
    instance.disks = new_disks
9336
    self.cfg.Update(instance, feedback_fn)
9337

    
9338
    # disks are created, waiting for sync
9339
    disk_abort = not _WaitForSync(self, instance)
9340
    if disk_abort:
9341
      raise errors.OpExecError("There are some degraded disks for"
9342
                               " this instance, please cleanup manually")
9343

    
9344
  def _ConvertDrbdToPlain(self, feedback_fn):
9345
    """Converts an instance from drbd to plain.
9346

9347
    """
9348
    instance = self.instance
9349
    assert len(instance.secondary_nodes) == 1
9350
    pnode = instance.primary_node
9351
    snode = instance.secondary_nodes[0]
9352
    feedback_fn("Converting template to plain")
9353

    
9354
    old_disks = instance.disks
9355
    new_disks = [d.children[0] for d in old_disks]
9356

    
9357
    # copy over size and mode
9358
    for parent, child in zip(old_disks, new_disks):
9359
      child.size = parent.size
9360
      child.mode = parent.mode
9361

    
9362
    # update instance structure
9363
    instance.disks = new_disks
9364
    instance.disk_template = constants.DT_PLAIN
9365
    self.cfg.Update(instance, feedback_fn)
9366

    
9367
    feedback_fn("Removing volumes on the secondary node...")
9368
    for disk in old_disks:
9369
      self.cfg.SetDiskID(disk, snode)
9370
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9371
      if msg:
9372
        self.LogWarning("Could not remove block device %s on node %s,"
9373
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9374

    
9375
    feedback_fn("Removing unneeded volumes on the primary node...")
9376
    for idx, disk in enumerate(old_disks):
9377
      meta = disk.children[1]
9378
      self.cfg.SetDiskID(meta, pnode)
9379
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9380
      if msg:
9381
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9382
                        " continuing anyway: %s", idx, pnode, msg)
9383

    
9384
  def Exec(self, feedback_fn):
9385
    """Modifies an instance.
9386

9387
    All parameters take effect only at the next restart of the instance.
9388

9389
    """
9390
    # Process here the warnings from CheckPrereq, as we don't have a
9391
    # feedback_fn there.
9392
    for warn in self.warn:
9393
      feedback_fn("WARNING: %s" % warn)
9394

    
9395
    result = []
9396
    instance = self.instance
9397
    # disk changes
9398
    for disk_op, disk_dict in self.op.disks:
9399
      if disk_op == constants.DDM_REMOVE:
9400
        # remove the last disk
9401
        device = instance.disks.pop()
9402
        device_idx = len(instance.disks)
9403
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9404
          self.cfg.SetDiskID(disk, node)
9405
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9406
          if msg:
9407
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9408
                            " continuing anyway", device_idx, node, msg)
9409
        result.append(("disk/%d" % device_idx, "remove"))
9410
      elif disk_op == constants.DDM_ADD:
9411
        # add a new disk
9412
        if instance.disk_template == constants.DT_FILE:
9413
          file_driver, file_path = instance.disks[0].logical_id
9414
          file_path = os.path.dirname(file_path)
9415
        else:
9416
          file_driver = file_path = None
9417
        disk_idx_base = len(instance.disks)
9418
        new_disk = _GenerateDiskTemplate(self,
9419
                                         instance.disk_template,
9420
                                         instance.name, instance.primary_node,
9421
                                         instance.secondary_nodes,
9422
                                         [disk_dict],
9423
                                         file_path,
9424
                                         file_driver,
9425
                                         disk_idx_base, feedback_fn)[0]
9426
        instance.disks.append(new_disk)
9427
        info = _GetInstanceInfoText(instance)
9428

    
9429
        logging.info("Creating volume %s for instance %s",
9430
                     new_disk.iv_name, instance.name)
9431
        # Note: this needs to be kept in sync with _CreateDisks
9432
        #HARDCODE
9433
        for node in instance.all_nodes:
9434
          f_create = node == instance.primary_node
9435
          try:
9436
            _CreateBlockDev(self, node, instance, new_disk,
9437
                            f_create, info, f_create)
9438
          except errors.OpExecError, err:
9439
            self.LogWarning("Failed to create volume %s (%s) on"
9440
                            " node %s: %s",
9441
                            new_disk.iv_name, new_disk, node, err)
9442
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9443
                       (new_disk.size, new_disk.mode)))
9444
      else:
9445
        # change a given disk
9446
        instance.disks[disk_op].mode = disk_dict['mode']
9447
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9448

    
9449
    if self.op.disk_template:
9450
      r_shut = _ShutdownInstanceDisks(self, instance)
9451
      if not r_shut:
9452
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
9453
                                 " proceed with disk template conversion")
9454
      mode = (instance.disk_template, self.op.disk_template)
9455
      try:
9456
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9457
      except:
9458
        self.cfg.ReleaseDRBDMinors(instance.name)
9459
        raise
9460
      result.append(("disk_template", self.op.disk_template))
9461

    
9462
    # NIC changes
9463
    for nic_op, nic_dict in self.op.nics:
9464
      if nic_op == constants.DDM_REMOVE:
9465
        # remove the last nic
9466
        del instance.nics[-1]
9467
        result.append(("nic.%d" % len(instance.nics), "remove"))
9468
      elif nic_op == constants.DDM_ADD:
9469
        # mac and bridge should be set, by now
9470
        mac = nic_dict['mac']
9471
        ip = nic_dict.get('ip', None)
9472
        nicparams = self.nic_pinst[constants.DDM_ADD]
9473
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9474
        instance.nics.append(new_nic)
9475
        result.append(("nic.%d" % (len(instance.nics) - 1),
9476
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9477
                       (new_nic.mac, new_nic.ip,
9478
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9479
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9480
                       )))
9481
      else:
9482
        for key in 'mac', 'ip':
9483
          if key in nic_dict:
9484
            setattr(instance.nics[nic_op], key, nic_dict[key])
9485
        if nic_op in self.nic_pinst:
9486
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9487
        for key, val in nic_dict.iteritems():
9488
          result.append(("nic.%s/%d" % (key, nic_op), val))
9489

    
9490
    # hvparams changes
9491
    if self.op.hvparams:
9492
      instance.hvparams = self.hv_inst
9493
      for key, val in self.op.hvparams.iteritems():
9494
        result.append(("hv/%s" % key, val))
9495

    
9496
    # beparams changes
9497
    if self.op.beparams:
9498
      instance.beparams = self.be_inst
9499
      for key, val in self.op.beparams.iteritems():
9500
        result.append(("be/%s" % key, val))
9501

    
9502
    # OS change
9503
    if self.op.os_name:
9504
      instance.os = self.op.os_name
9505

    
9506
    # osparams changes
9507
    if self.op.osparams:
9508
      instance.osparams = self.os_inst
9509
      for key, val in self.op.osparams.iteritems():
9510
        result.append(("os/%s" % key, val))
9511

    
9512
    self.cfg.Update(instance, feedback_fn)
9513

    
9514
    return result
9515

    
9516
  _DISK_CONVERSIONS = {
9517
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9518
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9519
    }
9520

    
9521

    
9522
class LUBackupQuery(NoHooksLU):
9523
  """Query the exports list
9524

9525
  """
9526
  REQ_BGL = False
9527

    
9528
  def ExpandNames(self):
9529
    self.needed_locks = {}
9530
    self.share_locks[locking.LEVEL_NODE] = 1
9531
    if not self.op.nodes:
9532
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9533
    else:
9534
      self.needed_locks[locking.LEVEL_NODE] = \
9535
        _GetWantedNodes(self, self.op.nodes)
9536

    
9537
  def Exec(self, feedback_fn):
9538
    """Compute the list of all the exported system images.
9539

9540
    @rtype: dict
9541
    @return: a dictionary with the structure node->(export-list)
9542
        where export-list is a list of the instances exported on
9543
        that node.
9544

9545
    """
9546
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9547
    rpcresult = self.rpc.call_export_list(self.nodes)
9548
    result = {}
9549
    for node in rpcresult:
9550
      if rpcresult[node].fail_msg:
9551
        result[node] = False
9552
      else:
9553
        result[node] = rpcresult[node].payload
9554

    
9555
    return result
9556

    
9557

    
9558
class LUBackupPrepare(NoHooksLU):
9559
  """Prepares an instance for an export and returns useful information.
9560

9561
  """
9562
  REQ_BGL = False
9563

    
9564
  def ExpandNames(self):
9565
    self._ExpandAndLockInstance()
9566

    
9567
  def CheckPrereq(self):
9568
    """Check prerequisites.
9569

9570
    """
9571
    instance_name = self.op.instance_name
9572

    
9573
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9574
    assert self.instance is not None, \
9575
          "Cannot retrieve locked instance %s" % self.op.instance_name
9576
    _CheckNodeOnline(self, self.instance.primary_node)
9577

    
9578
    self._cds = _GetClusterDomainSecret()
9579

    
9580
  def Exec(self, feedback_fn):
9581
    """Prepares an instance for an export.
9582

9583
    """
9584
    instance = self.instance
9585

    
9586
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9587
      salt = utils.GenerateSecret(8)
9588

    
9589
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9590
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9591
                                              constants.RIE_CERT_VALIDITY)
9592
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9593

    
9594
      (name, cert_pem) = result.payload
9595

    
9596
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9597
                                             cert_pem)
9598

    
9599
      return {
9600
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9601
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9602
                          salt),
9603
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9604
        }
9605

    
9606
    return None
9607

    
9608

    
9609
class LUBackupExport(LogicalUnit):
9610
  """Export an instance to an image in the cluster.
9611

9612
  """
9613
  HPATH = "instance-export"
9614
  HTYPE = constants.HTYPE_INSTANCE
9615
  REQ_BGL = False
9616

    
9617
  def CheckArguments(self):
9618
    """Check the arguments.
9619

9620
    """
9621
    self.x509_key_name = self.op.x509_key_name
9622
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9623

    
9624
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9625
      if not self.x509_key_name:
9626
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9627
                                   errors.ECODE_INVAL)
9628

    
9629
      if not self.dest_x509_ca_pem:
9630
        raise errors.OpPrereqError("Missing destination X509 CA",
9631
                                   errors.ECODE_INVAL)
9632

    
9633
  def ExpandNames(self):
9634
    self._ExpandAndLockInstance()
9635

    
9636
    # Lock all nodes for local exports
9637
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9638
      # FIXME: lock only instance primary and destination node
9639
      #
9640
      # Sad but true, for now we have do lock all nodes, as we don't know where
9641
      # the previous export might be, and in this LU we search for it and
9642
      # remove it from its current node. In the future we could fix this by:
9643
      #  - making a tasklet to search (share-lock all), then create the
9644
      #    new one, then one to remove, after
9645
      #  - removing the removal operation altogether
9646
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9647

    
9648
  def DeclareLocks(self, level):
9649
    """Last minute lock declaration."""
9650
    # All nodes are locked anyway, so nothing to do here.
9651

    
9652
  def BuildHooksEnv(self):
9653
    """Build hooks env.
9654

9655
    This will run on the master, primary node and target node.
9656

9657
    """
9658
    env = {
9659
      "EXPORT_MODE": self.op.mode,
9660
      "EXPORT_NODE": self.op.target_node,
9661
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9662
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9663
      # TODO: Generic function for boolean env variables
9664
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9665
      }
9666

    
9667
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9668

    
9669
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9670

    
9671
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9672
      nl.append(self.op.target_node)
9673

    
9674
    return env, nl, nl
9675

    
9676
  def CheckPrereq(self):
9677
    """Check prerequisites.
9678

9679
    This checks that the instance and node names are valid.
9680

9681
    """
9682
    instance_name = self.op.instance_name
9683

    
9684
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9685
    assert self.instance is not None, \
9686
          "Cannot retrieve locked instance %s" % self.op.instance_name
9687
    _CheckNodeOnline(self, self.instance.primary_node)
9688

    
9689
    if (self.op.remove_instance and self.instance.admin_up and
9690
        not self.op.shutdown):
9691
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9692
                                 " down before")
9693

    
9694
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9695
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9696
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9697
      assert self.dst_node is not None
9698

    
9699
      _CheckNodeOnline(self, self.dst_node.name)
9700
      _CheckNodeNotDrained(self, self.dst_node.name)
9701

    
9702
      self._cds = None
9703
      self.dest_disk_info = None
9704
      self.dest_x509_ca = None
9705

    
9706
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9707
      self.dst_node = None
9708

    
9709
      if len(self.op.target_node) != len(self.instance.disks):
9710
        raise errors.OpPrereqError(("Received destination information for %s"
9711
                                    " disks, but instance %s has %s disks") %
9712
                                   (len(self.op.target_node), instance_name,
9713
                                    len(self.instance.disks)),
9714
                                   errors.ECODE_INVAL)
9715

    
9716
      cds = _GetClusterDomainSecret()
9717

    
9718
      # Check X509 key name
9719
      try:
9720
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9721
      except (TypeError, ValueError), err:
9722
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9723

    
9724
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9725
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9726
                                   errors.ECODE_INVAL)
9727

    
9728
      # Load and verify CA
9729
      try:
9730
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9731
      except OpenSSL.crypto.Error, err:
9732
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9733
                                   (err, ), errors.ECODE_INVAL)
9734

    
9735
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9736
      if errcode is not None:
9737
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9738
                                   (msg, ), errors.ECODE_INVAL)
9739

    
9740
      self.dest_x509_ca = cert
9741

    
9742
      # Verify target information
9743
      disk_info = []
9744
      for idx, disk_data in enumerate(self.op.target_node):
9745
        try:
9746
          (host, port, magic) = \
9747
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9748
        except errors.GenericError, err:
9749
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9750
                                     (idx, err), errors.ECODE_INVAL)
9751

    
9752
        disk_info.append((host, port, magic))
9753

    
9754
      assert len(disk_info) == len(self.op.target_node)
9755
      self.dest_disk_info = disk_info
9756

    
9757
    else:
9758
      raise errors.ProgrammerError("Unhandled export mode %r" %
9759
                                   self.op.mode)
9760

    
9761
    # instance disk type verification
9762
    # TODO: Implement export support for file-based disks
9763
    for disk in self.instance.disks:
9764
      if disk.dev_type == constants.LD_FILE:
9765
        raise errors.OpPrereqError("Export not supported for instances with"
9766
                                   " file-based disks", errors.ECODE_INVAL)
9767

    
9768
  def _CleanupExports(self, feedback_fn):
9769
    """Removes exports of current instance from all other nodes.
9770

9771
    If an instance in a cluster with nodes A..D was exported to node C, its
9772
    exports will be removed from the nodes A, B and D.
9773

9774
    """
9775
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9776

    
9777
    nodelist = self.cfg.GetNodeList()
9778
    nodelist.remove(self.dst_node.name)
9779

    
9780
    # on one-node clusters nodelist will be empty after the removal
9781
    # if we proceed the backup would be removed because OpBackupQuery
9782
    # substitutes an empty list with the full cluster node list.
9783
    iname = self.instance.name
9784
    if nodelist:
9785
      feedback_fn("Removing old exports for instance %s" % iname)
9786
      exportlist = self.rpc.call_export_list(nodelist)
9787
      for node in exportlist:
9788
        if exportlist[node].fail_msg:
9789
          continue
9790
        if iname in exportlist[node].payload:
9791
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9792
          if msg:
9793
            self.LogWarning("Could not remove older export for instance %s"
9794
                            " on node %s: %s", iname, node, msg)
9795

    
9796
  def Exec(self, feedback_fn):
9797
    """Export an instance to an image in the cluster.
9798

9799
    """
9800
    assert self.op.mode in constants.EXPORT_MODES
9801

    
9802
    instance = self.instance
9803
    src_node = instance.primary_node
9804

    
9805
    if self.op.shutdown:
9806
      # shutdown the instance, but not the disks
9807
      feedback_fn("Shutting down instance %s" % instance.name)
9808
      result = self.rpc.call_instance_shutdown(src_node, instance,
9809
                                               self.op.shutdown_timeout)
9810
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9811
      result.Raise("Could not shutdown instance %s on"
9812
                   " node %s" % (instance.name, src_node))
9813

    
9814
    # set the disks ID correctly since call_instance_start needs the
9815
    # correct drbd minor to create the symlinks
9816
    for disk in instance.disks:
9817
      self.cfg.SetDiskID(disk, src_node)
9818

    
9819
    activate_disks = (not instance.admin_up)
9820

    
9821
    if activate_disks:
9822
      # Activate the instance disks if we'exporting a stopped instance
9823
      feedback_fn("Activating disks for %s" % instance.name)
9824
      _StartInstanceDisks(self, instance, None)
9825

    
9826
    try:
9827
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9828
                                                     instance)
9829

    
9830
      helper.CreateSnapshots()
9831
      try:
9832
        if (self.op.shutdown and instance.admin_up and
9833
            not self.op.remove_instance):
9834
          assert not activate_disks
9835
          feedback_fn("Starting instance %s" % instance.name)
9836
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9837
          msg = result.fail_msg
9838
          if msg:
9839
            feedback_fn("Failed to start instance: %s" % msg)
9840
            _ShutdownInstanceDisks(self, instance)
9841
            raise errors.OpExecError("Could not start instance: %s" % msg)
9842

    
9843
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9844
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9845
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9846
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9847
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9848

    
9849
          (key_name, _, _) = self.x509_key_name
9850

    
9851
          dest_ca_pem = \
9852
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9853
                                            self.dest_x509_ca)
9854

    
9855
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9856
                                                     key_name, dest_ca_pem,
9857
                                                     timeouts)
9858
      finally:
9859
        helper.Cleanup()
9860

    
9861
      # Check for backwards compatibility
9862
      assert len(dresults) == len(instance.disks)
9863
      assert compat.all(isinstance(i, bool) for i in dresults), \
9864
             "Not all results are boolean: %r" % dresults
9865

    
9866
    finally:
9867
      if activate_disks:
9868
        feedback_fn("Deactivating disks for %s" % instance.name)
9869
        _ShutdownInstanceDisks(self, instance)
9870

    
9871
    if not (compat.all(dresults) and fin_resu):
9872
      failures = []
9873
      if not fin_resu:
9874
        failures.append("export finalization")
9875
      if not compat.all(dresults):
9876
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9877
                               if not dsk)
9878
        failures.append("disk export: disk(s) %s" % fdsk)
9879

    
9880
      raise errors.OpExecError("Export failed, errors in %s" %
9881
                               utils.CommaJoin(failures))
9882

    
9883
    # At this point, the export was successful, we can cleanup/finish
9884

    
9885
    # Remove instance if requested
9886
    if self.op.remove_instance:
9887
      feedback_fn("Removing instance %s" % instance.name)
9888
      _RemoveInstance(self, feedback_fn, instance,
9889
                      self.op.ignore_remove_failures)
9890

    
9891
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9892
      self._CleanupExports(feedback_fn)
9893

    
9894
    return fin_resu, dresults
9895

    
9896

    
9897
class LUBackupRemove(NoHooksLU):
9898
  """Remove exports related to the named instance.
9899

9900
  """
9901
  REQ_BGL = False
9902

    
9903
  def ExpandNames(self):
9904
    self.needed_locks = {}
9905
    # We need all nodes to be locked in order for RemoveExport to work, but we
9906
    # don't need to lock the instance itself, as nothing will happen to it (and
9907
    # we can remove exports also for a removed instance)
9908
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9909

    
9910
  def Exec(self, feedback_fn):
9911
    """Remove any export.
9912

9913
    """
9914
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9915
    # If the instance was not found we'll try with the name that was passed in.
9916
    # This will only work if it was an FQDN, though.
9917
    fqdn_warn = False
9918
    if not instance_name:
9919
      fqdn_warn = True
9920
      instance_name = self.op.instance_name
9921

    
9922
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9923
    exportlist = self.rpc.call_export_list(locked_nodes)
9924
    found = False
9925
    for node in exportlist:
9926
      msg = exportlist[node].fail_msg
9927
      if msg:
9928
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9929
        continue
9930
      if instance_name in exportlist[node].payload:
9931
        found = True
9932
        result = self.rpc.call_export_remove(node, instance_name)
9933
        msg = result.fail_msg
9934
        if msg:
9935
          logging.error("Could not remove export for instance %s"
9936
                        " on node %s: %s", instance_name, node, msg)
9937

    
9938
    if fqdn_warn and not found:
9939
      feedback_fn("Export not found. If trying to remove an export belonging"
9940
                  " to a deleted instance please use its Fully Qualified"
9941
                  " Domain Name.")
9942

    
9943

    
9944
class LUGroupAdd(LogicalUnit):
9945
  """Logical unit for creating node groups.
9946

9947
  """
9948
  HPATH = "group-add"
9949
  HTYPE = constants.HTYPE_GROUP
9950
  REQ_BGL = False
9951

    
9952
  def ExpandNames(self):
9953
    # We need the new group's UUID here so that we can create and acquire the
9954
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
9955
    # that it should not check whether the UUID exists in the configuration.
9956
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
9957
    self.needed_locks = {}
9958
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
9959

    
9960
  def CheckPrereq(self):
9961
    """Check prerequisites.
9962

9963
    This checks that the given group name is not an existing node group
9964
    already.
9965

9966
    """
9967
    try:
9968
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
9969
    except errors.OpPrereqError:
9970
      pass
9971
    else:
9972
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
9973
                                 " node group (UUID: %s)" %
9974
                                 (self.op.group_name, existing_uuid),
9975
                                 errors.ECODE_EXISTS)
9976

    
9977
    if self.op.ndparams:
9978
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
9979

    
9980
  def BuildHooksEnv(self):
9981
    """Build hooks env.
9982

9983
    """
9984
    env = {
9985
      "GROUP_NAME": self.op.group_name,
9986
      }
9987
    mn = self.cfg.GetMasterNode()
9988
    return env, [mn], [mn]
9989

    
9990
  def Exec(self, feedback_fn):
9991
    """Add the node group to the cluster.
9992

9993
    """
9994
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
9995
                                  uuid=self.group_uuid,
9996
                                  alloc_policy=self.op.alloc_policy,
9997
                                  ndparams=self.op.ndparams)
9998

    
9999
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
10000
    del self.remove_locks[locking.LEVEL_NODEGROUP]
10001

    
10002

    
10003
class LUGroupAssignNodes(NoHooksLU):
10004
  """Logical unit for assigning nodes to groups.
10005

10006
  """
10007
  REQ_BGL = False
10008

    
10009
  def ExpandNames(self):
10010
    # These raise errors.OpPrereqError on their own:
10011
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10012
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
10013

    
10014
    # We want to lock all the affected nodes and groups. We have readily
10015
    # available the list of nodes, and the *destination* group. To gather the
10016
    # list of "source" groups, we need to fetch node information.
10017
    self.node_data = self.cfg.GetAllNodesInfo()
10018
    affected_groups = set(self.node_data[node].group for node in self.op.nodes)
10019
    affected_groups.add(self.group_uuid)
10020

    
10021
    self.needed_locks = {
10022
      locking.LEVEL_NODEGROUP: list(affected_groups),
10023
      locking.LEVEL_NODE: self.op.nodes,
10024
      }
10025

    
10026
  def CheckPrereq(self):
10027
    """Check prerequisites.
10028

10029
    """
10030
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10031
    instance_data = self.cfg.GetAllInstancesInfo()
10032

    
10033
    if self.group is None:
10034
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10035
                               (self.op.group_name, self.group_uuid))
10036

    
10037
    (new_splits, previous_splits) = \
10038
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
10039
                                             for node in self.op.nodes],
10040
                                            self.node_data, instance_data)
10041

    
10042
    if new_splits:
10043
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
10044

    
10045
      if not self.op.force:
10046
        raise errors.OpExecError("The following instances get split by this"
10047
                                 " change and --force was not given: %s" %
10048
                                 fmt_new_splits)
10049
      else:
10050
        self.LogWarning("This operation will split the following instances: %s",
10051
                        fmt_new_splits)
10052

    
10053
        if previous_splits:
10054
          self.LogWarning("In addition, these already-split instances continue"
10055
                          " to be spit across groups: %s",
10056
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
10057

    
10058
  def Exec(self, feedback_fn):
10059
    """Assign nodes to a new group.
10060

10061
    """
10062
    for node in self.op.nodes:
10063
      self.node_data[node].group = self.group_uuid
10064

    
10065
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
10066

    
10067
  @staticmethod
10068
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
10069
    """Check for split instances after a node assignment.
10070

10071
    This method considers a series of node assignments as an atomic operation,
10072
    and returns information about split instances after applying the set of
10073
    changes.
10074

10075
    In particular, it returns information about newly split instances, and
10076
    instances that were already split, and remain so after the change.
10077

10078
    Only instances whose disk template is listed in constants.DTS_NET_MIRROR are
10079
    considered.
10080

10081
    @type changes: list of (node_name, new_group_uuid) pairs.
10082
    @param changes: list of node assignments to consider.
10083
    @param node_data: a dict with data for all nodes
10084
    @param instance_data: a dict with all instances to consider
10085
    @rtype: a two-tuple
10086
    @return: a list of instances that were previously okay and result split as a
10087
      consequence of this change, and a list of instances that were previously
10088
      split and this change does not fix.
10089

10090
    """
10091
    changed_nodes = dict((node, group) for node, group in changes
10092
                         if node_data[node].group != group)
10093

    
10094
    all_split_instances = set()
10095
    previously_split_instances = set()
10096

    
10097
    def InstanceNodes(instance):
10098
      return [instance.primary_node] + list(instance.secondary_nodes)
10099

    
10100
    for inst in instance_data.values():
10101
      if inst.disk_template not in constants.DTS_NET_MIRROR:
10102
        continue
10103

    
10104
      instance_nodes = InstanceNodes(inst)
10105

    
10106
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
10107
        previously_split_instances.add(inst.name)
10108

    
10109
      if len(set(changed_nodes.get(node, node_data[node].group)
10110
                 for node in instance_nodes)) > 1:
10111
        all_split_instances.add(inst.name)
10112

    
10113
    return (list(all_split_instances - previously_split_instances),
10114
            list(previously_split_instances & all_split_instances))
10115

    
10116

    
10117
class _GroupQuery(_QueryBase):
10118

    
10119
  FIELDS = query.GROUP_FIELDS
10120

    
10121
  def ExpandNames(self, lu):
10122
    lu.needed_locks = {}
10123

    
10124
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
10125
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
10126

    
10127
    if not self.names:
10128
      self.wanted = [name_to_uuid[name]
10129
                     for name in utils.NiceSort(name_to_uuid.keys())]
10130
    else:
10131
      # Accept names to be either names or UUIDs.
10132
      missing = []
10133
      self.wanted = []
10134
      all_uuid = frozenset(self._all_groups.keys())
10135

    
10136
      for name in self.names:
10137
        if name in all_uuid:
10138
          self.wanted.append(name)
10139
        elif name in name_to_uuid:
10140
          self.wanted.append(name_to_uuid[name])
10141
        else:
10142
          missing.append(name)
10143

    
10144
      if missing:
10145
        raise errors.OpPrereqError("Some groups do not exist: %s" % missing,
10146
                                   errors.ECODE_NOENT)
10147

    
10148
  def DeclareLocks(self, lu, level):
10149
    pass
10150

    
10151
  def _GetQueryData(self, lu):
10152
    """Computes the list of node groups and their attributes.
10153

10154
    """
10155
    do_nodes = query.GQ_NODE in self.requested_data
10156
    do_instances = query.GQ_INST in self.requested_data
10157

    
10158
    group_to_nodes = None
10159
    group_to_instances = None
10160

    
10161
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
10162
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
10163
    # latter GetAllInstancesInfo() is not enough, for we have to go through
10164
    # instance->node. Hence, we will need to process nodes even if we only need
10165
    # instance information.
10166
    if do_nodes or do_instances:
10167
      all_nodes = lu.cfg.GetAllNodesInfo()
10168
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
10169
      node_to_group = {}
10170

    
10171
      for node in all_nodes.values():
10172
        if node.group in group_to_nodes:
10173
          group_to_nodes[node.group].append(node.name)
10174
          node_to_group[node.name] = node.group
10175

    
10176
      if do_instances:
10177
        all_instances = lu.cfg.GetAllInstancesInfo()
10178
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
10179

    
10180
        for instance in all_instances.values():
10181
          node = instance.primary_node
10182
          if node in node_to_group:
10183
            group_to_instances[node_to_group[node]].append(instance.name)
10184

    
10185
        if not do_nodes:
10186
          # Do not pass on node information if it was not requested.
10187
          group_to_nodes = None
10188

    
10189
    return query.GroupQueryData([self._all_groups[uuid]
10190
                                 for uuid in self.wanted],
10191
                                group_to_nodes, group_to_instances)
10192

    
10193

    
10194
class LUGroupQuery(NoHooksLU):
10195
  """Logical unit for querying node groups.
10196

10197
  """
10198
  REQ_BGL = False
10199

    
10200
  def CheckArguments(self):
10201
    self.gq = _GroupQuery(self.op.names, self.op.output_fields, False)
10202

    
10203
  def ExpandNames(self):
10204
    self.gq.ExpandNames(self)
10205

    
10206
  def Exec(self, feedback_fn):
10207
    return self.gq.OldStyleQuery(self)
10208

    
10209

    
10210
class LUGroupSetParams(LogicalUnit):
10211
  """Modifies the parameters of a node group.
10212

10213
  """
10214
  HPATH = "group-modify"
10215
  HTYPE = constants.HTYPE_GROUP
10216
  REQ_BGL = False
10217

    
10218
  def CheckArguments(self):
10219
    all_changes = [
10220
      self.op.ndparams,
10221
      self.op.alloc_policy,
10222
      ]
10223

    
10224
    if all_changes.count(None) == len(all_changes):
10225
      raise errors.OpPrereqError("Please pass at least one modification",
10226
                                 errors.ECODE_INVAL)
10227

    
10228
  def ExpandNames(self):
10229
    # This raises errors.OpPrereqError on its own:
10230
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10231

    
10232
    self.needed_locks = {
10233
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10234
      }
10235

    
10236
  def CheckPrereq(self):
10237
    """Check prerequisites.
10238

10239
    """
10240
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
10241

    
10242
    if self.group is None:
10243
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10244
                               (self.op.group_name, self.group_uuid))
10245

    
10246
    if self.op.ndparams:
10247
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
10248
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10249
      self.new_ndparams = new_ndparams
10250

    
10251
  def BuildHooksEnv(self):
10252
    """Build hooks env.
10253

10254
    """
10255
    env = {
10256
      "GROUP_NAME": self.op.group_name,
10257
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
10258
      }
10259
    mn = self.cfg.GetMasterNode()
10260
    return env, [mn], [mn]
10261

    
10262
  def Exec(self, feedback_fn):
10263
    """Modifies the node group.
10264

10265
    """
10266
    result = []
10267

    
10268
    if self.op.ndparams:
10269
      self.group.ndparams = self.new_ndparams
10270
      result.append(("ndparams", str(self.group.ndparams)))
10271

    
10272
    if self.op.alloc_policy:
10273
      self.group.alloc_policy = self.op.alloc_policy
10274

    
10275
    self.cfg.Update(self.group, feedback_fn)
10276
    return result
10277

    
10278

    
10279

    
10280
class LUGroupRemove(LogicalUnit):
10281
  HPATH = "group-remove"
10282
  HTYPE = constants.HTYPE_GROUP
10283
  REQ_BGL = False
10284

    
10285
  def ExpandNames(self):
10286
    # This will raises errors.OpPrereqError on its own:
10287
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10288
    self.needed_locks = {
10289
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10290
      }
10291

    
10292
  def CheckPrereq(self):
10293
    """Check prerequisites.
10294

10295
    This checks that the given group name exists as a node group, that is
10296
    empty (i.e., contains no nodes), and that is not the last group of the
10297
    cluster.
10298

10299
    """
10300
    # Verify that the group is empty.
10301
    group_nodes = [node.name
10302
                   for node in self.cfg.GetAllNodesInfo().values()
10303
                   if node.group == self.group_uuid]
10304

    
10305
    if group_nodes:
10306
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
10307
                                 " nodes: %s" %
10308
                                 (self.op.group_name,
10309
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
10310
                                 errors.ECODE_STATE)
10311

    
10312
    # Verify the cluster would not be left group-less.
10313
    if len(self.cfg.GetNodeGroupList()) == 1:
10314
      raise errors.OpPrereqError("Group '%s' is the last group in the cluster,"
10315
                                 " which cannot be left without at least one"
10316
                                 " group" % self.op.group_name,
10317
                                 errors.ECODE_STATE)
10318

    
10319
  def BuildHooksEnv(self):
10320
    """Build hooks env.
10321

10322
    """
10323
    env = {
10324
      "GROUP_NAME": self.op.group_name,
10325
      }
10326
    mn = self.cfg.GetMasterNode()
10327
    return env, [mn], [mn]
10328

    
10329
  def Exec(self, feedback_fn):
10330
    """Remove the node group.
10331

10332
    """
10333
    try:
10334
      self.cfg.RemoveNodeGroup(self.group_uuid)
10335
    except errors.ConfigurationError:
10336
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
10337
                               (self.op.group_name, self.group_uuid))
10338

    
10339
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10340

    
10341

    
10342
class LUGroupRename(LogicalUnit):
10343
  HPATH = "group-rename"
10344
  HTYPE = constants.HTYPE_GROUP
10345
  REQ_BGL = False
10346

    
10347
  def ExpandNames(self):
10348
    # This raises errors.OpPrereqError on its own:
10349
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.old_name)
10350

    
10351
    self.needed_locks = {
10352
      locking.LEVEL_NODEGROUP: [self.group_uuid],
10353
      }
10354

    
10355
  def CheckPrereq(self):
10356
    """Check prerequisites.
10357

10358
    This checks that the given old_name exists as a node group, and that
10359
    new_name doesn't.
10360

10361
    """
10362
    try:
10363
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
10364
    except errors.OpPrereqError:
10365
      pass
10366
    else:
10367
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
10368
                                 " node group (UUID: %s)" %
10369
                                 (self.op.new_name, new_name_uuid),
10370
                                 errors.ECODE_EXISTS)
10371

    
10372
  def BuildHooksEnv(self):
10373
    """Build hooks env.
10374

10375
    """
10376
    env = {
10377
      "OLD_NAME": self.op.old_name,
10378
      "NEW_NAME": self.op.new_name,
10379
      }
10380

    
10381
    mn = self.cfg.GetMasterNode()
10382
    all_nodes = self.cfg.GetAllNodesInfo()
10383
    run_nodes = [mn]
10384
    all_nodes.pop(mn, None)
10385

    
10386
    for node in all_nodes.values():
10387
      if node.group == self.group_uuid:
10388
        run_nodes.append(node.name)
10389

    
10390
    return env, run_nodes, run_nodes
10391

    
10392
  def Exec(self, feedback_fn):
10393
    """Rename the node group.
10394

10395
    """
10396
    group = self.cfg.GetNodeGroup(self.group_uuid)
10397

    
10398
    if group is None:
10399
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
10400
                               (self.op.old_name, self.group_uuid))
10401

    
10402
    group.name = self.op.new_name
10403
    self.cfg.Update(group, feedback_fn)
10404

    
10405
    return self.op.new_name
10406

    
10407

    
10408
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
10409
  """Generic tags LU.
10410

10411
  This is an abstract class which is the parent of all the other tags LUs.
10412

10413
  """
10414

    
10415
  def ExpandNames(self):
10416
    self.needed_locks = {}
10417
    if self.op.kind == constants.TAG_NODE:
10418
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
10419
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
10420
    elif self.op.kind == constants.TAG_INSTANCE:
10421
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
10422
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
10423

    
10424
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
10425
    # not possible to acquire the BGL based on opcode parameters)
10426

    
10427
  def CheckPrereq(self):
10428
    """Check prerequisites.
10429

10430
    """
10431
    if self.op.kind == constants.TAG_CLUSTER:
10432
      self.target = self.cfg.GetClusterInfo()
10433
    elif self.op.kind == constants.TAG_NODE:
10434
      self.target = self.cfg.GetNodeInfo(self.op.name)
10435
    elif self.op.kind == constants.TAG_INSTANCE:
10436
      self.target = self.cfg.GetInstanceInfo(self.op.name)
10437
    else:
10438
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
10439
                                 str(self.op.kind), errors.ECODE_INVAL)
10440

    
10441

    
10442
class LUTagsGet(TagsLU):
10443
  """Returns the tags of a given object.
10444

10445
  """
10446
  REQ_BGL = False
10447

    
10448
  def ExpandNames(self):
10449
    TagsLU.ExpandNames(self)
10450

    
10451
    # Share locks as this is only a read operation
10452
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10453

    
10454
  def Exec(self, feedback_fn):
10455
    """Returns the tag list.
10456

10457
    """
10458
    return list(self.target.GetTags())
10459

    
10460

    
10461
class LUTagsSearch(NoHooksLU):
10462
  """Searches the tags for a given pattern.
10463

10464
  """
10465
  REQ_BGL = False
10466

    
10467
  def ExpandNames(self):
10468
    self.needed_locks = {}
10469

    
10470
  def CheckPrereq(self):
10471
    """Check prerequisites.
10472

10473
    This checks the pattern passed for validity by compiling it.
10474

10475
    """
10476
    try:
10477
      self.re = re.compile(self.op.pattern)
10478
    except re.error, err:
10479
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
10480
                                 (self.op.pattern, err), errors.ECODE_INVAL)
10481

    
10482
  def Exec(self, feedback_fn):
10483
    """Returns the tag list.
10484

10485
    """
10486
    cfg = self.cfg
10487
    tgts = [("/cluster", cfg.GetClusterInfo())]
10488
    ilist = cfg.GetAllInstancesInfo().values()
10489
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
10490
    nlist = cfg.GetAllNodesInfo().values()
10491
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
10492
    results = []
10493
    for path, target in tgts:
10494
      for tag in target.GetTags():
10495
        if self.re.search(tag):
10496
          results.append((path, tag))
10497
    return results
10498

    
10499

    
10500
class LUTagsSet(TagsLU):
10501
  """Sets a tag on a given object.
10502

10503
  """
10504
  REQ_BGL = False
10505

    
10506
  def CheckPrereq(self):
10507
    """Check prerequisites.
10508

10509
    This checks the type and length of the tag name and value.
10510

10511
    """
10512
    TagsLU.CheckPrereq(self)
10513
    for tag in self.op.tags:
10514
      objects.TaggableObject.ValidateTag(tag)
10515

    
10516
  def Exec(self, feedback_fn):
10517
    """Sets the tag.
10518

10519
    """
10520
    try:
10521
      for tag in self.op.tags:
10522
        self.target.AddTag(tag)
10523
    except errors.TagError, err:
10524
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
10525
    self.cfg.Update(self.target, feedback_fn)
10526

    
10527

    
10528
class LUTagsDel(TagsLU):
10529
  """Delete a list of tags from a given object.
10530

10531
  """
10532
  REQ_BGL = False
10533

    
10534
  def CheckPrereq(self):
10535
    """Check prerequisites.
10536

10537
    This checks that we have the given tag.
10538

10539
    """
10540
    TagsLU.CheckPrereq(self)
10541
    for tag in self.op.tags:
10542
      objects.TaggableObject.ValidateTag(tag)
10543
    del_tags = frozenset(self.op.tags)
10544
    cur_tags = self.target.GetTags()
10545

    
10546
    diff_tags = del_tags - cur_tags
10547
    if diff_tags:
10548
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
10549
      raise errors.OpPrereqError("Tag(s) %s not found" %
10550
                                 (utils.CommaJoin(diff_names), ),
10551
                                 errors.ECODE_NOENT)
10552

    
10553
  def Exec(self, feedback_fn):
10554
    """Remove the tag from the object.
10555

10556
    """
10557
    for tag in self.op.tags:
10558
      self.target.RemoveTag(tag)
10559
    self.cfg.Update(self.target, feedback_fn)
10560

    
10561

    
10562
class LUTestDelay(NoHooksLU):
10563
  """Sleep for a specified amount of time.
10564

10565
  This LU sleeps on the master and/or nodes for a specified amount of
10566
  time.
10567

10568
  """
10569
  REQ_BGL = False
10570

    
10571
  def ExpandNames(self):
10572
    """Expand names and set required locks.
10573

10574
    This expands the node list, if any.
10575

10576
    """
10577
    self.needed_locks = {}
10578
    if self.op.on_nodes:
10579
      # _GetWantedNodes can be used here, but is not always appropriate to use
10580
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
10581
      # more information.
10582
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
10583
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
10584

    
10585
  def _TestDelay(self):
10586
    """Do the actual sleep.
10587

10588
    """
10589
    if self.op.on_master:
10590
      if not utils.TestDelay(self.op.duration):
10591
        raise errors.OpExecError("Error during master delay test")
10592
    if self.op.on_nodes:
10593
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
10594
      for node, node_result in result.items():
10595
        node_result.Raise("Failure during rpc call to node %s" % node)
10596

    
10597
  def Exec(self, feedback_fn):
10598
    """Execute the test delay opcode, with the wanted repetitions.
10599

10600
    """
10601
    if self.op.repeat == 0:
10602
      self._TestDelay()
10603
    else:
10604
      top_value = self.op.repeat - 1
10605
      for i in range(self.op.repeat):
10606
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
10607
        self._TestDelay()
10608

    
10609

    
10610
class LUTestJqueue(NoHooksLU):
10611
  """Utility LU to test some aspects of the job queue.
10612

10613
  """
10614
  REQ_BGL = False
10615

    
10616
  # Must be lower than default timeout for WaitForJobChange to see whether it
10617
  # notices changed jobs
10618
  _CLIENT_CONNECT_TIMEOUT = 20.0
10619
  _CLIENT_CONFIRM_TIMEOUT = 60.0
10620

    
10621
  @classmethod
10622
  def _NotifyUsingSocket(cls, cb, errcls):
10623
    """Opens a Unix socket and waits for another program to connect.
10624

10625
    @type cb: callable
10626
    @param cb: Callback to send socket name to client
10627
    @type errcls: class
10628
    @param errcls: Exception class to use for errors
10629

10630
    """
10631
    # Using a temporary directory as there's no easy way to create temporary
10632
    # sockets without writing a custom loop around tempfile.mktemp and
10633
    # socket.bind
10634
    tmpdir = tempfile.mkdtemp()
10635
    try:
10636
      tmpsock = utils.PathJoin(tmpdir, "sock")
10637

    
10638
      logging.debug("Creating temporary socket at %s", tmpsock)
10639
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
10640
      try:
10641
        sock.bind(tmpsock)
10642
        sock.listen(1)
10643

    
10644
        # Send details to client
10645
        cb(tmpsock)
10646

    
10647
        # Wait for client to connect before continuing
10648
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
10649
        try:
10650
          (conn, _) = sock.accept()
10651
        except socket.error, err:
10652
          raise errcls("Client didn't connect in time (%s)" % err)
10653
      finally:
10654
        sock.close()
10655
    finally:
10656
      # Remove as soon as client is connected
10657
      shutil.rmtree(tmpdir)
10658

    
10659
    # Wait for client to close
10660
    try:
10661
      try:
10662
        # pylint: disable-msg=E1101
10663
        # Instance of '_socketobject' has no ... member
10664
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10665
        conn.recv(1)
10666
      except socket.error, err:
10667
        raise errcls("Client failed to confirm notification (%s)" % err)
10668
    finally:
10669
      conn.close()
10670

    
10671
  def _SendNotification(self, test, arg, sockname):
10672
    """Sends a notification to the client.
10673

10674
    @type test: string
10675
    @param test: Test name
10676
    @param arg: Test argument (depends on test)
10677
    @type sockname: string
10678
    @param sockname: Socket path
10679

10680
    """
10681
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10682

    
10683
  def _Notify(self, prereq, test, arg):
10684
    """Notifies the client of a test.
10685

10686
    @type prereq: bool
10687
    @param prereq: Whether this is a prereq-phase test
10688
    @type test: string
10689
    @param test: Test name
10690
    @param arg: Test argument (depends on test)
10691

10692
    """
10693
    if prereq:
10694
      errcls = errors.OpPrereqError
10695
    else:
10696
      errcls = errors.OpExecError
10697

    
10698
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10699
                                                  test, arg),
10700
                                   errcls)
10701

    
10702
  def CheckArguments(self):
10703
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10704
    self.expandnames_calls = 0
10705

    
10706
  def ExpandNames(self):
10707
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10708
    if checkargs_calls < 1:
10709
      raise errors.ProgrammerError("CheckArguments was not called")
10710

    
10711
    self.expandnames_calls += 1
10712

    
10713
    if self.op.notify_waitlock:
10714
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10715

    
10716
    self.LogInfo("Expanding names")
10717

    
10718
    # Get lock on master node (just to get a lock, not for a particular reason)
10719
    self.needed_locks = {
10720
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10721
      }
10722

    
10723
  def Exec(self, feedback_fn):
10724
    if self.expandnames_calls < 1:
10725
      raise errors.ProgrammerError("ExpandNames was not called")
10726

    
10727
    if self.op.notify_exec:
10728
      self._Notify(False, constants.JQT_EXEC, None)
10729

    
10730
    self.LogInfo("Executing")
10731

    
10732
    if self.op.log_messages:
10733
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10734
      for idx, msg in enumerate(self.op.log_messages):
10735
        self.LogInfo("Sending log message %s", idx + 1)
10736
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10737
        # Report how many test messages have been sent
10738
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10739

    
10740
    if self.op.fail:
10741
      raise errors.OpExecError("Opcode failure was requested")
10742

    
10743
    return True
10744

    
10745

    
10746
class IAllocator(object):
10747
  """IAllocator framework.
10748

10749
  An IAllocator instance has three sets of attributes:
10750
    - cfg that is needed to query the cluster
10751
    - input data (all members of the _KEYS class attribute are required)
10752
    - four buffer attributes (in|out_data|text), that represent the
10753
      input (to the external script) in text and data structure format,
10754
      and the output from it, again in two formats
10755
    - the result variables from the script (success, info, nodes) for
10756
      easy usage
10757

10758
  """
10759
  # pylint: disable-msg=R0902
10760
  # lots of instance attributes
10761
  _ALLO_KEYS = [
10762
    "name", "mem_size", "disks", "disk_template",
10763
    "os", "tags", "nics", "vcpus", "hypervisor",
10764
    ]
10765
  _RELO_KEYS = [
10766
    "name", "relocate_from",
10767
    ]
10768
  _EVAC_KEYS = [
10769
    "evac_nodes",
10770
    ]
10771

    
10772
  def __init__(self, cfg, rpc, mode, **kwargs):
10773
    self.cfg = cfg
10774
    self.rpc = rpc
10775
    # init buffer variables
10776
    self.in_text = self.out_text = self.in_data = self.out_data = None
10777
    # init all input fields so that pylint is happy
10778
    self.mode = mode
10779
    self.mem_size = self.disks = self.disk_template = None
10780
    self.os = self.tags = self.nics = self.vcpus = None
10781
    self.hypervisor = None
10782
    self.relocate_from = None
10783
    self.name = None
10784
    self.evac_nodes = None
10785
    # computed fields
10786
    self.required_nodes = None
10787
    # init result fields
10788
    self.success = self.info = self.result = None
10789
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10790
      keyset = self._ALLO_KEYS
10791
      fn = self._AddNewInstance
10792
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10793
      keyset = self._RELO_KEYS
10794
      fn = self._AddRelocateInstance
10795
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10796
      keyset = self._EVAC_KEYS
10797
      fn = self._AddEvacuateNodes
10798
    else:
10799
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10800
                                   " IAllocator" % self.mode)
10801
    for key in kwargs:
10802
      if key not in keyset:
10803
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10804
                                     " IAllocator" % key)
10805
      setattr(self, key, kwargs[key])
10806

    
10807
    for key in keyset:
10808
      if key not in kwargs:
10809
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10810
                                     " IAllocator" % key)
10811
    self._BuildInputData(fn)
10812

    
10813
  def _ComputeClusterData(self):
10814
    """Compute the generic allocator input data.
10815

10816
    This is the data that is independent of the actual operation.
10817

10818
    """
10819
    cfg = self.cfg
10820
    cluster_info = cfg.GetClusterInfo()
10821
    # cluster data
10822
    data = {
10823
      "version": constants.IALLOCATOR_VERSION,
10824
      "cluster_name": cfg.GetClusterName(),
10825
      "cluster_tags": list(cluster_info.GetTags()),
10826
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10827
      # we don't have job IDs
10828
      }
10829
    ninfo = cfg.GetAllNodesInfo()
10830
    iinfo = cfg.GetAllInstancesInfo().values()
10831
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10832

    
10833
    # node data
10834
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
10835

    
10836
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10837
      hypervisor_name = self.hypervisor
10838
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10839
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10840
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10841
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10842

    
10843
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10844
                                        hypervisor_name)
10845
    node_iinfo = \
10846
      self.rpc.call_all_instances_info(node_list,
10847
                                       cluster_info.enabled_hypervisors)
10848

    
10849
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
10850

    
10851
    config_ndata = self._ComputeBasicNodeData(ninfo)
10852
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
10853
                                                 i_list, config_ndata)
10854
    assert len(data["nodes"]) == len(ninfo), \
10855
        "Incomplete node data computed"
10856

    
10857
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
10858

    
10859
    self.in_data = data
10860

    
10861
  @staticmethod
10862
  def _ComputeNodeGroupData(cfg):
10863
    """Compute node groups data.
10864

10865
    """
10866
    ng = {}
10867
    for guuid, gdata in cfg.GetAllNodeGroupsInfo().items():
10868
      ng[guuid] = {
10869
        "name": gdata.name,
10870
        "alloc_policy": gdata.alloc_policy,
10871
        }
10872
    return ng
10873

    
10874
  @staticmethod
10875
  def _ComputeBasicNodeData(node_cfg):
10876
    """Compute global node data.
10877

10878
    @rtype: dict
10879
    @returns: a dict of name: (node dict, node config)
10880

10881
    """
10882
    node_results = {}
10883
    for ninfo in node_cfg.values():
10884
      # fill in static (config-based) values
10885
      pnr = {
10886
        "tags": list(ninfo.GetTags()),
10887
        "primary_ip": ninfo.primary_ip,
10888
        "secondary_ip": ninfo.secondary_ip,
10889
        "offline": ninfo.offline,
10890
        "drained": ninfo.drained,
10891
        "master_candidate": ninfo.master_candidate,
10892
        "group": ninfo.group,
10893
        "master_capable": ninfo.master_capable,
10894
        "vm_capable": ninfo.vm_capable,
10895
        }
10896

    
10897
      node_results[ninfo.name] = pnr
10898

    
10899
    return node_results
10900

    
10901
  @staticmethod
10902
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
10903
                              node_results):
10904
    """Compute global node data.
10905

10906
    @param node_results: the basic node structures as filled from the config
10907

10908
    """
10909
    # make a copy of the current dict
10910
    node_results = dict(node_results)
10911
    for nname, nresult in node_data.items():
10912
      assert nname in node_results, "Missing basic data for node %s" % nname
10913
      ninfo = node_cfg[nname]
10914

    
10915
      if not (ninfo.offline or ninfo.drained):
10916
        nresult.Raise("Can't get data for node %s" % nname)
10917
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10918
                                nname)
10919
        remote_info = nresult.payload
10920

    
10921
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10922
                     'vg_size', 'vg_free', 'cpu_total']:
10923
          if attr not in remote_info:
10924
            raise errors.OpExecError("Node '%s' didn't return attribute"
10925
                                     " '%s'" % (nname, attr))
10926
          if not isinstance(remote_info[attr], int):
10927
            raise errors.OpExecError("Node '%s' returned invalid value"
10928
                                     " for '%s': %s" %
10929
                                     (nname, attr, remote_info[attr]))
10930
        # compute memory used by primary instances
10931
        i_p_mem = i_p_up_mem = 0
10932
        for iinfo, beinfo in i_list:
10933
          if iinfo.primary_node == nname:
10934
            i_p_mem += beinfo[constants.BE_MEMORY]
10935
            if iinfo.name not in node_iinfo[nname].payload:
10936
              i_used_mem = 0
10937
            else:
10938
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10939
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10940
            remote_info['memory_free'] -= max(0, i_mem_diff)
10941

    
10942
            if iinfo.admin_up:
10943
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10944

    
10945
        # compute memory used by instances
10946
        pnr_dyn = {
10947
          "total_memory": remote_info['memory_total'],
10948
          "reserved_memory": remote_info['memory_dom0'],
10949
          "free_memory": remote_info['memory_free'],
10950
          "total_disk": remote_info['vg_size'],
10951
          "free_disk": remote_info['vg_free'],
10952
          "total_cpus": remote_info['cpu_total'],
10953
          "i_pri_memory": i_p_mem,
10954
          "i_pri_up_memory": i_p_up_mem,
10955
          }
10956
        pnr_dyn.update(node_results[nname])
10957

    
10958
      node_results[nname] = pnr_dyn
10959

    
10960
    return node_results
10961

    
10962
  @staticmethod
10963
  def _ComputeInstanceData(cluster_info, i_list):
10964
    """Compute global instance data.
10965

10966
    """
10967
    instance_data = {}
10968
    for iinfo, beinfo in i_list:
10969
      nic_data = []
10970
      for nic in iinfo.nics:
10971
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10972
        nic_dict = {"mac": nic.mac,
10973
                    "ip": nic.ip,
10974
                    "mode": filled_params[constants.NIC_MODE],
10975
                    "link": filled_params[constants.NIC_LINK],
10976
                   }
10977
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10978
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10979
        nic_data.append(nic_dict)
10980
      pir = {
10981
        "tags": list(iinfo.GetTags()),
10982
        "admin_up": iinfo.admin_up,
10983
        "vcpus": beinfo[constants.BE_VCPUS],
10984
        "memory": beinfo[constants.BE_MEMORY],
10985
        "os": iinfo.os,
10986
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10987
        "nics": nic_data,
10988
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10989
        "disk_template": iinfo.disk_template,
10990
        "hypervisor": iinfo.hypervisor,
10991
        }
10992
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10993
                                                 pir["disks"])
10994
      instance_data[iinfo.name] = pir
10995

    
10996
    return instance_data
10997

    
10998
  def _AddNewInstance(self):
10999
    """Add new instance data to allocator structure.
11000

11001
    This in combination with _AllocatorGetClusterData will create the
11002
    correct structure needed as input for the allocator.
11003

11004
    The checks for the completeness of the opcode must have already been
11005
    done.
11006

11007
    """
11008
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
11009

    
11010
    if self.disk_template in constants.DTS_NET_MIRROR:
11011
      self.required_nodes = 2
11012
    else:
11013
      self.required_nodes = 1
11014
    request = {
11015
      "name": self.name,
11016
      "disk_template": self.disk_template,
11017
      "tags": self.tags,
11018
      "os": self.os,
11019
      "vcpus": self.vcpus,
11020
      "memory": self.mem_size,
11021
      "disks": self.disks,
11022
      "disk_space_total": disk_space,
11023
      "nics": self.nics,
11024
      "required_nodes": self.required_nodes,
11025
      }
11026
    return request
11027

    
11028
  def _AddRelocateInstance(self):
11029
    """Add relocate instance data to allocator structure.
11030

11031
    This in combination with _IAllocatorGetClusterData will create the
11032
    correct structure needed as input for the allocator.
11033

11034
    The checks for the completeness of the opcode must have already been
11035
    done.
11036

11037
    """
11038
    instance = self.cfg.GetInstanceInfo(self.name)
11039
    if instance is None:
11040
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
11041
                                   " IAllocator" % self.name)
11042

    
11043
    if instance.disk_template not in constants.DTS_NET_MIRROR:
11044
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
11045
                                 errors.ECODE_INVAL)
11046

    
11047
    if len(instance.secondary_nodes) != 1:
11048
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
11049
                                 errors.ECODE_STATE)
11050

    
11051
    self.required_nodes = 1
11052
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
11053
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
11054

    
11055
    request = {
11056
      "name": self.name,
11057
      "disk_space_total": disk_space,
11058
      "required_nodes": self.required_nodes,
11059
      "relocate_from": self.relocate_from,
11060
      }
11061
    return request
11062

    
11063
  def _AddEvacuateNodes(self):
11064
    """Add evacuate nodes data to allocator structure.
11065

11066
    """
11067
    request = {
11068
      "evac_nodes": self.evac_nodes
11069
      }
11070
    return request
11071

    
11072
  def _BuildInputData(self, fn):
11073
    """Build input data structures.
11074

11075
    """
11076
    self._ComputeClusterData()
11077

    
11078
    request = fn()
11079
    request["type"] = self.mode
11080
    self.in_data["request"] = request
11081

    
11082
    self.in_text = serializer.Dump(self.in_data)
11083

    
11084
  def Run(self, name, validate=True, call_fn=None):
11085
    """Run an instance allocator and return the results.
11086

11087
    """
11088
    if call_fn is None:
11089
      call_fn = self.rpc.call_iallocator_runner
11090

    
11091
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
11092
    result.Raise("Failure while running the iallocator script")
11093

    
11094
    self.out_text = result.payload
11095
    if validate:
11096
      self._ValidateResult()
11097

    
11098
  def _ValidateResult(self):
11099
    """Process the allocator results.
11100

11101
    This will process and if successful save the result in
11102
    self.out_data and the other parameters.
11103

11104
    """
11105
    try:
11106
      rdict = serializer.Load(self.out_text)
11107
    except Exception, err:
11108
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
11109

    
11110
    if not isinstance(rdict, dict):
11111
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
11112

    
11113
    # TODO: remove backwards compatiblity in later versions
11114
    if "nodes" in rdict and "result" not in rdict:
11115
      rdict["result"] = rdict["nodes"]
11116
      del rdict["nodes"]
11117

    
11118
    for key in "success", "info", "result":
11119
      if key not in rdict:
11120
        raise errors.OpExecError("Can't parse iallocator results:"
11121
                                 " missing key '%s'" % key)
11122
      setattr(self, key, rdict[key])
11123

    
11124
    if not isinstance(rdict["result"], list):
11125
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
11126
                               " is not a list")
11127
    self.out_data = rdict
11128

    
11129

    
11130
class LUTestAllocator(NoHooksLU):
11131
  """Run allocator tests.
11132

11133
  This LU runs the allocator tests
11134

11135
  """
11136
  def CheckPrereq(self):
11137
    """Check prerequisites.
11138

11139
    This checks the opcode parameters depending on the director and mode test.
11140

11141
    """
11142
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11143
      for attr in ["mem_size", "disks", "disk_template",
11144
                   "os", "tags", "nics", "vcpus"]:
11145
        if not hasattr(self.op, attr):
11146
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
11147
                                     attr, errors.ECODE_INVAL)
11148
      iname = self.cfg.ExpandInstanceName(self.op.name)
11149
      if iname is not None:
11150
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
11151
                                   iname, errors.ECODE_EXISTS)
11152
      if not isinstance(self.op.nics, list):
11153
        raise errors.OpPrereqError("Invalid parameter 'nics'",
11154
                                   errors.ECODE_INVAL)
11155
      if not isinstance(self.op.disks, list):
11156
        raise errors.OpPrereqError("Invalid parameter 'disks'",
11157
                                   errors.ECODE_INVAL)
11158
      for row in self.op.disks:
11159
        if (not isinstance(row, dict) or
11160
            "size" not in row or
11161
            not isinstance(row["size"], int) or
11162
            "mode" not in row or
11163
            row["mode"] not in ['r', 'w']):
11164
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
11165
                                     " parameter", errors.ECODE_INVAL)
11166
      if self.op.hypervisor is None:
11167
        self.op.hypervisor = self.cfg.GetHypervisorType()
11168
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11169
      fname = _ExpandInstanceName(self.cfg, self.op.name)
11170
      self.op.name = fname
11171
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
11172
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11173
      if not hasattr(self.op, "evac_nodes"):
11174
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
11175
                                   " opcode input", errors.ECODE_INVAL)
11176
    else:
11177
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
11178
                                 self.op.mode, errors.ECODE_INVAL)
11179

    
11180
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
11181
      if self.op.allocator is None:
11182
        raise errors.OpPrereqError("Missing allocator name",
11183
                                   errors.ECODE_INVAL)
11184
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
11185
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
11186
                                 self.op.direction, errors.ECODE_INVAL)
11187

    
11188
  def Exec(self, feedback_fn):
11189
    """Run the allocator test.
11190

11191
    """
11192
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
11193
      ial = IAllocator(self.cfg, self.rpc,
11194
                       mode=self.op.mode,
11195
                       name=self.op.name,
11196
                       mem_size=self.op.mem_size,
11197
                       disks=self.op.disks,
11198
                       disk_template=self.op.disk_template,
11199
                       os=self.op.os,
11200
                       tags=self.op.tags,
11201
                       nics=self.op.nics,
11202
                       vcpus=self.op.vcpus,
11203
                       hypervisor=self.op.hypervisor,
11204
                       )
11205
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
11206
      ial = IAllocator(self.cfg, self.rpc,
11207
                       mode=self.op.mode,
11208
                       name=self.op.name,
11209
                       relocate_from=list(self.relocate_from),
11210
                       )
11211
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
11212
      ial = IAllocator(self.cfg, self.rpc,
11213
                       mode=self.op.mode,
11214
                       evac_nodes=self.op.evac_nodes)
11215
    else:
11216
      raise errors.ProgrammerError("Uncatched mode %s in"
11217
                                   " LUTestAllocator.Exec", self.op.mode)
11218

    
11219
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
11220
      result = ial.in_text
11221
    else:
11222
      ial.Run(self.op.allocator, validate=False)
11223
      result = ial.out_text
11224
    return result
11225

    
11226

    
11227
#: Query type implementations
11228
_QUERY_IMPL = {
11229
  constants.QR_INSTANCE: _InstanceQuery,
11230
  constants.QR_NODE: _NodeQuery,
11231
  constants.QR_GROUP: _GroupQuery,
11232
  }
11233

    
11234

    
11235
def _GetQueryImplementation(name):
11236
  """Returns the implemtnation for a query type.
11237

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

11240
  """
11241
  try:
11242
    return _QUERY_IMPL[name]
11243
  except KeyError:
11244
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
11245
                               errors.ECODE_INVAL)