Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 895eb320

History | View | Annotate | Download (338.2 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008 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
25

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

    
29
import os
30
import os.path
31
import time
32
import re
33
import platform
34
import logging
35
import copy
36
import OpenSSL
37

    
38
from ganeti import ssh
39
from ganeti import utils
40
from ganeti import errors
41
from ganeti import hypervisor
42
from ganeti import locking
43
from ganeti import constants
44
from ganeti import objects
45
from ganeti import serializer
46
from ganeti import ssconf
47
from ganeti import uidpool
48
from ganeti import compat
49
from ganeti import masterd
50

    
51
import ganeti.masterd.instance # pylint: disable-msg=W0611
52

    
53

    
54
class LogicalUnit(object):
55
  """Logical Unit base class.
56

57
  Subclasses must follow these rules:
58
    - implement ExpandNames
59
    - implement CheckPrereq (except when tasklets are used)
60
    - implement Exec (except when tasklets are used)
61
    - implement BuildHooksEnv
62
    - redefine HPATH and HTYPE
63
    - optionally redefine their run requirements:
64
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
65

66
  Note that all commands require root permissions.
67

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

71
  """
72
  HPATH = None
73
  HTYPE = None
74
  _OP_REQP = []
75
  REQ_BGL = True
76

    
77
  def __init__(self, processor, op, context, rpc):
78
    """Constructor for LogicalUnit.
79

80
    This needs to be overridden in derived classes in order to check op
81
    validity.
82

83
    """
84
    self.proc = processor
85
    self.op = op
86
    self.cfg = context.cfg
87
    self.context = context
88
    self.rpc = rpc
89
    # Dicts used to declare locking needs to mcpu
90
    self.needed_locks = None
91
    self.acquired_locks = {}
92
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
93
    self.add_locks = {}
94
    self.remove_locks = {}
95
    # Used to force good behavior when calling helper functions
96
    self.recalculate_locks = {}
97
    self.__ssh = None
98
    # logging
99
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
100
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
101
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
102
    # support for dry-run
103
    self.dry_run_result = None
104
    # support for generic debug attribute
105
    if (not hasattr(self.op, "debug_level") or
106
        not isinstance(self.op.debug_level, int)):
107
      self.op.debug_level = 0
108

    
109
    # Tasklets
110
    self.tasklets = None
111

    
112
    for attr_name in self._OP_REQP:
113
      attr_val = getattr(op, attr_name, None)
114
      if attr_val is None:
115
        raise errors.OpPrereqError("Required parameter '%s' missing" %
116
                                   attr_name, errors.ECODE_INVAL)
117

    
118
    self.CheckArguments()
119

    
120
  def __GetSSH(self):
121
    """Returns the SshRunner object
122

123
    """
124
    if not self.__ssh:
125
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
126
    return self.__ssh
127

    
128
  ssh = property(fget=__GetSSH)
129

    
130
  def CheckArguments(self):
131
    """Check syntactic validity for the opcode arguments.
132

133
    This method is for doing a simple syntactic check and ensure
134
    validity of opcode parameters, without any cluster-related
135
    checks. While the same can be accomplished in ExpandNames and/or
136
    CheckPrereq, doing these separate is better because:
137

138
      - ExpandNames is left as as purely a lock-related function
139
      - CheckPrereq is run after we have acquired locks (and possible
140
        waited for them)
141

142
    The function is allowed to change the self.op attribute so that
143
    later methods can no longer worry about missing parameters.
144

145
    """
146
    pass
147

    
148
  def ExpandNames(self):
149
    """Expand names for this LU.
150

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

156
    LUs which implement this method must also populate the self.needed_locks
157
    member, as a dict with lock levels as keys, and a list of needed lock names
158
    as values. Rules:
159

160
      - use an empty dict if you don't need any lock
161
      - if you don't need any lock at a particular level omit that level
162
      - don't put anything for the BGL level
163
      - if you want all locks at a level use locking.ALL_SET as a value
164

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

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

173
    Examples::
174

175
      # Acquire all nodes and one instance
176
      self.needed_locks = {
177
        locking.LEVEL_NODE: locking.ALL_SET,
178
        locking.LEVEL_INSTANCE: ['instance1.example.tld'],
179
      }
180
      # Acquire just two nodes
181
      self.needed_locks = {
182
        locking.LEVEL_NODE: ['node1.example.tld', 'node2.example.tld'],
183
      }
184
      # Acquire no locks
185
      self.needed_locks = {} # No, you can't leave it to the default value None
186

187
    """
188
    # The implementation of this method is mandatory only if the new LU is
189
    # concurrent, so that old LUs don't need to be changed all at the same
190
    # time.
191
    if self.REQ_BGL:
192
      self.needed_locks = {} # Exclusive LUs don't need locks.
193
    else:
194
      raise NotImplementedError
195

    
196
  def DeclareLocks(self, level):
197
    """Declare LU locking needs for a level
198

199
    While most LUs can just declare their locking needs at ExpandNames time,
200
    sometimes there's the need to calculate some locks after having acquired
201
    the ones before. This function is called just before acquiring locks at a
202
    particular level, but after acquiring the ones at lower levels, and permits
203
    such calculations. It can be used to modify self.needed_locks, and by
204
    default it does nothing.
205

206
    This function is only called if you have something already set in
207
    self.needed_locks for the level.
208

209
    @param level: Locking level which is going to be locked
210
    @type level: member of ganeti.locking.LEVELS
211

212
    """
213

    
214
  def CheckPrereq(self):
215
    """Check prerequisites for this LU.
216

217
    This method should check that the prerequisites for the execution
218
    of this LU are fulfilled. It can do internode communication, but
219
    it should be idempotent - no cluster or system changes are
220
    allowed.
221

222
    The method should raise errors.OpPrereqError in case something is
223
    not fulfilled. Its return value is ignored.
224

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

228
    """
229
    if self.tasklets is not None:
230
      for (idx, tl) in enumerate(self.tasklets):
231
        logging.debug("Checking prerequisites for tasklet %s/%s",
232
                      idx + 1, len(self.tasklets))
233
        tl.CheckPrereq()
234
    else:
235
      raise NotImplementedError
236

    
237
  def Exec(self, feedback_fn):
238
    """Execute the LU.
239

240
    This method should implement the actual work. It should raise
241
    errors.OpExecError for failures that are somewhat dealt with in
242
    code, or expected.
243

244
    """
245
    if self.tasklets is not None:
246
      for (idx, tl) in enumerate(self.tasklets):
247
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
248
        tl.Exec(feedback_fn)
249
    else:
250
      raise NotImplementedError
251

    
252
  def BuildHooksEnv(self):
253
    """Build hooks environment for this LU.
254

255
    This method should return a three-node tuple consisting of: a dict
256
    containing the environment that will be used for running the
257
    specific hook for this LU, a list of node names on which the hook
258
    should run before the execution, and a list of node names on which
259
    the hook should run after the execution.
260

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

266
    No nodes should be returned as an empty list (and not None).
267

268
    Note that if the HPATH for a LU class is None, this function will
269
    not be called.
270

271
    """
272
    raise NotImplementedError
273

    
274
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
275
    """Notify the LU about the results of its hooks.
276

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

283
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
284
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
285
    @param hook_results: the results of the multi-node hooks rpc call
286
    @param feedback_fn: function used send feedback back to the caller
287
    @param lu_result: the previous Exec result this LU had, or None
288
        in the PRE phase
289
    @return: the new Exec result, based on the previous result
290
        and hook results
291

292
    """
293
    # API must be kept, thus we ignore the unused argument and could
294
    # be a function warnings
295
    # pylint: disable-msg=W0613,R0201
296
    return lu_result
297

    
298
  def _ExpandAndLockInstance(self):
299
    """Helper function to expand and lock an instance.
300

301
    Many LUs that work on an instance take its name in self.op.instance_name
302
    and need to expand it and then declare the expanded name for locking. This
303
    function does it, and then updates self.op.instance_name to the expanded
304
    name. It also initializes needed_locks as a dict, if this hasn't been done
305
    before.
306

307
    """
308
    if self.needed_locks is None:
309
      self.needed_locks = {}
310
    else:
311
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
312
        "_ExpandAndLockInstance called with instance-level locks set"
313
    self.op.instance_name = _ExpandInstanceName(self.cfg,
314
                                                self.op.instance_name)
315
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
316

    
317
  def _LockInstancesNodes(self, primary_only=False):
318
    """Helper function to declare instances' nodes for locking.
319

320
    This function should be called after locking one or more instances to lock
321
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
322
    with all primary or secondary nodes for instances already locked and
323
    present in self.needed_locks[locking.LEVEL_INSTANCE].
324

325
    It should be called from DeclareLocks, and for safety only works if
326
    self.recalculate_locks[locking.LEVEL_NODE] is set.
327

328
    In the future it may grow parameters to just lock some instance's nodes, or
329
    to just lock primaries or secondary nodes, if needed.
330

331
    If should be called in DeclareLocks in a way similar to::
332

333
      if level == locking.LEVEL_NODE:
334
        self._LockInstancesNodes()
335

336
    @type primary_only: boolean
337
    @param primary_only: only lock primary nodes of locked instances
338

339
    """
340
    assert locking.LEVEL_NODE in self.recalculate_locks, \
341
      "_LockInstancesNodes helper function called with no nodes to recalculate"
342

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

    
345
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
346
    # future we might want to have different behaviors depending on the value
347
    # of self.recalculate_locks[locking.LEVEL_NODE]
348
    wanted_nodes = []
349
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
350
      instance = self.context.cfg.GetInstanceInfo(instance_name)
351
      wanted_nodes.append(instance.primary_node)
352
      if not primary_only:
353
        wanted_nodes.extend(instance.secondary_nodes)
354

    
355
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
356
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
357
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
358
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
359

    
360
    del self.recalculate_locks[locking.LEVEL_NODE]
361

    
362

    
363
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
364
  """Simple LU which runs no hooks.
365

366
  This LU is intended as a parent for other LogicalUnits which will
367
  run no hooks, in order to reduce duplicate code.
368

369
  """
370
  HPATH = None
371
  HTYPE = None
372

    
373
  def BuildHooksEnv(self):
374
    """Empty BuildHooksEnv for NoHooksLu.
375

376
    This just raises an error.
377

378
    """
379
    assert False, "BuildHooksEnv called for NoHooksLUs"
380

    
381

    
382
class Tasklet:
383
  """Tasklet base class.
384

385
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
386
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
387
  tasklets know nothing about locks.
388

389
  Subclasses must follow these rules:
390
    - Implement CheckPrereq
391
    - Implement Exec
392

393
  """
394
  def __init__(self, lu):
395
    self.lu = lu
396

    
397
    # Shortcuts
398
    self.cfg = lu.cfg
399
    self.rpc = lu.rpc
400

    
401
  def CheckPrereq(self):
402
    """Check prerequisites for this tasklets.
403

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

408
    The method should raise errors.OpPrereqError in case something is not
409
    fulfilled. Its return value is ignored.
410

411
    This method should also update all parameters to their canonical form if it
412
    hasn't been done before.
413

414
    """
415
    raise NotImplementedError
416

    
417
  def Exec(self, feedback_fn):
418
    """Execute the tasklet.
419

420
    This method should implement the actual work. It should raise
421
    errors.OpExecError for failures that are somewhat dealt with in code, or
422
    expected.
423

424
    """
425
    raise NotImplementedError
426

    
427

    
428
def _GetWantedNodes(lu, nodes):
429
  """Returns list of checked and expanded node names.
430

431
  @type lu: L{LogicalUnit}
432
  @param lu: the logical unit on whose behalf we execute
433
  @type nodes: list
434
  @param nodes: list of node names or None for all nodes
435
  @rtype: list
436
  @return: the list of nodes, sorted
437
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
438

439
  """
440
  if not isinstance(nodes, list):
441
    raise errors.OpPrereqError("Invalid argument type 'nodes'",
442
                               errors.ECODE_INVAL)
443

    
444
  if not nodes:
445
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
446
      " non-empty list of nodes whose name is to be expanded.")
447

    
448
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
449
  return utils.NiceSort(wanted)
450

    
451

    
452
def _GetWantedInstances(lu, instances):
453
  """Returns list of checked and expanded instance names.
454

455
  @type lu: L{LogicalUnit}
456
  @param lu: the logical unit on whose behalf we execute
457
  @type instances: list
458
  @param instances: list of instance names or None for all instances
459
  @rtype: list
460
  @return: the list of instances, sorted
461
  @raise errors.OpPrereqError: if the instances parameter is wrong type
462
  @raise errors.OpPrereqError: if any of the passed instances is not found
463

464
  """
465
  if not isinstance(instances, list):
466
    raise errors.OpPrereqError("Invalid argument type 'instances'",
467
                               errors.ECODE_INVAL)
468

    
469
  if instances:
470
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
471
  else:
472
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
473
  return wanted
474

    
475

    
476
def _CheckOutputFields(static, dynamic, selected):
477
  """Checks whether all selected fields are valid.
478

479
  @type static: L{utils.FieldSet}
480
  @param static: static fields set
481
  @type dynamic: L{utils.FieldSet}
482
  @param dynamic: dynamic fields set
483

484
  """
485
  f = utils.FieldSet()
486
  f.Extend(static)
487
  f.Extend(dynamic)
488

    
489
  delta = f.NonMatching(selected)
490
  if delta:
491
    raise errors.OpPrereqError("Unknown output fields selected: %s"
492
                               % ",".join(delta), errors.ECODE_INVAL)
493

    
494

    
495
def _CheckBooleanOpField(op, name):
496
  """Validates boolean opcode parameters.
497

498
  This will ensure that an opcode parameter is either a boolean value,
499
  or None (but that it always exists).
500

501
  """
502
  val = getattr(op, name, None)
503
  if not (val is None or isinstance(val, bool)):
504
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
505
                               (name, str(val)), errors.ECODE_INVAL)
506
  setattr(op, name, val)
507

    
508

    
509
def _CheckGlobalHvParams(params):
510
  """Validates that given hypervisor params are not global ones.
511

512
  This will ensure that instances don't get customised versions of
513
  global params.
514

515
  """
516
  used_globals = constants.HVC_GLOBALS.intersection(params)
517
  if used_globals:
518
    msg = ("The following hypervisor parameters are global and cannot"
519
           " be customized at instance level, please modify them at"
520
           " cluster level: %s" % utils.CommaJoin(used_globals))
521
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
522

    
523

    
524
def _CheckNodeOnline(lu, node):
525
  """Ensure that a given node is online.
526

527
  @param lu: the LU on behalf of which we make the check
528
  @param node: the node to check
529
  @raise errors.OpPrereqError: if the node is offline
530

531
  """
532
  if lu.cfg.GetNodeInfo(node).offline:
533
    raise errors.OpPrereqError("Can't use offline node %s" % node,
534
                               errors.ECODE_INVAL)
535

    
536

    
537
def _CheckNodeNotDrained(lu, node):
538
  """Ensure that a given node is not drained.
539

540
  @param lu: the LU on behalf of which we make the check
541
  @param node: the node to check
542
  @raise errors.OpPrereqError: if the node is drained
543

544
  """
545
  if lu.cfg.GetNodeInfo(node).drained:
546
    raise errors.OpPrereqError("Can't use drained node %s" % node,
547
                               errors.ECODE_INVAL)
548

    
549

    
550
def _CheckNodeHasOS(lu, node, os_name, force_variant):
551
  """Ensure that a node supports a given OS.
552

553
  @param lu: the LU on behalf of which we make the check
554
  @param node: the node to check
555
  @param os_name: the OS to query about
556
  @param force_variant: whether to ignore variant errors
557
  @raise errors.OpPrereqError: if the node is not supporting the OS
558

559
  """
560
  result = lu.rpc.call_os_get(node, os_name)
561
  result.Raise("OS '%s' not in supported OS list for node %s" %
562
               (os_name, node),
563
               prereq=True, ecode=errors.ECODE_INVAL)
564
  if not force_variant:
565
    _CheckOSVariant(result.payload, os_name)
566

    
567

    
568
def _RequireFileStorage():
569
  """Checks that file storage is enabled.
570

571
  @raise errors.OpPrereqError: when file storage is disabled
572

573
  """
574
  if not constants.ENABLE_FILE_STORAGE:
575
    raise errors.OpPrereqError("File storage disabled at configure time",
576
                               errors.ECODE_INVAL)
577

    
578

    
579
def _CheckDiskTemplate(template):
580
  """Ensure a given disk template is valid.
581

582
  """
583
  if template not in constants.DISK_TEMPLATES:
584
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
585
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
586
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
587
  if template == constants.DT_FILE:
588
    _RequireFileStorage()
589

    
590

    
591
def _CheckStorageType(storage_type):
592
  """Ensure a given storage type is valid.
593

594
  """
595
  if storage_type not in constants.VALID_STORAGE_TYPES:
596
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
597
                               errors.ECODE_INVAL)
598
  if storage_type == constants.ST_FILE:
599
    _RequireFileStorage()
600

    
601

    
602

    
603
def _CheckInstanceDown(lu, instance, reason):
604
  """Ensure that an instance is not running."""
605
  if instance.admin_up:
606
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
607
                               (instance.name, reason), errors.ECODE_STATE)
608

    
609
  pnode = instance.primary_node
610
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
611
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
612
              prereq=True, ecode=errors.ECODE_ENVIRON)
613

    
614
  if instance.name in ins_l.payload:
615
    raise errors.OpPrereqError("Instance %s is running, %s" %
616
                               (instance.name, reason), errors.ECODE_STATE)
617

    
618

    
619
def _ExpandItemName(fn, name, kind):
620
  """Expand an item name.
621

622
  @param fn: the function to use for expansion
623
  @param name: requested item name
624
  @param kind: text description ('Node' or 'Instance')
625
  @return: the resolved (full) name
626
  @raise errors.OpPrereqError: if the item is not found
627

628
  """
629
  full_name = fn(name)
630
  if full_name is None:
631
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
632
                               errors.ECODE_NOENT)
633
  return full_name
634

    
635

    
636
def _ExpandNodeName(cfg, name):
637
  """Wrapper over L{_ExpandItemName} for nodes."""
638
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
639

    
640

    
641
def _ExpandInstanceName(cfg, name):
642
  """Wrapper over L{_ExpandItemName} for instance."""
643
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
644

    
645

    
646
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
647
                          memory, vcpus, nics, disk_template, disks,
648
                          bep, hvp, hypervisor_name):
649
  """Builds instance related env variables for hooks
650

651
  This builds the hook environment from individual variables.
652

653
  @type name: string
654
  @param name: the name of the instance
655
  @type primary_node: string
656
  @param primary_node: the name of the instance's primary node
657
  @type secondary_nodes: list
658
  @param secondary_nodes: list of secondary nodes as strings
659
  @type os_type: string
660
  @param os_type: the name of the instance's OS
661
  @type status: boolean
662
  @param status: the should_run status of the instance
663
  @type memory: string
664
  @param memory: the memory size of the instance
665
  @type vcpus: string
666
  @param vcpus: the count of VCPUs the instance has
667
  @type nics: list
668
  @param nics: list of tuples (ip, mac, mode, link) representing
669
      the NICs the instance has
670
  @type disk_template: string
671
  @param disk_template: the disk template of the instance
672
  @type disks: list
673
  @param disks: the list of (size, mode) pairs
674
  @type bep: dict
675
  @param bep: the backend parameters for the instance
676
  @type hvp: dict
677
  @param hvp: the hypervisor parameters for the instance
678
  @type hypervisor_name: string
679
  @param hypervisor_name: the hypervisor for the instance
680
  @rtype: dict
681
  @return: the hook environment for this instance
682

683
  """
684
  if status:
685
    str_status = "up"
686
  else:
687
    str_status = "down"
688
  env = {
689
    "OP_TARGET": name,
690
    "INSTANCE_NAME": name,
691
    "INSTANCE_PRIMARY": primary_node,
692
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
693
    "INSTANCE_OS_TYPE": os_type,
694
    "INSTANCE_STATUS": str_status,
695
    "INSTANCE_MEMORY": memory,
696
    "INSTANCE_VCPUS": vcpus,
697
    "INSTANCE_DISK_TEMPLATE": disk_template,
698
    "INSTANCE_HYPERVISOR": hypervisor_name,
699
  }
700

    
701
  if nics:
702
    nic_count = len(nics)
703
    for idx, (ip, mac, mode, link) in enumerate(nics):
704
      if ip is None:
705
        ip = ""
706
      env["INSTANCE_NIC%d_IP" % idx] = ip
707
      env["INSTANCE_NIC%d_MAC" % idx] = mac
708
      env["INSTANCE_NIC%d_MODE" % idx] = mode
709
      env["INSTANCE_NIC%d_LINK" % idx] = link
710
      if mode == constants.NIC_MODE_BRIDGED:
711
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
712
  else:
713
    nic_count = 0
714

    
715
  env["INSTANCE_NIC_COUNT"] = nic_count
716

    
717
  if disks:
718
    disk_count = len(disks)
719
    for idx, (size, mode) in enumerate(disks):
720
      env["INSTANCE_DISK%d_SIZE" % idx] = size
721
      env["INSTANCE_DISK%d_MODE" % idx] = mode
722
  else:
723
    disk_count = 0
724

    
725
  env["INSTANCE_DISK_COUNT"] = disk_count
726

    
727
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
728
    for key, value in source.items():
729
      env["INSTANCE_%s_%s" % (kind, key)] = value
730

    
731
  return env
732

    
733

    
734
def _NICListToTuple(lu, nics):
735
  """Build a list of nic information tuples.
736

737
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
738
  value in LUQueryInstanceData.
739

740
  @type lu:  L{LogicalUnit}
741
  @param lu: the logical unit on whose behalf we execute
742
  @type nics: list of L{objects.NIC}
743
  @param nics: list of nics to convert to hooks tuples
744

745
  """
746
  hooks_nics = []
747
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[constants.PP_DEFAULT]
748
  for nic in nics:
749
    ip = nic.ip
750
    mac = nic.mac
751
    filled_params = objects.FillDict(c_nicparams, nic.nicparams)
752
    mode = filled_params[constants.NIC_MODE]
753
    link = filled_params[constants.NIC_LINK]
754
    hooks_nics.append((ip, mac, mode, link))
755
  return hooks_nics
756

    
757

    
758
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
759
  """Builds instance related env variables for hooks from an object.
760

761
  @type lu: L{LogicalUnit}
762
  @param lu: the logical unit on whose behalf we execute
763
  @type instance: L{objects.Instance}
764
  @param instance: the instance for which we should build the
765
      environment
766
  @type override: dict
767
  @param override: dictionary with key/values that will override
768
      our values
769
  @rtype: dict
770
  @return: the hook environment dictionary
771

772
  """
773
  cluster = lu.cfg.GetClusterInfo()
774
  bep = cluster.FillBE(instance)
775
  hvp = cluster.FillHV(instance)
776
  args = {
777
    'name': instance.name,
778
    'primary_node': instance.primary_node,
779
    'secondary_nodes': instance.secondary_nodes,
780
    'os_type': instance.os,
781
    'status': instance.admin_up,
782
    'memory': bep[constants.BE_MEMORY],
783
    'vcpus': bep[constants.BE_VCPUS],
784
    'nics': _NICListToTuple(lu, instance.nics),
785
    'disk_template': instance.disk_template,
786
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
787
    'bep': bep,
788
    'hvp': hvp,
789
    'hypervisor_name': instance.hypervisor,
790
  }
791
  if override:
792
    args.update(override)
793
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
794

    
795

    
796
def _AdjustCandidatePool(lu, exceptions):
797
  """Adjust the candidate pool after node operations.
798

799
  """
800
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
801
  if mod_list:
802
    lu.LogInfo("Promoted nodes to master candidate role: %s",
803
               utils.CommaJoin(node.name for node in mod_list))
804
    for name in mod_list:
805
      lu.context.ReaddNode(name)
806
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
807
  if mc_now > mc_max:
808
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
809
               (mc_now, mc_max))
810

    
811

    
812
def _DecideSelfPromotion(lu, exceptions=None):
813
  """Decide whether I should promote myself as a master candidate.
814

815
  """
816
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
817
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
818
  # the new node will increase mc_max with one, so:
819
  mc_should = min(mc_should + 1, cp_size)
820
  return mc_now < mc_should
821

    
822

    
823
def _CheckNicsBridgesExist(lu, target_nics, target_node,
824
                               profile=constants.PP_DEFAULT):
825
  """Check that the brigdes needed by a list of nics exist.
826

827
  """
828
  c_nicparams = lu.cfg.GetClusterInfo().nicparams[profile]
829
  paramslist = [objects.FillDict(c_nicparams, nic.nicparams)
830
                for nic in target_nics]
831
  brlist = [params[constants.NIC_LINK] for params in paramslist
832
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
833
  if brlist:
834
    result = lu.rpc.call_bridges_exist(target_node, brlist)
835
    result.Raise("Error checking bridges on destination node '%s'" %
836
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
837

    
838

    
839
def _CheckInstanceBridgesExist(lu, instance, node=None):
840
  """Check that the brigdes needed by an instance exist.
841

842
  """
843
  if node is None:
844
    node = instance.primary_node
845
  _CheckNicsBridgesExist(lu, instance.nics, node)
846

    
847

    
848
def _CheckOSVariant(os_obj, name):
849
  """Check whether an OS name conforms to the os variants specification.
850

851
  @type os_obj: L{objects.OS}
852
  @param os_obj: OS object to check
853
  @type name: string
854
  @param name: OS name passed by the user, to check for validity
855

856
  """
857
  if not os_obj.supported_variants:
858
    return
859
  try:
860
    variant = name.split("+", 1)[1]
861
  except IndexError:
862
    raise errors.OpPrereqError("OS name must include a variant",
863
                               errors.ECODE_INVAL)
864

    
865
  if variant not in os_obj.supported_variants:
866
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
867

    
868

    
869
def _GetNodeInstancesInner(cfg, fn):
870
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
871

    
872

    
873
def _GetNodeInstances(cfg, node_name):
874
  """Returns a list of all primary and secondary instances on a node.
875

876
  """
877

    
878
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
879

    
880

    
881
def _GetNodePrimaryInstances(cfg, node_name):
882
  """Returns primary instances on a node.
883

884
  """
885
  return _GetNodeInstancesInner(cfg,
886
                                lambda inst: node_name == inst.primary_node)
887

    
888

    
889
def _GetNodeSecondaryInstances(cfg, node_name):
890
  """Returns secondary instances on a node.
891

892
  """
893
  return _GetNodeInstancesInner(cfg,
894
                                lambda inst: node_name in inst.secondary_nodes)
895

    
896

    
897
def _GetStorageTypeArgs(cfg, storage_type):
898
  """Returns the arguments for a storage type.
899

900
  """
901
  # Special case for file storage
902
  if storage_type == constants.ST_FILE:
903
    # storage.FileStorage wants a list of storage directories
904
    return [[cfg.GetFileStorageDir()]]
905

    
906
  return []
907

    
908

    
909
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
910
  faulty = []
911

    
912
  for dev in instance.disks:
913
    cfg.SetDiskID(dev, node_name)
914

    
915
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
916
  result.Raise("Failed to get disk status from node %s" % node_name,
917
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
918

    
919
  for idx, bdev_status in enumerate(result.payload):
920
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
921
      faulty.append(idx)
922

    
923
  return faulty
924

    
925

    
926
class LUPostInitCluster(LogicalUnit):
927
  """Logical unit for running hooks after cluster initialization.
928

929
  """
930
  HPATH = "cluster-init"
931
  HTYPE = constants.HTYPE_CLUSTER
932
  _OP_REQP = []
933

    
934
  def BuildHooksEnv(self):
935
    """Build hooks env.
936

937
    """
938
    env = {"OP_TARGET": self.cfg.GetClusterName()}
939
    mn = self.cfg.GetMasterNode()
940
    return env, [], [mn]
941

    
942
  def CheckPrereq(self):
943
    """No prerequisites to check.
944

945
    """
946
    return True
947

    
948
  def Exec(self, feedback_fn):
949
    """Nothing to do.
950

951
    """
952
    return True
953

    
954

    
955
class LUDestroyCluster(LogicalUnit):
956
  """Logical unit for destroying the cluster.
957

958
  """
959
  HPATH = "cluster-destroy"
960
  HTYPE = constants.HTYPE_CLUSTER
961
  _OP_REQP = []
962

    
963
  def BuildHooksEnv(self):
964
    """Build hooks env.
965

966
    """
967
    env = {"OP_TARGET": self.cfg.GetClusterName()}
968
    return env, [], []
969

    
970
  def CheckPrereq(self):
971
    """Check prerequisites.
972

973
    This checks whether the cluster is empty.
974

975
    Any errors are signaled by raising errors.OpPrereqError.
976

977
    """
978
    master = self.cfg.GetMasterNode()
979

    
980
    nodelist = self.cfg.GetNodeList()
981
    if len(nodelist) != 1 or nodelist[0] != master:
982
      raise errors.OpPrereqError("There are still %d node(s) in"
983
                                 " this cluster." % (len(nodelist) - 1),
984
                                 errors.ECODE_INVAL)
985
    instancelist = self.cfg.GetInstanceList()
986
    if instancelist:
987
      raise errors.OpPrereqError("There are still %d instance(s) in"
988
                                 " this cluster." % len(instancelist),
989
                                 errors.ECODE_INVAL)
990

    
991
  def Exec(self, feedback_fn):
992
    """Destroys the cluster.
993

994
    """
995
    master = self.cfg.GetMasterNode()
996
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
997

    
998
    # Run post hooks on master node before it's removed
999
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1000
    try:
1001
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1002
    except:
1003
      # pylint: disable-msg=W0702
1004
      self.LogWarning("Errors occurred running hooks on %s" % master)
1005

    
1006
    result = self.rpc.call_node_stop_master(master, False)
1007
    result.Raise("Could not disable the master role")
1008

    
1009
    if modify_ssh_setup:
1010
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1011
      utils.CreateBackup(priv_key)
1012
      utils.CreateBackup(pub_key)
1013

    
1014
    return master
1015

    
1016

    
1017
def _VerifyCertificate(filename):
1018
  """Verifies a certificate for LUVerifyCluster.
1019

1020
  @type filename: string
1021
  @param filename: Path to PEM file
1022

1023
  """
1024
  try:
1025
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1026
                                           utils.ReadFile(filename))
1027
  except Exception, err: # pylint: disable-msg=W0703
1028
    return (LUVerifyCluster.ETYPE_ERROR,
1029
            "Failed to load X509 certificate %s: %s" % (filename, err))
1030

    
1031
  (errcode, msg) = \
1032
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1033
                                constants.SSL_CERT_EXPIRATION_ERROR)
1034

    
1035
  if msg:
1036
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1037
  else:
1038
    fnamemsg = None
1039

    
1040
  if errcode is None:
1041
    return (None, fnamemsg)
1042
  elif errcode == utils.CERT_WARNING:
1043
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1044
  elif errcode == utils.CERT_ERROR:
1045
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1046

    
1047
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1048

    
1049

    
1050
class LUVerifyCluster(LogicalUnit):
1051
  """Verifies the cluster status.
1052

1053
  """
1054
  HPATH = "cluster-verify"
1055
  HTYPE = constants.HTYPE_CLUSTER
1056
  _OP_REQP = ["skip_checks", "verbose", "error_codes", "debug_simulate_errors"]
1057
  REQ_BGL = False
1058

    
1059
  TCLUSTER = "cluster"
1060
  TNODE = "node"
1061
  TINSTANCE = "instance"
1062

    
1063
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1064
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1065
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1066
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1067
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1068
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1069
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1070
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1071
  ENODEDRBD = (TNODE, "ENODEDRBD")
1072
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1073
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1074
  ENODEHV = (TNODE, "ENODEHV")
1075
  ENODELVM = (TNODE, "ENODELVM")
1076
  ENODEN1 = (TNODE, "ENODEN1")
1077
  ENODENET = (TNODE, "ENODENET")
1078
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1079
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1080
  ENODERPC = (TNODE, "ENODERPC")
1081
  ENODESSH = (TNODE, "ENODESSH")
1082
  ENODEVERSION = (TNODE, "ENODEVERSION")
1083
  ENODESETUP = (TNODE, "ENODESETUP")
1084
  ENODETIME = (TNODE, "ENODETIME")
1085

    
1086
  ETYPE_FIELD = "code"
1087
  ETYPE_ERROR = "ERROR"
1088
  ETYPE_WARNING = "WARNING"
1089

    
1090
  class NodeImage(object):
1091
    """A class representing the logical and physical status of a node.
1092

1093
    @ivar volumes: a structure as returned from
1094
        L{ganeti.backend.GetVolumeList} (runtime)
1095
    @ivar instances: a list of running instances (runtime)
1096
    @ivar pinst: list of configured primary instances (config)
1097
    @ivar sinst: list of configured secondary instances (config)
1098
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1099
        of this node (config)
1100
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1101
    @ivar dfree: free disk, as reported by the node (runtime)
1102
    @ivar offline: the offline status (config)
1103
    @type rpc_fail: boolean
1104
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1105
        not whether the individual keys were correct) (runtime)
1106
    @type lvm_fail: boolean
1107
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1108
    @type hyp_fail: boolean
1109
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1110
    @type ghost: boolean
1111
    @ivar ghost: whether this is a known node or not (config)
1112

1113
    """
1114
    def __init__(self, offline=False):
1115
      self.volumes = {}
1116
      self.instances = []
1117
      self.pinst = []
1118
      self.sinst = []
1119
      self.sbp = {}
1120
      self.mfree = 0
1121
      self.dfree = 0
1122
      self.offline = offline
1123
      self.rpc_fail = False
1124
      self.lvm_fail = False
1125
      self.hyp_fail = False
1126
      self.ghost = False
1127

    
1128
  def ExpandNames(self):
1129
    self.needed_locks = {
1130
      locking.LEVEL_NODE: locking.ALL_SET,
1131
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1132
    }
1133
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1134

    
1135
  def _Error(self, ecode, item, msg, *args, **kwargs):
1136
    """Format an error message.
1137

1138
    Based on the opcode's error_codes parameter, either format a
1139
    parseable error code, or a simpler error string.
1140

1141
    This must be called only from Exec and functions called from Exec.
1142

1143
    """
1144
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1145
    itype, etxt = ecode
1146
    # first complete the msg
1147
    if args:
1148
      msg = msg % args
1149
    # then format the whole message
1150
    if self.op.error_codes:
1151
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1152
    else:
1153
      if item:
1154
        item = " " + item
1155
      else:
1156
        item = ""
1157
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1158
    # and finally report it via the feedback_fn
1159
    self._feedback_fn("  - %s" % msg)
1160

    
1161
  def _ErrorIf(self, cond, *args, **kwargs):
1162
    """Log an error message if the passed condition is True.
1163

1164
    """
1165
    cond = bool(cond) or self.op.debug_simulate_errors
1166
    if cond:
1167
      self._Error(*args, **kwargs)
1168
    # do not mark the operation as failed for WARN cases only
1169
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1170
      self.bad = self.bad or cond
1171

    
1172
  def _VerifyNode(self, ninfo, nresult):
1173
    """Run multiple tests against a node.
1174

1175
    Test list:
1176

1177
      - compares ganeti version
1178
      - checks vg existence and size > 20G
1179
      - checks config file checksum
1180
      - checks ssh to other nodes
1181

1182
    @type ninfo: L{objects.Node}
1183
    @param ninfo: the node to check
1184
    @param nresult: the results from the node
1185
    @rtype: boolean
1186
    @return: whether overall this call was successful (and we can expect
1187
         reasonable values in the respose)
1188

1189
    """
1190
    node = ninfo.name
1191
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1192

    
1193
    # main result, nresult should be a non-empty dict
1194
    test = not nresult or not isinstance(nresult, dict)
1195
    _ErrorIf(test, self.ENODERPC, node,
1196
                  "unable to verify node: no data returned")
1197
    if test:
1198
      return False
1199

    
1200
    # compares ganeti version
1201
    local_version = constants.PROTOCOL_VERSION
1202
    remote_version = nresult.get("version", None)
1203
    test = not (remote_version and
1204
                isinstance(remote_version, (list, tuple)) and
1205
                len(remote_version) == 2)
1206
    _ErrorIf(test, self.ENODERPC, node,
1207
             "connection to node returned invalid data")
1208
    if test:
1209
      return False
1210

    
1211
    test = local_version != remote_version[0]
1212
    _ErrorIf(test, self.ENODEVERSION, node,
1213
             "incompatible protocol versions: master %s,"
1214
             " node %s", local_version, remote_version[0])
1215
    if test:
1216
      return False
1217

    
1218
    # node seems compatible, we can actually try to look into its results
1219

    
1220
    # full package version
1221
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1222
                  self.ENODEVERSION, node,
1223
                  "software version mismatch: master %s, node %s",
1224
                  constants.RELEASE_VERSION, remote_version[1],
1225
                  code=self.ETYPE_WARNING)
1226

    
1227
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1228
    if isinstance(hyp_result, dict):
1229
      for hv_name, hv_result in hyp_result.iteritems():
1230
        test = hv_result is not None
1231
        _ErrorIf(test, self.ENODEHV, node,
1232
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1233

    
1234

    
1235
    test = nresult.get(constants.NV_NODESETUP,
1236
                           ["Missing NODESETUP results"])
1237
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1238
             "; ".join(test))
1239

    
1240
    return True
1241

    
1242
  def _VerifyNodeTime(self, ninfo, nresult,
1243
                      nvinfo_starttime, nvinfo_endtime):
1244
    """Check the node time.
1245

1246
    @type ninfo: L{objects.Node}
1247
    @param ninfo: the node to check
1248
    @param nresult: the remote results for the node
1249
    @param nvinfo_starttime: the start time of the RPC call
1250
    @param nvinfo_endtime: the end time of the RPC call
1251

1252
    """
1253
    node = ninfo.name
1254
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1255

    
1256
    ntime = nresult.get(constants.NV_TIME, None)
1257
    try:
1258
      ntime_merged = utils.MergeTime(ntime)
1259
    except (ValueError, TypeError):
1260
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1261
      return
1262

    
1263
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1264
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1265
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1266
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1267
    else:
1268
      ntime_diff = None
1269

    
1270
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1271
             "Node time diverges by at least %s from master node time",
1272
             ntime_diff)
1273

    
1274
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1275
    """Check the node time.
1276

1277
    @type ninfo: L{objects.Node}
1278
    @param ninfo: the node to check
1279
    @param nresult: the remote results for the node
1280
    @param vg_name: the configured VG name
1281

1282
    """
1283
    if vg_name is None:
1284
      return
1285

    
1286
    node = ninfo.name
1287
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1288

    
1289
    # checks vg existence and size > 20G
1290
    vglist = nresult.get(constants.NV_VGLIST, None)
1291
    test = not vglist
1292
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1293
    if not test:
1294
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1295
                                            constants.MIN_VG_SIZE)
1296
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1297

    
1298
    # check pv names
1299
    pvlist = nresult.get(constants.NV_PVLIST, None)
1300
    test = pvlist is None
1301
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1302
    if not test:
1303
      # check that ':' is not present in PV names, since it's a
1304
      # special character for lvcreate (denotes the range of PEs to
1305
      # use on the PV)
1306
      for _, pvname, owner_vg in pvlist:
1307
        test = ":" in pvname
1308
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1309
                 " '%s' of VG '%s'", pvname, owner_vg)
1310

    
1311
  def _VerifyNodeNetwork(self, ninfo, nresult):
1312
    """Check the node time.
1313

1314
    @type ninfo: L{objects.Node}
1315
    @param ninfo: the node to check
1316
    @param nresult: the remote results for the node
1317

1318
    """
1319
    node = ninfo.name
1320
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1321

    
1322
    test = constants.NV_NODELIST not in nresult
1323
    _ErrorIf(test, self.ENODESSH, node,
1324
             "node hasn't returned node ssh connectivity data")
1325
    if not test:
1326
      if nresult[constants.NV_NODELIST]:
1327
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1328
          _ErrorIf(True, self.ENODESSH, node,
1329
                   "ssh communication with node '%s': %s", a_node, a_msg)
1330

    
1331
    test = constants.NV_NODENETTEST not in nresult
1332
    _ErrorIf(test, self.ENODENET, node,
1333
             "node hasn't returned node tcp connectivity data")
1334
    if not test:
1335
      if nresult[constants.NV_NODENETTEST]:
1336
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1337
        for anode in nlist:
1338
          _ErrorIf(True, self.ENODENET, node,
1339
                   "tcp communication with node '%s': %s",
1340
                   anode, nresult[constants.NV_NODENETTEST][anode])
1341

    
1342
    test = constants.NV_MASTERIP not in nresult
1343
    _ErrorIf(test, self.ENODENET, node,
1344
             "node hasn't returned node master IP reachability data")
1345
    if not test:
1346
      if not nresult[constants.NV_MASTERIP]:
1347
        if node == self.master_node:
1348
          msg = "the master node cannot reach the master IP (not configured?)"
1349
        else:
1350
          msg = "cannot reach the master IP"
1351
        _ErrorIf(True, self.ENODENET, node, msg)
1352

    
1353

    
1354
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1355
    """Verify an instance.
1356

1357
    This function checks to see if the required block devices are
1358
    available on the instance's node.
1359

1360
    """
1361
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1362
    node_current = instanceconfig.primary_node
1363

    
1364
    node_vol_should = {}
1365
    instanceconfig.MapLVsByNode(node_vol_should)
1366

    
1367
    for node in node_vol_should:
1368
      n_img = node_image[node]
1369
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1370
        # ignore missing volumes on offline or broken nodes
1371
        continue
1372
      for volume in node_vol_should[node]:
1373
        test = volume not in n_img.volumes
1374
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1375
                 "volume %s missing on node %s", volume, node)
1376

    
1377
    if instanceconfig.admin_up:
1378
      pri_img = node_image[node_current]
1379
      test = instance not in pri_img.instances and not pri_img.offline
1380
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1381
               "instance not running on its primary node %s",
1382
               node_current)
1383

    
1384
    for node, n_img in node_image.items():
1385
      if (not node == node_current):
1386
        test = instance in n_img.instances
1387
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1388
                 "instance should not run on node %s", node)
1389

    
1390
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1391
    """Verify if there are any unknown volumes in the cluster.
1392

1393
    The .os, .swap and backup volumes are ignored. All other volumes are
1394
    reported as unknown.
1395

1396
    """
1397
    for node, n_img in node_image.items():
1398
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1399
        # skip non-healthy nodes
1400
        continue
1401
      for volume in n_img.volumes:
1402
        test = (node not in node_vol_should or
1403
                volume not in node_vol_should[node])
1404
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1405
                      "volume %s is unknown", volume)
1406

    
1407
  def _VerifyOrphanInstances(self, instancelist, node_image):
1408
    """Verify the list of running instances.
1409

1410
    This checks what instances are running but unknown to the cluster.
1411

1412
    """
1413
    for node, n_img in node_image.items():
1414
      for o_inst in n_img.instances:
1415
        test = o_inst not in instancelist
1416
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1417
                      "instance %s on node %s should not exist", o_inst, node)
1418

    
1419
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1420
    """Verify N+1 Memory Resilience.
1421

1422
    Check that if one single node dies we can still start all the
1423
    instances it was primary for.
1424

1425
    """
1426
    for node, n_img in node_image.items():
1427
      # This code checks that every node which is now listed as
1428
      # secondary has enough memory to host all instances it is
1429
      # supposed to should a single other node in the cluster fail.
1430
      # FIXME: not ready for failover to an arbitrary node
1431
      # FIXME: does not support file-backed instances
1432
      # WARNING: we currently take into account down instances as well
1433
      # as up ones, considering that even if they're down someone
1434
      # might want to start them even in the event of a node failure.
1435
      for prinode, instances in n_img.sbp.items():
1436
        needed_mem = 0
1437
        for instance in instances:
1438
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1439
          if bep[constants.BE_AUTO_BALANCE]:
1440
            needed_mem += bep[constants.BE_MEMORY]
1441
        test = n_img.mfree < needed_mem
1442
        self._ErrorIf(test, self.ENODEN1, node,
1443
                      "not enough memory on to accommodate"
1444
                      " failovers should peer node %s fail", prinode)
1445

    
1446
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1447
                       master_files):
1448
    """Verifies and computes the node required file checksums.
1449

1450
    @type ninfo: L{objects.Node}
1451
    @param ninfo: the node to check
1452
    @param nresult: the remote results for the node
1453
    @param file_list: required list of files
1454
    @param local_cksum: dictionary of local files and their checksums
1455
    @param master_files: list of files that only masters should have
1456

1457
    """
1458
    node = ninfo.name
1459
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1460

    
1461
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1462
    test = not isinstance(remote_cksum, dict)
1463
    _ErrorIf(test, self.ENODEFILECHECK, node,
1464
             "node hasn't returned file checksum data")
1465
    if test:
1466
      return
1467

    
1468
    for file_name in file_list:
1469
      node_is_mc = ninfo.master_candidate
1470
      must_have = (file_name not in master_files) or node_is_mc
1471
      # missing
1472
      test1 = file_name not in remote_cksum
1473
      # invalid checksum
1474
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1475
      # existing and good
1476
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1477
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1478
               "file '%s' missing", file_name)
1479
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1480
               "file '%s' has wrong checksum", file_name)
1481
      # not candidate and this is not a must-have file
1482
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1483
               "file '%s' should not exist on non master"
1484
               " candidates (and the file is outdated)", file_name)
1485
      # all good, except non-master/non-must have combination
1486
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1487
               "file '%s' should not exist"
1488
               " on non master candidates", file_name)
1489

    
1490
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_map):
1491
    """Verifies and the node DRBD status.
1492

1493
    @type ninfo: L{objects.Node}
1494
    @param ninfo: the node to check
1495
    @param nresult: the remote results for the node
1496
    @param instanceinfo: the dict of instances
1497
    @param drbd_map: the DRBD map as returned by
1498
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1499

1500
    """
1501
    node = ninfo.name
1502
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1503

    
1504
    # compute the DRBD minors
1505
    node_drbd = {}
1506
    for minor, instance in drbd_map[node].items():
1507
      test = instance not in instanceinfo
1508
      _ErrorIf(test, self.ECLUSTERCFG, None,
1509
               "ghost instance '%s' in temporary DRBD map", instance)
1510
        # ghost instance should not be running, but otherwise we
1511
        # don't give double warnings (both ghost instance and
1512
        # unallocated minor in use)
1513
      if test:
1514
        node_drbd[minor] = (instance, False)
1515
      else:
1516
        instance = instanceinfo[instance]
1517
        node_drbd[minor] = (instance.name, instance.admin_up)
1518

    
1519
    # and now check them
1520
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1521
    test = not isinstance(used_minors, (tuple, list))
1522
    _ErrorIf(test, self.ENODEDRBD, node,
1523
             "cannot parse drbd status file: %s", str(used_minors))
1524
    if test:
1525
      # we cannot check drbd status
1526
      return
1527

    
1528
    for minor, (iname, must_exist) in node_drbd.items():
1529
      test = minor not in used_minors and must_exist
1530
      _ErrorIf(test, self.ENODEDRBD, node,
1531
               "drbd minor %d of instance %s is not active", minor, iname)
1532
    for minor in used_minors:
1533
      test = minor not in node_drbd
1534
      _ErrorIf(test, self.ENODEDRBD, node,
1535
               "unallocated drbd minor %d is in use", minor)
1536

    
1537
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1538
    """Verifies and updates the node volume data.
1539

1540
    This function will update a L{NodeImage}'s internal structures
1541
    with data from the remote call.
1542

1543
    @type ninfo: L{objects.Node}
1544
    @param ninfo: the node to check
1545
    @param nresult: the remote results for the node
1546
    @param nimg: the node image object
1547
    @param vg_name: the configured VG name
1548

1549
    """
1550
    node = ninfo.name
1551
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1552

    
1553
    nimg.lvm_fail = True
1554
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1555
    if vg_name is None:
1556
      pass
1557
    elif isinstance(lvdata, basestring):
1558
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1559
               utils.SafeEncode(lvdata))
1560
    elif not isinstance(lvdata, dict):
1561
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1562
    else:
1563
      nimg.volumes = lvdata
1564
      nimg.lvm_fail = False
1565

    
1566
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1567
    """Verifies and updates the node instance list.
1568

1569
    If the listing was successful, then updates this node's instance
1570
    list. Otherwise, it marks the RPC call as failed for the instance
1571
    list key.
1572

1573
    @type ninfo: L{objects.Node}
1574
    @param ninfo: the node to check
1575
    @param nresult: the remote results for the node
1576
    @param nimg: the node image object
1577

1578
    """
1579
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1580
    test = not isinstance(idata, list)
1581
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1582
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1583
    if test:
1584
      nimg.hyp_fail = True
1585
    else:
1586
      nimg.instances = idata
1587

    
1588
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1589
    """Verifies and computes a node information map
1590

1591
    @type ninfo: L{objects.Node}
1592
    @param ninfo: the node to check
1593
    @param nresult: the remote results for the node
1594
    @param nimg: the node image object
1595
    @param vg_name: the configured VG name
1596

1597
    """
1598
    node = ninfo.name
1599
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1600

    
1601
    # try to read free memory (from the hypervisor)
1602
    hv_info = nresult.get(constants.NV_HVINFO, None)
1603
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1604
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1605
    if not test:
1606
      try:
1607
        nimg.mfree = int(hv_info["memory_free"])
1608
      except (ValueError, TypeError):
1609
        _ErrorIf(True, self.ENODERPC, node,
1610
                 "node returned invalid nodeinfo, check hypervisor")
1611

    
1612
    # FIXME: devise a free space model for file based instances as well
1613
    if vg_name is not None:
1614
      test = (constants.NV_VGLIST not in nresult or
1615
              vg_name not in nresult[constants.NV_VGLIST])
1616
      _ErrorIf(test, self.ENODELVM, node,
1617
               "node didn't return data for the volume group '%s'"
1618
               " - it is either missing or broken", vg_name)
1619
      if not test:
1620
        try:
1621
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1622
        except (ValueError, TypeError):
1623
          _ErrorIf(True, self.ENODERPC, node,
1624
                   "node returned invalid LVM info, check LVM status")
1625

    
1626
  def CheckPrereq(self):
1627
    """Check prerequisites.
1628

1629
    Transform the list of checks we're going to skip into a set and check that
1630
    all its members are valid.
1631

1632
    """
1633
    self.skip_set = frozenset(self.op.skip_checks)
1634
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
1635
      raise errors.OpPrereqError("Invalid checks to be skipped specified",
1636
                                 errors.ECODE_INVAL)
1637

    
1638
  def BuildHooksEnv(self):
1639
    """Build hooks env.
1640

1641
    Cluster-Verify hooks just ran in the post phase and their failure makes
1642
    the output be logged in the verify output and the verification to fail.
1643

1644
    """
1645
    all_nodes = self.cfg.GetNodeList()
1646
    env = {
1647
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1648
      }
1649
    for node in self.cfg.GetAllNodesInfo().values():
1650
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1651

    
1652
    return env, [], all_nodes
1653

    
1654
  def Exec(self, feedback_fn):
1655
    """Verify integrity of cluster, performing various test on nodes.
1656

1657
    """
1658
    self.bad = False
1659
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1660
    verbose = self.op.verbose
1661
    self._feedback_fn = feedback_fn
1662
    feedback_fn("* Verifying global settings")
1663
    for msg in self.cfg.VerifyConfig():
1664
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1665

    
1666
    # Check the cluster certificates
1667
    for cert_filename in constants.ALL_CERT_FILES:
1668
      (errcode, msg) = _VerifyCertificate(cert_filename)
1669
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1670

    
1671
    vg_name = self.cfg.GetVGName()
1672
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1673
    cluster = self.cfg.GetClusterInfo()
1674
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1675
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1676
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1677
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1678
                        for iname in instancelist)
1679
    i_non_redundant = [] # Non redundant instances
1680
    i_non_a_balanced = [] # Non auto-balanced instances
1681
    n_offline = 0 # Count of offline nodes
1682
    n_drained = 0 # Count of nodes being drained
1683
    node_vol_should = {}
1684

    
1685
    # FIXME: verify OS list
1686
    # do local checksums
1687
    master_files = [constants.CLUSTER_CONF_FILE]
1688
    master_node = self.master_node = self.cfg.GetMasterNode()
1689
    master_ip = self.cfg.GetMasterIP()
1690

    
1691
    file_names = ssconf.SimpleStore().GetFileList()
1692
    file_names.extend(constants.ALL_CERT_FILES)
1693
    file_names.extend(master_files)
1694
    if cluster.modify_etc_hosts:
1695
      file_names.append(constants.ETC_HOSTS)
1696

    
1697
    local_checksums = utils.FingerprintFiles(file_names)
1698

    
1699
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
1700
    node_verify_param = {
1701
      constants.NV_FILELIST: file_names,
1702
      constants.NV_NODELIST: [node.name for node in nodeinfo
1703
                              if not node.offline],
1704
      constants.NV_HYPERVISOR: hypervisors,
1705
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
1706
                                  node.secondary_ip) for node in nodeinfo
1707
                                 if not node.offline],
1708
      constants.NV_INSTANCELIST: hypervisors,
1709
      constants.NV_VERSION: None,
1710
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
1711
      constants.NV_NODESETUP: None,
1712
      constants.NV_TIME: None,
1713
      constants.NV_MASTERIP: (master_node, master_ip),
1714
      }
1715

    
1716
    if vg_name is not None:
1717
      node_verify_param[constants.NV_VGLIST] = None
1718
      node_verify_param[constants.NV_LVLIST] = vg_name
1719
      node_verify_param[constants.NV_PVLIST] = [vg_name]
1720
      node_verify_param[constants.NV_DRBDLIST] = None
1721

    
1722
    # Build our expected cluster state
1723
    node_image = dict((node.name, self.NodeImage(offline=node.offline))
1724
                      for node in nodeinfo)
1725

    
1726
    for instance in instancelist:
1727
      inst_config = instanceinfo[instance]
1728

    
1729
      for nname in inst_config.all_nodes:
1730
        if nname not in node_image:
1731
          # ghost node
1732
          gnode = self.NodeImage()
1733
          gnode.ghost = True
1734
          node_image[nname] = gnode
1735

    
1736
      inst_config.MapLVsByNode(node_vol_should)
1737

    
1738
      pnode = inst_config.primary_node
1739
      node_image[pnode].pinst.append(instance)
1740

    
1741
      for snode in inst_config.secondary_nodes:
1742
        nimg = node_image[snode]
1743
        nimg.sinst.append(instance)
1744
        if pnode not in nimg.sbp:
1745
          nimg.sbp[pnode] = []
1746
        nimg.sbp[pnode].append(instance)
1747

    
1748
    # At this point, we have the in-memory data structures complete,
1749
    # except for the runtime information, which we'll gather next
1750

    
1751
    # Due to the way our RPC system works, exact response times cannot be
1752
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
1753
    # time before and after executing the request, we can at least have a time
1754
    # window.
1755
    nvinfo_starttime = time.time()
1756
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
1757
                                           self.cfg.GetClusterName())
1758
    nvinfo_endtime = time.time()
1759

    
1760
    all_drbd_map = self.cfg.ComputeDRBDMap()
1761

    
1762
    feedback_fn("* Verifying node status")
1763
    for node_i in nodeinfo:
1764
      node = node_i.name
1765
      nimg = node_image[node]
1766

    
1767
      if node_i.offline:
1768
        if verbose:
1769
          feedback_fn("* Skipping offline node %s" % (node,))
1770
        n_offline += 1
1771
        continue
1772

    
1773
      if node == master_node:
1774
        ntype = "master"
1775
      elif node_i.master_candidate:
1776
        ntype = "master candidate"
1777
      elif node_i.drained:
1778
        ntype = "drained"
1779
        n_drained += 1
1780
      else:
1781
        ntype = "regular"
1782
      if verbose:
1783
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
1784

    
1785
      msg = all_nvinfo[node].fail_msg
1786
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
1787
      if msg:
1788
        nimg.rpc_fail = True
1789
        continue
1790

    
1791
      nresult = all_nvinfo[node].payload
1792

    
1793
      nimg.call_ok = self._VerifyNode(node_i, nresult)
1794
      self._VerifyNodeNetwork(node_i, nresult)
1795
      self._VerifyNodeLVM(node_i, nresult, vg_name)
1796
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
1797
                            master_files)
1798
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, all_drbd_map)
1799
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
1800

    
1801
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
1802
      self._UpdateNodeInstances(node_i, nresult, nimg)
1803
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
1804

    
1805
    feedback_fn("* Verifying instance status")
1806
    for instance in instancelist:
1807
      if verbose:
1808
        feedback_fn("* Verifying instance %s" % instance)
1809
      inst_config = instanceinfo[instance]
1810
      self._VerifyInstance(instance, inst_config, node_image)
1811
      inst_nodes_offline = []
1812

    
1813
      pnode = inst_config.primary_node
1814
      pnode_img = node_image[pnode]
1815
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
1816
               self.ENODERPC, pnode, "instance %s, connection to"
1817
               " primary node failed", instance)
1818

    
1819
      if pnode_img.offline:
1820
        inst_nodes_offline.append(pnode)
1821

    
1822
      # If the instance is non-redundant we cannot survive losing its primary
1823
      # node, so we are not N+1 compliant. On the other hand we have no disk
1824
      # templates with more than one secondary so that situation is not well
1825
      # supported either.
1826
      # FIXME: does not support file-backed instances
1827
      if not inst_config.secondary_nodes:
1828
        i_non_redundant.append(instance)
1829
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
1830
               instance, "instance has multiple secondary nodes: %s",
1831
               utils.CommaJoin(inst_config.secondary_nodes),
1832
               code=self.ETYPE_WARNING)
1833

    
1834
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
1835
        i_non_a_balanced.append(instance)
1836

    
1837
      for snode in inst_config.secondary_nodes:
1838
        s_img = node_image[snode]
1839
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
1840
                 "instance %s, connection to secondary node failed", instance)
1841

    
1842
        if s_img.offline:
1843
          inst_nodes_offline.append(snode)
1844

    
1845
      # warn that the instance lives on offline nodes
1846
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
1847
               "instance lives on offline node(s) %s",
1848
               utils.CommaJoin(inst_nodes_offline))
1849
      # ... or ghost nodes
1850
      for node in inst_config.all_nodes:
1851
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
1852
                 "instance lives on ghost node %s", node)
1853

    
1854
    feedback_fn("* Verifying orphan volumes")
1855
    self._VerifyOrphanVolumes(node_vol_should, node_image)
1856

    
1857
    feedback_fn("* Verifying orphan instances")
1858
    self._VerifyOrphanInstances(instancelist, node_image)
1859

    
1860
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
1861
      feedback_fn("* Verifying N+1 Memory redundancy")
1862
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
1863

    
1864
    feedback_fn("* Other Notes")
1865
    if i_non_redundant:
1866
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
1867
                  % len(i_non_redundant))
1868

    
1869
    if i_non_a_balanced:
1870
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
1871
                  % len(i_non_a_balanced))
1872

    
1873
    if n_offline:
1874
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
1875

    
1876
    if n_drained:
1877
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
1878

    
1879
    return not self.bad
1880

    
1881
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
1882
    """Analyze the post-hooks' result
1883

1884
    This method analyses the hook result, handles it, and sends some
1885
    nicely-formatted feedback back to the user.
1886

1887
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
1888
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
1889
    @param hooks_results: the results of the multi-node hooks rpc call
1890
    @param feedback_fn: function used send feedback back to the caller
1891
    @param lu_result: previous Exec result
1892
    @return: the new Exec result, based on the previous result
1893
        and hook results
1894

1895
    """
1896
    # We only really run POST phase hooks, and are only interested in
1897
    # their results
1898
    if phase == constants.HOOKS_PHASE_POST:
1899
      # Used to change hooks' output to proper indentation
1900
      indent_re = re.compile('^', re.M)
1901
      feedback_fn("* Hooks Results")
1902
      assert hooks_results, "invalid result from hooks"
1903

    
1904
      for node_name in hooks_results:
1905
        res = hooks_results[node_name]
1906
        msg = res.fail_msg
1907
        test = msg and not res.offline
1908
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
1909
                      "Communication failure in hooks execution: %s", msg)
1910
        if res.offline or msg:
1911
          # No need to investigate payload if node is offline or gave an error.
1912
          # override manually lu_result here as _ErrorIf only
1913
          # overrides self.bad
1914
          lu_result = 1
1915
          continue
1916
        for script, hkr, output in res.payload:
1917
          test = hkr == constants.HKR_FAIL
1918
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
1919
                        "Script %s failed, output:", script)
1920
          if test:
1921
            output = indent_re.sub('      ', output)
1922
            feedback_fn("%s" % output)
1923
            lu_result = 0
1924

    
1925
      return lu_result
1926

    
1927

    
1928
class LUVerifyDisks(NoHooksLU):
1929
  """Verifies the cluster disks status.
1930

1931
  """
1932
  _OP_REQP = []
1933
  REQ_BGL = False
1934

    
1935
  def ExpandNames(self):
1936
    self.needed_locks = {
1937
      locking.LEVEL_NODE: locking.ALL_SET,
1938
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1939
    }
1940
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1941

    
1942
  def CheckPrereq(self):
1943
    """Check prerequisites.
1944

1945
    This has no prerequisites.
1946

1947
    """
1948
    pass
1949

    
1950
  def Exec(self, feedback_fn):
1951
    """Verify integrity of cluster disks.
1952

1953
    @rtype: tuple of three items
1954
    @return: a tuple of (dict of node-to-node_error, list of instances
1955
        which need activate-disks, dict of instance: (node, volume) for
1956
        missing volumes
1957

1958
    """
1959
    result = res_nodes, res_instances, res_missing = {}, [], {}
1960

    
1961
    vg_name = self.cfg.GetVGName()
1962
    nodes = utils.NiceSort(self.cfg.GetNodeList())
1963
    instances = [self.cfg.GetInstanceInfo(name)
1964
                 for name in self.cfg.GetInstanceList()]
1965

    
1966
    nv_dict = {}
1967
    for inst in instances:
1968
      inst_lvs = {}
1969
      if (not inst.admin_up or
1970
          inst.disk_template not in constants.DTS_NET_MIRROR):
1971
        continue
1972
      inst.MapLVsByNode(inst_lvs)
1973
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
1974
      for node, vol_list in inst_lvs.iteritems():
1975
        for vol in vol_list:
1976
          nv_dict[(node, vol)] = inst
1977

    
1978
    if not nv_dict:
1979
      return result
1980

    
1981
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
1982

    
1983
    for node in nodes:
1984
      # node_volume
1985
      node_res = node_lvs[node]
1986
      if node_res.offline:
1987
        continue
1988
      msg = node_res.fail_msg
1989
      if msg:
1990
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
1991
        res_nodes[node] = msg
1992
        continue
1993

    
1994
      lvs = node_res.payload
1995
      for lv_name, (_, _, lv_online) in lvs.items():
1996
        inst = nv_dict.pop((node, lv_name), None)
1997
        if (not lv_online and inst is not None
1998
            and inst.name not in res_instances):
1999
          res_instances.append(inst.name)
2000

    
2001
    # any leftover items in nv_dict are missing LVs, let's arrange the
2002
    # data better
2003
    for key, inst in nv_dict.iteritems():
2004
      if inst.name not in res_missing:
2005
        res_missing[inst.name] = []
2006
      res_missing[inst.name].append(key)
2007

    
2008
    return result
2009

    
2010

    
2011
class LURepairDiskSizes(NoHooksLU):
2012
  """Verifies the cluster disks sizes.
2013

2014
  """
2015
  _OP_REQP = ["instances"]
2016
  REQ_BGL = False
2017

    
2018
  def ExpandNames(self):
2019
    if not isinstance(self.op.instances, list):
2020
      raise errors.OpPrereqError("Invalid argument type 'instances'",
2021
                                 errors.ECODE_INVAL)
2022

    
2023
    if self.op.instances:
2024
      self.wanted_names = []
2025
      for name in self.op.instances:
2026
        full_name = _ExpandInstanceName(self.cfg, name)
2027
        self.wanted_names.append(full_name)
2028
      self.needed_locks = {
2029
        locking.LEVEL_NODE: [],
2030
        locking.LEVEL_INSTANCE: self.wanted_names,
2031
        }
2032
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2033
    else:
2034
      self.wanted_names = None
2035
      self.needed_locks = {
2036
        locking.LEVEL_NODE: locking.ALL_SET,
2037
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2038
        }
2039
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2040

    
2041
  def DeclareLocks(self, level):
2042
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2043
      self._LockInstancesNodes(primary_only=True)
2044

    
2045
  def CheckPrereq(self):
2046
    """Check prerequisites.
2047

2048
    This only checks the optional instance list against the existing names.
2049

2050
    """
2051
    if self.wanted_names is None:
2052
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2053

    
2054
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2055
                             in self.wanted_names]
2056

    
2057
  def _EnsureChildSizes(self, disk):
2058
    """Ensure children of the disk have the needed disk size.
2059

2060
    This is valid mainly for DRBD8 and fixes an issue where the
2061
    children have smaller disk size.
2062

2063
    @param disk: an L{ganeti.objects.Disk} object
2064

2065
    """
2066
    if disk.dev_type == constants.LD_DRBD8:
2067
      assert disk.children, "Empty children for DRBD8?"
2068
      fchild = disk.children[0]
2069
      mismatch = fchild.size < disk.size
2070
      if mismatch:
2071
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2072
                     fchild.size, disk.size)
2073
        fchild.size = disk.size
2074

    
2075
      # and we recurse on this child only, not on the metadev
2076
      return self._EnsureChildSizes(fchild) or mismatch
2077
    else:
2078
      return False
2079

    
2080
  def Exec(self, feedback_fn):
2081
    """Verify the size of cluster disks.
2082

2083
    """
2084
    # TODO: check child disks too
2085
    # TODO: check differences in size between primary/secondary nodes
2086
    per_node_disks = {}
2087
    for instance in self.wanted_instances:
2088
      pnode = instance.primary_node
2089
      if pnode not in per_node_disks:
2090
        per_node_disks[pnode] = []
2091
      for idx, disk in enumerate(instance.disks):
2092
        per_node_disks[pnode].append((instance, idx, disk))
2093

    
2094
    changed = []
2095
    for node, dskl in per_node_disks.items():
2096
      newl = [v[2].Copy() for v in dskl]
2097
      for dsk in newl:
2098
        self.cfg.SetDiskID(dsk, node)
2099
      result = self.rpc.call_blockdev_getsizes(node, newl)
2100
      if result.fail_msg:
2101
        self.LogWarning("Failure in blockdev_getsizes call to node"
2102
                        " %s, ignoring", node)
2103
        continue
2104
      if len(result.data) != len(dskl):
2105
        self.LogWarning("Invalid result from node %s, ignoring node results",
2106
                        node)
2107
        continue
2108
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2109
        if size is None:
2110
          self.LogWarning("Disk %d of instance %s did not return size"
2111
                          " information, ignoring", idx, instance.name)
2112
          continue
2113
        if not isinstance(size, (int, long)):
2114
          self.LogWarning("Disk %d of instance %s did not return valid"
2115
                          " size information, ignoring", idx, instance.name)
2116
          continue
2117
        size = size >> 20
2118
        if size != disk.size:
2119
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2120
                       " correcting: recorded %d, actual %d", idx,
2121
                       instance.name, disk.size, size)
2122
          disk.size = size
2123
          self.cfg.Update(instance, feedback_fn)
2124
          changed.append((instance.name, idx, size))
2125
        if self._EnsureChildSizes(disk):
2126
          self.cfg.Update(instance, feedback_fn)
2127
          changed.append((instance.name, idx, disk.size))
2128
    return changed
2129

    
2130

    
2131
class LURenameCluster(LogicalUnit):
2132
  """Rename the cluster.
2133

2134
  """
2135
  HPATH = "cluster-rename"
2136
  HTYPE = constants.HTYPE_CLUSTER
2137
  _OP_REQP = ["name"]
2138

    
2139
  def BuildHooksEnv(self):
2140
    """Build hooks env.
2141

2142
    """
2143
    env = {
2144
      "OP_TARGET": self.cfg.GetClusterName(),
2145
      "NEW_NAME": self.op.name,
2146
      }
2147
    mn = self.cfg.GetMasterNode()
2148
    all_nodes = self.cfg.GetNodeList()
2149
    return env, [mn], all_nodes
2150

    
2151
  def CheckPrereq(self):
2152
    """Verify that the passed name is a valid one.
2153

2154
    """
2155
    hostname = utils.GetHostInfo(self.op.name)
2156

    
2157
    new_name = hostname.name
2158
    self.ip = new_ip = hostname.ip
2159
    old_name = self.cfg.GetClusterName()
2160
    old_ip = self.cfg.GetMasterIP()
2161
    if new_name == old_name and new_ip == old_ip:
2162
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2163
                                 " cluster has changed",
2164
                                 errors.ECODE_INVAL)
2165
    if new_ip != old_ip:
2166
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2167
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2168
                                   " reachable on the network. Aborting." %
2169
                                   new_ip, errors.ECODE_NOTUNIQUE)
2170

    
2171
    self.op.name = new_name
2172

    
2173
  def Exec(self, feedback_fn):
2174
    """Rename the cluster.
2175

2176
    """
2177
    clustername = self.op.name
2178
    ip = self.ip
2179

    
2180
    # shutdown the master IP
2181
    master = self.cfg.GetMasterNode()
2182
    result = self.rpc.call_node_stop_master(master, False)
2183
    result.Raise("Could not disable the master role")
2184

    
2185
    try:
2186
      cluster = self.cfg.GetClusterInfo()
2187
      cluster.cluster_name = clustername
2188
      cluster.master_ip = ip
2189
      self.cfg.Update(cluster, feedback_fn)
2190

    
2191
      # update the known hosts file
2192
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2193
      node_list = self.cfg.GetNodeList()
2194
      try:
2195
        node_list.remove(master)
2196
      except ValueError:
2197
        pass
2198
      result = self.rpc.call_upload_file(node_list,
2199
                                         constants.SSH_KNOWN_HOSTS_FILE)
2200
      for to_node, to_result in result.iteritems():
2201
        msg = to_result.fail_msg
2202
        if msg:
2203
          msg = ("Copy of file %s to node %s failed: %s" %
2204
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2205
          self.proc.LogWarning(msg)
2206

    
2207
    finally:
2208
      result = self.rpc.call_node_start_master(master, False, False)
2209
      msg = result.fail_msg
2210
      if msg:
2211
        self.LogWarning("Could not re-enable the master role on"
2212
                        " the master, please restart manually: %s", msg)
2213

    
2214

    
2215
def _RecursiveCheckIfLVMBased(disk):
2216
  """Check if the given disk or its children are lvm-based.
2217

2218
  @type disk: L{objects.Disk}
2219
  @param disk: the disk to check
2220
  @rtype: boolean
2221
  @return: boolean indicating whether a LD_LV dev_type was found or not
2222

2223
  """
2224
  if disk.children:
2225
    for chdisk in disk.children:
2226
      if _RecursiveCheckIfLVMBased(chdisk):
2227
        return True
2228
  return disk.dev_type == constants.LD_LV
2229

    
2230

    
2231
class LUSetClusterParams(LogicalUnit):
2232
  """Change the parameters of the cluster.
2233

2234
  """
2235
  HPATH = "cluster-modify"
2236
  HTYPE = constants.HTYPE_CLUSTER
2237
  _OP_REQP = []
2238
  REQ_BGL = False
2239

    
2240
  def CheckArguments(self):
2241
    """Check parameters
2242

2243
    """
2244
    for attr in ["candidate_pool_size",
2245
                 "uid_pool", "add_uids", "remove_uids"]:
2246
      if not hasattr(self.op, attr):
2247
        setattr(self.op, attr, None)
2248

    
2249
    if self.op.candidate_pool_size is not None:
2250
      try:
2251
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
2252
      except (ValueError, TypeError), err:
2253
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
2254
                                   str(err), errors.ECODE_INVAL)
2255
      if self.op.candidate_pool_size < 1:
2256
        raise errors.OpPrereqError("At least one master candidate needed",
2257
                                   errors.ECODE_INVAL)
2258

    
2259
    _CheckBooleanOpField(self.op, "maintain_node_health")
2260

    
2261
    if self.op.uid_pool:
2262
      uidpool.CheckUidPool(self.op.uid_pool)
2263

    
2264
    if self.op.add_uids:
2265
      uidpool.CheckUidPool(self.op.add_uids)
2266

    
2267
    if self.op.remove_uids:
2268
      uidpool.CheckUidPool(self.op.remove_uids)
2269

    
2270
  def ExpandNames(self):
2271
    # FIXME: in the future maybe other cluster params won't require checking on
2272
    # all nodes to be modified.
2273
    self.needed_locks = {
2274
      locking.LEVEL_NODE: locking.ALL_SET,
2275
    }
2276
    self.share_locks[locking.LEVEL_NODE] = 1
2277

    
2278
  def BuildHooksEnv(self):
2279
    """Build hooks env.
2280

2281
    """
2282
    env = {
2283
      "OP_TARGET": self.cfg.GetClusterName(),
2284
      "NEW_VG_NAME": self.op.vg_name,
2285
      }
2286
    mn = self.cfg.GetMasterNode()
2287
    return env, [mn], [mn]
2288

    
2289
  def CheckPrereq(self):
2290
    """Check prerequisites.
2291

2292
    This checks whether the given params don't conflict and
2293
    if the given volume group is valid.
2294

2295
    """
2296
    if self.op.vg_name is not None and not self.op.vg_name:
2297
      instances = self.cfg.GetAllInstancesInfo().values()
2298
      for inst in instances:
2299
        for disk in inst.disks:
2300
          if _RecursiveCheckIfLVMBased(disk):
2301
            raise errors.OpPrereqError("Cannot disable lvm storage while"
2302
                                       " lvm-based instances exist",
2303
                                       errors.ECODE_INVAL)
2304

    
2305
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2306

    
2307
    # if vg_name not None, checks given volume group on all nodes
2308
    if self.op.vg_name:
2309
      vglist = self.rpc.call_vg_list(node_list)
2310
      for node in node_list:
2311
        msg = vglist[node].fail_msg
2312
        if msg:
2313
          # ignoring down node
2314
          self.LogWarning("Error while gathering data on node %s"
2315
                          " (ignoring node): %s", node, msg)
2316
          continue
2317
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2318
                                              self.op.vg_name,
2319
                                              constants.MIN_VG_SIZE)
2320
        if vgstatus:
2321
          raise errors.OpPrereqError("Error on node '%s': %s" %
2322
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2323

    
2324
    self.cluster = cluster = self.cfg.GetClusterInfo()
2325
    # validate params changes
2326
    if self.op.beparams:
2327
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2328
      self.new_beparams = objects.FillDict(
2329
        cluster.beparams[constants.PP_DEFAULT], self.op.beparams)
2330

    
2331
    if self.op.nicparams:
2332
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2333
      self.new_nicparams = objects.FillDict(
2334
        cluster.nicparams[constants.PP_DEFAULT], self.op.nicparams)
2335
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2336
      nic_errors = []
2337

    
2338
      # check all instances for consistency
2339
      for instance in self.cfg.GetAllInstancesInfo().values():
2340
        for nic_idx, nic in enumerate(instance.nics):
2341
          params_copy = copy.deepcopy(nic.nicparams)
2342
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2343

    
2344
          # check parameter syntax
2345
          try:
2346
            objects.NIC.CheckParameterSyntax(params_filled)
2347
          except errors.ConfigurationError, err:
2348
            nic_errors.append("Instance %s, nic/%d: %s" %
2349
                              (instance.name, nic_idx, err))
2350

    
2351
          # if we're moving instances to routed, check that they have an ip
2352
          target_mode = params_filled[constants.NIC_MODE]
2353
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2354
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2355
                              (instance.name, nic_idx))
2356
      if nic_errors:
2357
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2358
                                   "\n".join(nic_errors))
2359

    
2360
    # hypervisor list/parameters
2361
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2362
    if self.op.hvparams:
2363
      if not isinstance(self.op.hvparams, dict):
2364
        raise errors.OpPrereqError("Invalid 'hvparams' parameter on input",
2365
                                   errors.ECODE_INVAL)
2366
      for hv_name, hv_dict in self.op.hvparams.items():
2367
        if hv_name not in self.new_hvparams:
2368
          self.new_hvparams[hv_name] = hv_dict
2369
        else:
2370
          self.new_hvparams[hv_name].update(hv_dict)
2371

    
2372
    # os hypervisor parameters
2373
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2374
    if self.op.os_hvp:
2375
      if not isinstance(self.op.os_hvp, dict):
2376
        raise errors.OpPrereqError("Invalid 'os_hvp' parameter on input",
2377
                                   errors.ECODE_INVAL)
2378
      for os_name, hvs in self.op.os_hvp.items():
2379
        if not isinstance(hvs, dict):
2380
          raise errors.OpPrereqError(("Invalid 'os_hvp' parameter on"
2381
                                      " input"), errors.ECODE_INVAL)
2382
        if os_name not in self.new_os_hvp:
2383
          self.new_os_hvp[os_name] = hvs
2384
        else:
2385
          for hv_name, hv_dict in hvs.items():
2386
            if hv_name not in self.new_os_hvp[os_name]:
2387
              self.new_os_hvp[os_name][hv_name] = hv_dict
2388
            else:
2389
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2390

    
2391
    # changes to the hypervisor list
2392
    if self.op.enabled_hypervisors is not None:
2393
      self.hv_list = self.op.enabled_hypervisors
2394
      if not self.hv_list:
2395
        raise errors.OpPrereqError("Enabled hypervisors list must contain at"
2396
                                   " least one member",
2397
                                   errors.ECODE_INVAL)
2398
      invalid_hvs = set(self.hv_list) - constants.HYPER_TYPES
2399
      if invalid_hvs:
2400
        raise errors.OpPrereqError("Enabled hypervisors contains invalid"
2401
                                   " entries: %s" %
2402
                                   utils.CommaJoin(invalid_hvs),
2403
                                   errors.ECODE_INVAL)
2404
      for hv in self.hv_list:
2405
        # if the hypervisor doesn't already exist in the cluster
2406
        # hvparams, we initialize it to empty, and then (in both
2407
        # cases) we make sure to fill the defaults, as we might not
2408
        # have a complete defaults list if the hypervisor wasn't
2409
        # enabled before
2410
        if hv not in new_hvp:
2411
          new_hvp[hv] = {}
2412
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2413
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2414
    else:
2415
      self.hv_list = cluster.enabled_hypervisors
2416

    
2417
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2418
      # either the enabled list has changed, or the parameters have, validate
2419
      for hv_name, hv_params in self.new_hvparams.items():
2420
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2421
            (self.op.enabled_hypervisors and
2422
             hv_name in self.op.enabled_hypervisors)):
2423
          # either this is a new hypervisor, or its parameters have changed
2424
          hv_class = hypervisor.GetHypervisor(hv_name)
2425
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2426
          hv_class.CheckParameterSyntax(hv_params)
2427
          _CheckHVParams(self, node_list, hv_name, hv_params)
2428

    
2429
    if self.op.os_hvp:
2430
      # no need to check any newly-enabled hypervisors, since the
2431
      # defaults have already been checked in the above code-block
2432
      for os_name, os_hvp in self.new_os_hvp.items():
2433
        for hv_name, hv_params in os_hvp.items():
2434
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2435
          # we need to fill in the new os_hvp on top of the actual hv_p
2436
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2437
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2438
          hv_class = hypervisor.GetHypervisor(hv_name)
2439
          hv_class.CheckParameterSyntax(new_osp)
2440
          _CheckHVParams(self, node_list, hv_name, new_osp)
2441

    
2442

    
2443
  def Exec(self, feedback_fn):
2444
    """Change the parameters of the cluster.
2445

2446
    """
2447
    if self.op.vg_name is not None:
2448
      new_volume = self.op.vg_name
2449
      if not new_volume:
2450
        new_volume = None
2451
      if new_volume != self.cfg.GetVGName():
2452
        self.cfg.SetVGName(new_volume)
2453
      else:
2454
        feedback_fn("Cluster LVM configuration already in desired"
2455
                    " state, not changing")
2456
    if self.op.hvparams:
2457
      self.cluster.hvparams = self.new_hvparams
2458
    if self.op.os_hvp:
2459
      self.cluster.os_hvp = self.new_os_hvp
2460
    if self.op.enabled_hypervisors is not None:
2461
      self.cluster.hvparams = self.new_hvparams
2462
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2463
    if self.op.beparams:
2464
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2465
    if self.op.nicparams:
2466
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2467

    
2468
    if self.op.candidate_pool_size is not None:
2469
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2470
      # we need to update the pool size here, otherwise the save will fail
2471
      _AdjustCandidatePool(self, [])
2472

    
2473
    if self.op.maintain_node_health is not None:
2474
      self.cluster.maintain_node_health = self.op.maintain_node_health
2475

    
2476
    if self.op.add_uids is not None:
2477
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2478

    
2479
    if self.op.remove_uids is not None:
2480
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2481

    
2482
    if self.op.uid_pool is not None:
2483
      self.cluster.uid_pool = self.op.uid_pool
2484

    
2485
    self.cfg.Update(self.cluster, feedback_fn)
2486

    
2487

    
2488
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2489
  """Distribute additional files which are part of the cluster configuration.
2490

2491
  ConfigWriter takes care of distributing the config and ssconf files, but
2492
  there are more files which should be distributed to all nodes. This function
2493
  makes sure those are copied.
2494

2495
  @param lu: calling logical unit
2496
  @param additional_nodes: list of nodes not in the config to distribute to
2497

2498
  """
2499
  # 1. Gather target nodes
2500
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2501
  dist_nodes = lu.cfg.GetOnlineNodeList()
2502
  if additional_nodes is not None:
2503
    dist_nodes.extend(additional_nodes)
2504
  if myself.name in dist_nodes:
2505
    dist_nodes.remove(myself.name)
2506

    
2507
  # 2. Gather files to distribute
2508
  dist_files = set([constants.ETC_HOSTS,
2509
                    constants.SSH_KNOWN_HOSTS_FILE,
2510
                    constants.RAPI_CERT_FILE,
2511
                    constants.RAPI_USERS_FILE,
2512
                    constants.CONFD_HMAC_KEY,
2513
                   ])
2514

    
2515
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2516
  for hv_name in enabled_hypervisors:
2517
    hv_class = hypervisor.GetHypervisor(hv_name)
2518
    dist_files.update(hv_class.GetAncillaryFiles())
2519

    
2520
  # 3. Perform the files upload
2521
  for fname in dist_files:
2522
    if os.path.exists(fname):
2523
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2524
      for to_node, to_result in result.items():
2525
        msg = to_result.fail_msg
2526
        if msg:
2527
          msg = ("Copy of file %s to node %s failed: %s" %
2528
                 (fname, to_node, msg))
2529
          lu.proc.LogWarning(msg)
2530

    
2531

    
2532
class LURedistributeConfig(NoHooksLU):
2533
  """Force the redistribution of cluster configuration.
2534

2535
  This is a very simple LU.
2536

2537
  """
2538
  _OP_REQP = []
2539
  REQ_BGL = False
2540

    
2541
  def ExpandNames(self):
2542
    self.needed_locks = {
2543
      locking.LEVEL_NODE: locking.ALL_SET,
2544
    }
2545
    self.share_locks[locking.LEVEL_NODE] = 1
2546

    
2547
  def CheckPrereq(self):
2548
    """Check prerequisites.
2549

2550
    """
2551

    
2552
  def Exec(self, feedback_fn):
2553
    """Redistribute the configuration.
2554

2555
    """
2556
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2557
    _RedistributeAncillaryFiles(self)
2558

    
2559

    
2560
def _WaitForSync(lu, instance, oneshot=False):
2561
  """Sleep and poll for an instance's disk to sync.
2562

2563
  """
2564
  if not instance.disks:
2565
    return True
2566

    
2567
  if not oneshot:
2568
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2569

    
2570
  node = instance.primary_node
2571

    
2572
  for dev in instance.disks:
2573
    lu.cfg.SetDiskID(dev, node)
2574

    
2575
  # TODO: Convert to utils.Retry
2576

    
2577
  retries = 0
2578
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2579
  while True:
2580
    max_time = 0
2581
    done = True
2582
    cumul_degraded = False
2583
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, instance.disks)
2584
    msg = rstats.fail_msg
2585
    if msg:
2586
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2587
      retries += 1
2588
      if retries >= 10:
2589
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2590
                                 " aborting." % node)
2591
      time.sleep(6)
2592
      continue
2593
    rstats = rstats.payload
2594
    retries = 0
2595
    for i, mstat in enumerate(rstats):
2596
      if mstat is None:
2597
        lu.LogWarning("Can't compute data for node %s/%s",
2598
                           node, instance.disks[i].iv_name)
2599
        continue
2600

    
2601
      cumul_degraded = (cumul_degraded or
2602
                        (mstat.is_degraded and mstat.sync_percent is None))
2603
      if mstat.sync_percent is not None:
2604
        done = False
2605
        if mstat.estimated_time is not None:
2606
          rem_time = "%d estimated seconds remaining" % mstat.estimated_time
2607
          max_time = mstat.estimated_time
2608
        else:
2609
          rem_time = "no time estimate"
2610
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2611
                        (instance.disks[i].iv_name, mstat.sync_percent,
2612
                         rem_time))
2613

    
2614
    # if we're done but degraded, let's do a few small retries, to
2615
    # make sure we see a stable and not transient situation; therefore
2616
    # we force restart of the loop
2617
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2618
      logging.info("Degraded disks found, %d retries left", degr_retries)
2619
      degr_retries -= 1
2620
      time.sleep(1)
2621
      continue
2622

    
2623
    if done or oneshot:
2624
      break
2625

    
2626
    time.sleep(min(60, max_time))
2627

    
2628
  if done:
2629
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2630
  return not cumul_degraded
2631

    
2632

    
2633
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2634
  """Check that mirrors are not degraded.
2635

2636
  The ldisk parameter, if True, will change the test from the
2637
  is_degraded attribute (which represents overall non-ok status for
2638
  the device(s)) to the ldisk (representing the local storage status).
2639

2640
  """
2641
  lu.cfg.SetDiskID(dev, node)
2642

    
2643
  result = True
2644

    
2645
  if on_primary or dev.AssembleOnSecondary():
2646
    rstats = lu.rpc.call_blockdev_find(node, dev)
2647
    msg = rstats.fail_msg
2648
    if msg:
2649
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2650
      result = False
2651
    elif not rstats.payload:
2652
      lu.LogWarning("Can't find disk on node %s", node)
2653
      result = False
2654
    else:
2655
      if ldisk:
2656
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2657
      else:
2658
        result = result and not rstats.payload.is_degraded
2659

    
2660
  if dev.children:
2661
    for child in dev.children:
2662
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2663

    
2664
  return result
2665

    
2666

    
2667
class LUDiagnoseOS(NoHooksLU):
2668
  """Logical unit for OS diagnose/query.
2669

2670
  """
2671
  _OP_REQP = ["output_fields", "names"]
2672
  REQ_BGL = False
2673
  _FIELDS_STATIC = utils.FieldSet()
2674
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants")
2675
  # Fields that need calculation of global os validity
2676
  _FIELDS_NEEDVALID = frozenset(["valid", "variants"])
2677

    
2678
  def ExpandNames(self):
2679
    if self.op.names:
2680
      raise errors.OpPrereqError("Selective OS query not supported",
2681
                                 errors.ECODE_INVAL)
2682

    
2683
    _CheckOutputFields(static=self._FIELDS_STATIC,
2684
                       dynamic=self._FIELDS_DYNAMIC,
2685
                       selected=self.op.output_fields)
2686

    
2687
    # Lock all nodes, in shared mode
2688
    # Temporary removal of locks, should be reverted later
2689
    # TODO: reintroduce locks when they are lighter-weight
2690
    self.needed_locks = {}
2691
    #self.share_locks[locking.LEVEL_NODE] = 1
2692
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2693

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

2697
    """
2698

    
2699
  @staticmethod
2700
  def _DiagnoseByOS(rlist):
2701
    """Remaps a per-node return list into an a per-os per-node dictionary
2702

2703
    @param rlist: a map with node names as keys and OS objects as values
2704

2705
    @rtype: dict
2706
    @return: a dictionary with osnames as keys and as value another map, with
2707
        nodes as keys and tuples of (path, status, diagnose) as values, eg::
2708

2709
          {"debian-etch": {"node1": [(/usr/lib/..., True, ""),
2710
                                     (/srv/..., False, "invalid api")],
2711
                           "node2": [(/srv/..., True, "")]}
2712
          }
2713

2714
    """
2715
    all_os = {}
2716
    # we build here the list of nodes that didn't fail the RPC (at RPC
2717
    # level), so that nodes with a non-responding node daemon don't
2718
    # make all OSes invalid
2719
    good_nodes = [node_name for node_name in rlist
2720
                  if not rlist[node_name].fail_msg]
2721
    for node_name, nr in rlist.items():
2722
      if nr.fail_msg or not nr.payload:
2723
        continue
2724
      for name, path, status, diagnose, variants in nr.payload:
2725
        if name not in all_os:
2726
          # build a list of nodes for this os containing empty lists
2727
          # for each node in node_list
2728
          all_os[name] = {}
2729
          for nname in good_nodes:
2730
            all_os[name][nname] = []
2731
        all_os[name][node_name].append((path, status, diagnose, variants))
2732
    return all_os
2733

    
2734
  def Exec(self, feedback_fn):
2735
    """Compute the list of OSes.
2736

2737
    """
2738
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
2739
    node_data = self.rpc.call_os_diagnose(valid_nodes)
2740
    pol = self._DiagnoseByOS(node_data)
2741
    output = []
2742
    calc_valid = self._FIELDS_NEEDVALID.intersection(self.op.output_fields)
2743
    calc_variants = "variants" in self.op.output_fields
2744

    
2745
    for os_name, os_data in pol.items():
2746
      row = []
2747
      if calc_valid:
2748
        valid = True
2749
        variants = None
2750
        for osl in os_data.values():
2751
          valid = valid and osl and osl[0][1]
2752
          if not valid:
2753
            variants = None
2754
            break
2755
          if calc_variants:
2756
            node_variants = osl[0][3]
2757
            if variants is None:
2758
              variants = node_variants
2759
            else:
2760
              variants = [v for v in variants if v in node_variants]
2761

    
2762
      for field in self.op.output_fields:
2763
        if field == "name":
2764
          val = os_name
2765
        elif field == "valid":
2766
          val = valid
2767
        elif field == "node_status":
2768
          # this is just a copy of the dict
2769
          val = {}
2770
          for node_name, nos_list in os_data.items():
2771
            val[node_name] = nos_list
2772
        elif field == "variants":
2773
          val =  variants
2774
        else:
2775
          raise errors.ParameterError(field)
2776
        row.append(val)
2777
      output.append(row)
2778

    
2779
    return output
2780

    
2781

    
2782
class LURemoveNode(LogicalUnit):
2783
  """Logical unit for removing a node.
2784

2785
  """
2786
  HPATH = "node-remove"
2787
  HTYPE = constants.HTYPE_NODE
2788
  _OP_REQP = ["node_name"]
2789

    
2790
  def BuildHooksEnv(self):
2791
    """Build hooks env.
2792

2793
    This doesn't run on the target node in the pre phase as a failed
2794
    node would then be impossible to remove.
2795

2796
    """
2797
    env = {
2798
      "OP_TARGET": self.op.node_name,
2799
      "NODE_NAME": self.op.node_name,
2800
      }
2801
    all_nodes = self.cfg.GetNodeList()
2802
    try:
2803
      all_nodes.remove(self.op.node_name)
2804
    except ValueError:
2805
      logging.warning("Node %s which is about to be removed not found"
2806
                      " in the all nodes list", self.op.node_name)
2807
    return env, all_nodes, all_nodes
2808

    
2809
  def CheckPrereq(self):
2810
    """Check prerequisites.
2811

2812
    This checks:
2813
     - the node exists in the configuration
2814
     - it does not have primary or secondary instances
2815
     - it's not the master
2816

2817
    Any errors are signaled by raising errors.OpPrereqError.
2818

2819
    """
2820
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
2821
    node = self.cfg.GetNodeInfo(self.op.node_name)
2822
    assert node is not None
2823

    
2824
    instance_list = self.cfg.GetInstanceList()
2825

    
2826
    masternode = self.cfg.GetMasterNode()
2827
    if node.name == masternode:
2828
      raise errors.OpPrereqError("Node is the master node,"
2829
                                 " you need to failover first.",
2830
                                 errors.ECODE_INVAL)
2831

    
2832
    for instance_name in instance_list:
2833
      instance = self.cfg.GetInstanceInfo(instance_name)
2834
      if node.name in instance.all_nodes:
2835
        raise errors.OpPrereqError("Instance %s is still running on the node,"
2836
                                   " please remove first." % instance_name,
2837
                                   errors.ECODE_INVAL)
2838
    self.op.node_name = node.name
2839
    self.node = node
2840

    
2841
  def Exec(self, feedback_fn):
2842
    """Removes the node from the cluster.
2843

2844
    """
2845
    node = self.node
2846
    logging.info("Stopping the node daemon and removing configs from node %s",
2847
                 node.name)
2848

    
2849
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
2850

    
2851
    # Promote nodes to master candidate as needed
2852
    _AdjustCandidatePool(self, exceptions=[node.name])
2853
    self.context.RemoveNode(node.name)
2854

    
2855
    # Run post hooks on the node before it's removed
2856
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
2857
    try:
2858
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
2859
    except:
2860
      # pylint: disable-msg=W0702
2861
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
2862

    
2863
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
2864
    msg = result.fail_msg
2865
    if msg:
2866
      self.LogWarning("Errors encountered on the remote node while leaving"
2867
                      " the cluster: %s", msg)
2868

    
2869
    # Remove node from our /etc/hosts
2870
    if self.cfg.GetClusterInfo().modify_etc_hosts:
2871
      # FIXME: this should be done via an rpc call to node daemon
2872
      utils.RemoveHostFromEtcHosts(node.name)
2873
      _RedistributeAncillaryFiles(self)
2874

    
2875

    
2876
class LUQueryNodes(NoHooksLU):
2877
  """Logical unit for querying nodes.
2878

2879
  """
2880
  # pylint: disable-msg=W0142
2881
  _OP_REQP = ["output_fields", "names", "use_locking"]
2882
  REQ_BGL = False
2883

    
2884
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
2885
                    "master_candidate", "offline", "drained"]
2886

    
2887
  _FIELDS_DYNAMIC = utils.FieldSet(
2888
    "dtotal", "dfree",
2889
    "mtotal", "mnode", "mfree",
2890
    "bootid",
2891
    "ctotal", "cnodes", "csockets",
2892
    )
2893

    
2894
  _FIELDS_STATIC = utils.FieldSet(*[
2895
    "pinst_cnt", "sinst_cnt",
2896
    "pinst_list", "sinst_list",
2897
    "pip", "sip", "tags",
2898
    "master",
2899
    "role"] + _SIMPLE_FIELDS
2900
    )
2901

    
2902
  def ExpandNames(self):
2903
    _CheckOutputFields(static=self._FIELDS_STATIC,
2904
                       dynamic=self._FIELDS_DYNAMIC,
2905
                       selected=self.op.output_fields)
2906

    
2907
    self.needed_locks = {}
2908
    self.share_locks[locking.LEVEL_NODE] = 1
2909

    
2910
    if self.op.names:
2911
      self.wanted = _GetWantedNodes(self, self.op.names)
2912
    else:
2913
      self.wanted = locking.ALL_SET
2914

    
2915
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
2916
    self.do_locking = self.do_node_query and self.op.use_locking
2917
    if self.do_locking:
2918
      # if we don't request only static fields, we need to lock the nodes
2919
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
2920

    
2921
  def CheckPrereq(self):
2922
    """Check prerequisites.
2923

2924
    """
2925
    # The validation of the node list is done in the _GetWantedNodes,
2926
    # if non empty, and if empty, there's no validation to do
2927
    pass
2928

    
2929
  def Exec(self, feedback_fn):
2930
    """Computes the list of nodes and their attributes.
2931

2932
    """
2933
    all_info = self.cfg.GetAllNodesInfo()
2934
    if self.do_locking:
2935
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
2936
    elif self.wanted != locking.ALL_SET:
2937
      nodenames = self.wanted
2938
      missing = set(nodenames).difference(all_info.keys())
2939
      if missing:
2940
        raise errors.OpExecError(
2941
          "Some nodes were removed before retrieving their data: %s" % missing)
2942
    else:
2943
      nodenames = all_info.keys()
2944

    
2945
    nodenames = utils.NiceSort(nodenames)
2946
    nodelist = [all_info[name] for name in nodenames]
2947

    
2948
    # begin data gathering
2949

    
2950
    if self.do_node_query:
2951
      live_data = {}
2952
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
2953
                                          self.cfg.GetHypervisorType())
2954
      for name in nodenames:
2955
        nodeinfo = node_data[name]
2956
        if not nodeinfo.fail_msg and nodeinfo.payload:
2957
          nodeinfo = nodeinfo.payload
2958
          fn = utils.TryConvert
2959
          live_data[name] = {
2960
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
2961
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
2962
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
2963
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
2964
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
2965
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
2966
            "bootid": nodeinfo.get('bootid', None),
2967
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
2968
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
2969
            }
2970
        else:
2971
          live_data[name] = {}
2972
    else:
2973
      live_data = dict.fromkeys(nodenames, {})
2974

    
2975
    node_to_primary = dict([(name, set()) for name in nodenames])
2976
    node_to_secondary = dict([(name, set()) for name in nodenames])
2977

    
2978
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
2979
                             "sinst_cnt", "sinst_list"))
2980
    if inst_fields & frozenset(self.op.output_fields):
2981
      inst_data = self.cfg.GetAllInstancesInfo()
2982

    
2983
      for inst in inst_data.values():
2984
        if inst.primary_node in node_to_primary:
2985
          node_to_primary[inst.primary_node].add(inst.name)
2986
        for secnode in inst.secondary_nodes:
2987
          if secnode in node_to_secondary:
2988
            node_to_secondary[secnode].add(inst.name)
2989

    
2990
    master_node = self.cfg.GetMasterNode()
2991

    
2992
    # end data gathering
2993

    
2994
    output = []
2995
    for node in nodelist:
2996
      node_output = []
2997
      for field in self.op.output_fields:
2998
        if field in self._SIMPLE_FIELDS:
2999
          val = getattr(node, field)
3000
        elif field == "pinst_list":
3001
          val = list(node_to_primary[node.name])
3002
        elif field == "sinst_list":
3003
          val = list(node_to_secondary[node.name])
3004
        elif field == "pinst_cnt":
3005
          val = len(node_to_primary[node.name])
3006
        elif field == "sinst_cnt":
3007
          val = len(node_to_secondary[node.name])
3008
        elif field == "pip":
3009
          val = node.primary_ip
3010
        elif field == "sip":
3011
          val = node.secondary_ip
3012
        elif field == "tags":
3013
          val = list(node.GetTags())
3014
        elif field == "master":
3015
          val = node.name == master_node
3016
        elif self._FIELDS_DYNAMIC.Matches(field):
3017
          val = live_data[node.name].get(field, None)
3018
        elif field == "role":
3019
          if node.name == master_node:
3020
            val = "M"
3021
          elif node.master_candidate:
3022
            val = "C"
3023
          elif node.drained:
3024
            val = "D"
3025
          elif node.offline:
3026
            val = "O"
3027
          else:
3028
            val = "R"
3029
        else:
3030
          raise errors.ParameterError(field)
3031
        node_output.append(val)
3032
      output.append(node_output)
3033

    
3034
    return output
3035

    
3036

    
3037
class LUQueryNodeVolumes(NoHooksLU):
3038
  """Logical unit for getting volumes on node(s).
3039

3040
  """
3041
  _OP_REQP = ["nodes", "output_fields"]
3042
  REQ_BGL = False
3043
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3044
  _FIELDS_STATIC = utils.FieldSet("node")
3045

    
3046
  def ExpandNames(self):
3047
    _CheckOutputFields(static=self._FIELDS_STATIC,
3048
                       dynamic=self._FIELDS_DYNAMIC,
3049
                       selected=self.op.output_fields)
3050

    
3051
    self.needed_locks = {}
3052
    self.share_locks[locking.LEVEL_NODE] = 1
3053
    if not self.op.nodes:
3054
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3055
    else:
3056
      self.needed_locks[locking.LEVEL_NODE] = \
3057
        _GetWantedNodes(self, self.op.nodes)
3058

    
3059
  def CheckPrereq(self):
3060
    """Check prerequisites.
3061

3062
    This checks that the fields required are valid output fields.
3063

3064
    """
3065
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3066

    
3067
  def Exec(self, feedback_fn):
3068
    """Computes the list of nodes and their attributes.
3069

3070
    """
3071
    nodenames = self.nodes
3072
    volumes = self.rpc.call_node_volumes(nodenames)
3073

    
3074
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3075
             in self.cfg.GetInstanceList()]
3076

    
3077
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3078

    
3079
    output = []
3080
    for node in nodenames:
3081
      nresult = volumes[node]
3082
      if nresult.offline:
3083
        continue
3084
      msg = nresult.fail_msg
3085
      if msg:
3086
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3087
        continue
3088

    
3089
      node_vols = nresult.payload[:]
3090
      node_vols.sort(key=lambda vol: vol['dev'])
3091

    
3092
      for vol in node_vols:
3093
        node_output = []
3094
        for field in self.op.output_fields:
3095
          if field == "node":
3096
            val = node
3097
          elif field == "phys":
3098
            val = vol['dev']
3099
          elif field == "vg":
3100
            val = vol['vg']
3101
          elif field == "name":
3102
            val = vol['name']
3103
          elif field == "size":
3104
            val = int(float(vol['size']))
3105
          elif field == "instance":
3106
            for inst in ilist:
3107
              if node not in lv_by_node[inst]:
3108
                continue
3109
              if vol['name'] in lv_by_node[inst][node]:
3110
                val = inst.name
3111
                break
3112
            else:
3113
              val = '-'
3114
          else:
3115
            raise errors.ParameterError(field)
3116
          node_output.append(str(val))
3117

    
3118
        output.append(node_output)
3119

    
3120
    return output
3121

    
3122

    
3123
class LUQueryNodeStorage(NoHooksLU):
3124
  """Logical unit for getting information on storage units on node(s).
3125

3126
  """
3127
  _OP_REQP = ["nodes", "storage_type", "output_fields"]
3128
  REQ_BGL = False
3129
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3130

    
3131
  def CheckArguments(self):
3132
    _CheckStorageType(self.op.storage_type)
3133

    
3134
    _CheckOutputFields(static=self._FIELDS_STATIC,
3135
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3136
                       selected=self.op.output_fields)
3137

    
3138
  def ExpandNames(self):
3139
    self.needed_locks = {}
3140
    self.share_locks[locking.LEVEL_NODE] = 1
3141

    
3142
    if self.op.nodes:
3143
      self.needed_locks[locking.LEVEL_NODE] = \
3144
        _GetWantedNodes(self, self.op.nodes)
3145
    else:
3146
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3147

    
3148
  def CheckPrereq(self):
3149
    """Check prerequisites.
3150

3151
    This checks that the fields required are valid output fields.
3152

3153
    """
3154
    self.op.name = getattr(self.op, "name", None)
3155

    
3156
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3157

    
3158
  def Exec(self, feedback_fn):
3159
    """Computes the list of nodes and their attributes.
3160

3161
    """
3162
    # Always get name to sort by
3163
    if constants.SF_NAME in self.op.output_fields:
3164
      fields = self.op.output_fields[:]
3165
    else:
3166
      fields = [constants.SF_NAME] + self.op.output_fields
3167

    
3168
    # Never ask for node or type as it's only known to the LU
3169
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3170
      while extra in fields:
3171
        fields.remove(extra)
3172

    
3173
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3174
    name_idx = field_idx[constants.SF_NAME]
3175

    
3176
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3177
    data = self.rpc.call_storage_list(self.nodes,
3178
                                      self.op.storage_type, st_args,
3179
                                      self.op.name, fields)
3180

    
3181
    result = []
3182

    
3183
    for node in utils.NiceSort(self.nodes):
3184
      nresult = data[node]
3185
      if nresult.offline:
3186
        continue
3187

    
3188
      msg = nresult.fail_msg
3189
      if msg:
3190
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3191
        continue
3192

    
3193
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3194

    
3195
      for name in utils.NiceSort(rows.keys()):
3196
        row = rows[name]
3197

    
3198
        out = []
3199

    
3200
        for field in self.op.output_fields:
3201
          if field == constants.SF_NODE:
3202
            val = node
3203
          elif field == constants.SF_TYPE:
3204
            val = self.op.storage_type
3205
          elif field in field_idx:
3206
            val = row[field_idx[field]]
3207
          else:
3208
            raise errors.ParameterError(field)
3209

    
3210
          out.append(val)
3211

    
3212
        result.append(out)
3213

    
3214
    return result
3215

    
3216

    
3217
class LUModifyNodeStorage(NoHooksLU):
3218
  """Logical unit for modifying a storage volume on a node.
3219

3220
  """
3221
  _OP_REQP = ["node_name", "storage_type", "name", "changes"]
3222
  REQ_BGL = False
3223

    
3224
  def CheckArguments(self):
3225
    self.opnode_name = _ExpandNodeName(self.cfg, self.op.node_name)
3226

    
3227
    _CheckStorageType(self.op.storage_type)
3228

    
3229
  def ExpandNames(self):
3230
    self.needed_locks = {
3231
      locking.LEVEL_NODE: self.op.node_name,
3232
      }
3233

    
3234
  def CheckPrereq(self):
3235
    """Check prerequisites.
3236

3237
    """
3238
    storage_type = self.op.storage_type
3239

    
3240
    try:
3241
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3242
    except KeyError:
3243
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3244
                                 " modified" % storage_type,
3245
                                 errors.ECODE_INVAL)
3246

    
3247
    diff = set(self.op.changes.keys()) - modifiable
3248
    if diff:
3249
      raise errors.OpPrereqError("The following fields can not be modified for"
3250
                                 " storage units of type '%s': %r" %
3251
                                 (storage_type, list(diff)),
3252
                                 errors.ECODE_INVAL)
3253

    
3254
  def Exec(self, feedback_fn):
3255
    """Computes the list of nodes and their attributes.
3256

3257
    """
3258
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3259
    result = self.rpc.call_storage_modify(self.op.node_name,
3260
                                          self.op.storage_type, st_args,
3261
                                          self.op.name, self.op.changes)
3262
    result.Raise("Failed to modify storage unit '%s' on %s" %
3263
                 (self.op.name, self.op.node_name))
3264

    
3265

    
3266
class LUAddNode(LogicalUnit):
3267
  """Logical unit for adding node to the cluster.
3268

3269
  """
3270
  HPATH = "node-add"
3271
  HTYPE = constants.HTYPE_NODE
3272
  _OP_REQP = ["node_name"]
3273

    
3274
  def CheckArguments(self):
3275
    # validate/normalize the node name
3276
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3277

    
3278
  def BuildHooksEnv(self):
3279
    """Build hooks env.
3280

3281
    This will run on all nodes before, and on all nodes + the new node after.
3282

3283
    """
3284
    env = {
3285
      "OP_TARGET": self.op.node_name,
3286
      "NODE_NAME": self.op.node_name,
3287
      "NODE_PIP": self.op.primary_ip,
3288
      "NODE_SIP": self.op.secondary_ip,
3289
      }
3290
    nodes_0 = self.cfg.GetNodeList()
3291
    nodes_1 = nodes_0 + [self.op.node_name, ]
3292
    return env, nodes_0, nodes_1
3293

    
3294
  def CheckPrereq(self):
3295
    """Check prerequisites.
3296

3297
    This checks:
3298
     - the new node is not already in the config
3299
     - it is resolvable
3300
     - its parameters (single/dual homed) matches the cluster
3301

3302
    Any errors are signaled by raising errors.OpPrereqError.
3303

3304
    """
3305
    node_name = self.op.node_name
3306
    cfg = self.cfg
3307

    
3308
    dns_data = utils.GetHostInfo(node_name)
3309

    
3310
    node = dns_data.name
3311
    primary_ip = self.op.primary_ip = dns_data.ip
3312
    secondary_ip = getattr(self.op, "secondary_ip", None)
3313
    if secondary_ip is None:
3314
      secondary_ip = primary_ip
3315
    if not utils.IsValidIP(secondary_ip):
3316
      raise errors.OpPrereqError("Invalid secondary IP given",
3317
                                 errors.ECODE_INVAL)
3318
    self.op.secondary_ip = secondary_ip
3319

    
3320
    node_list = cfg.GetNodeList()
3321
    if not self.op.readd and node in node_list:
3322
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3323
                                 node, errors.ECODE_EXISTS)
3324
    elif self.op.readd and node not in node_list:
3325
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3326
                                 errors.ECODE_NOENT)
3327

    
3328
    self.changed_primary_ip = False
3329

    
3330
    for existing_node_name in node_list:
3331
      existing_node = cfg.GetNodeInfo(existing_node_name)
3332

    
3333
      if self.op.readd and node == existing_node_name:
3334
        if existing_node.secondary_ip != secondary_ip:
3335
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3336
                                     " address configuration as before",
3337
                                     errors.ECODE_INVAL)
3338
        if existing_node.primary_ip != primary_ip:
3339
          self.changed_primary_ip = True
3340

    
3341
        continue
3342

    
3343
      if (existing_node.primary_ip == primary_ip or
3344
          existing_node.secondary_ip == primary_ip or
3345
          existing_node.primary_ip == secondary_ip or
3346
          existing_node.secondary_ip == secondary_ip):
3347
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3348
                                   " existing node %s" % existing_node.name,
3349
                                   errors.ECODE_NOTUNIQUE)
3350

    
3351
    # check that the type of the node (single versus dual homed) is the
3352
    # same as for the master
3353
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3354
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3355
    newbie_singlehomed = secondary_ip == primary_ip
3356
    if master_singlehomed != newbie_singlehomed:
3357
      if master_singlehomed:
3358
        raise errors.OpPrereqError("The master has no private ip but the"
3359
                                   " new node has one",
3360
                                   errors.ECODE_INVAL)
3361
      else:
3362
        raise errors.OpPrereqError("The master has a private ip but the"
3363
                                   " new node doesn't have one",
3364
                                   errors.ECODE_INVAL)
3365

    
3366
    # checks reachability
3367
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3368
      raise errors.OpPrereqError("Node not reachable by ping",
3369
                                 errors.ECODE_ENVIRON)
3370

    
3371
    if not newbie_singlehomed:
3372
      # check reachability from my secondary ip to newbie's secondary ip
3373
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3374
                           source=myself.secondary_ip):
3375
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3376
                                   " based ping to noded port",
3377
                                   errors.ECODE_ENVIRON)
3378

    
3379
    if self.op.readd:
3380
      exceptions = [node]
3381
    else:
3382
      exceptions = []
3383

    
3384
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3385

    
3386
    if self.op.readd:
3387
      self.new_node = self.cfg.GetNodeInfo(node)
3388
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3389
    else:
3390
      self.new_node = objects.Node(name=node,
3391
                                   primary_ip=primary_ip,
3392
                                   secondary_ip=secondary_ip,
3393
                                   master_candidate=self.master_candidate,
3394
                                   offline=False, drained=False)
3395

    
3396
  def Exec(self, feedback_fn):
3397
    """Adds the new node to the cluster.
3398

3399
    """
3400
    new_node = self.new_node
3401
    node = new_node.name
3402

    
3403
    # for re-adds, reset the offline/drained/master-candidate flags;
3404
    # we need to reset here, otherwise offline would prevent RPC calls
3405
    # later in the procedure; this also means that if the re-add
3406
    # fails, we are left with a non-offlined, broken node
3407
    if self.op.readd:
3408
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3409
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3410
      # if we demote the node, we do cleanup later in the procedure
3411
      new_node.master_candidate = self.master_candidate
3412
      if self.changed_primary_ip:
3413
        new_node.primary_ip = self.op.primary_ip
3414

    
3415
    # notify the user about any possible mc promotion
3416
    if new_node.master_candidate:
3417
      self.LogInfo("Node will be a master candidate")
3418

    
3419
    # check connectivity
3420
    result = self.rpc.call_version([node])[node]
3421
    result.Raise("Can't get version information from node %s" % node)
3422
    if constants.PROTOCOL_VERSION == result.payload:
3423
      logging.info("Communication to node %s fine, sw version %s match",
3424
                   node, result.payload)
3425
    else:
3426
      raise errors.OpExecError("Version mismatch master version %s,"
3427
                               " node version %s" %
3428
                               (constants.PROTOCOL_VERSION, result.payload))
3429

    
3430
    # setup ssh on node
3431
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3432
      logging.info("Copy ssh key to node %s", node)
3433
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3434
      keyarray = []
3435
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3436
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3437
                  priv_key, pub_key]
3438

    
3439
      for i in keyfiles:
3440
        keyarray.append(utils.ReadFile(i))
3441

    
3442
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3443
                                      keyarray[2], keyarray[3], keyarray[4],
3444
                                      keyarray[5])
3445
      result.Raise("Cannot transfer ssh keys to the new node")
3446

    
3447
    # Add node to our /etc/hosts, and add key to known_hosts
3448
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3449
      # FIXME: this should be done via an rpc call to node daemon
3450
      utils.AddHostToEtcHosts(new_node.name)
3451

    
3452
    if new_node.secondary_ip != new_node.primary_ip:
3453
      result = self.rpc.call_node_has_ip_address(new_node.name,
3454
                                                 new_node.secondary_ip)
3455
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3456
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3457
      if not result.payload:
3458
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3459
                                 " you gave (%s). Please fix and re-run this"
3460
                                 " command." % new_node.secondary_ip)
3461

    
3462
    node_verify_list = [self.cfg.GetMasterNode()]
3463
    node_verify_param = {
3464
      constants.NV_NODELIST: [node],
3465
      # TODO: do a node-net-test as well?
3466
    }
3467

    
3468
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3469
                                       self.cfg.GetClusterName())
3470
    for verifier in node_verify_list:
3471
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3472
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3473
      if nl_payload:
3474
        for failed in nl_payload:
3475
          feedback_fn("ssh/hostname verification failed"
3476
                      " (checking from %s): %s" %
3477
                      (verifier, nl_payload[failed]))
3478
        raise errors.OpExecError("ssh/hostname verification failed.")
3479

    
3480
    if self.op.readd:
3481
      _RedistributeAncillaryFiles(self)
3482
      self.context.ReaddNode(new_node)
3483
      # make sure we redistribute the config
3484
      self.cfg.Update(new_node, feedback_fn)
3485
      # and make sure the new node will not have old files around
3486
      if not new_node.master_candidate:
3487
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3488
        msg = result.fail_msg
3489
        if msg:
3490
          self.LogWarning("Node failed to demote itself from master"
3491
                          " candidate status: %s" % msg)
3492
    else:
3493
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3494
      self.context.AddNode(new_node, self.proc.GetECId())
3495

    
3496

    
3497
class LUSetNodeParams(LogicalUnit):
3498
  """Modifies the parameters of a node.
3499

3500
  """
3501
  HPATH = "node-modify"
3502
  HTYPE = constants.HTYPE_NODE
3503
  _OP_REQP = ["node_name"]
3504
  REQ_BGL = False
3505

    
3506
  def CheckArguments(self):
3507
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3508
    _CheckBooleanOpField(self.op, 'master_candidate')
3509
    _CheckBooleanOpField(self.op, 'offline')
3510
    _CheckBooleanOpField(self.op, 'drained')
3511
    _CheckBooleanOpField(self.op, 'auto_promote')
3512
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3513
    if all_mods.count(None) == 3:
3514
      raise errors.OpPrereqError("Please pass at least one modification",
3515
                                 errors.ECODE_INVAL)
3516
    if all_mods.count(True) > 1:
3517
      raise errors.OpPrereqError("Can't set the node into more than one"
3518
                                 " state at the same time",
3519
                                 errors.ECODE_INVAL)
3520

    
3521
    # Boolean value that tells us whether we're offlining or draining the node
3522
    self.offline_or_drain = (self.op.offline == True or
3523
                             self.op.drained == True)
3524
    self.deoffline_or_drain = (self.op.offline == False or
3525
                               self.op.drained == False)
3526
    self.might_demote = (self.op.master_candidate == False or
3527
                         self.offline_or_drain)
3528

    
3529
    self.lock_all = self.op.auto_promote and self.might_demote
3530

    
3531

    
3532
  def ExpandNames(self):
3533
    if self.lock_all:
3534
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3535
    else:
3536
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3537

    
3538
  def BuildHooksEnv(self):
3539
    """Build hooks env.
3540

3541
    This runs on the master node.
3542

3543
    """
3544
    env = {
3545
      "OP_TARGET": self.op.node_name,
3546
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3547
      "OFFLINE": str(self.op.offline),
3548
      "DRAINED": str(self.op.drained),
3549
      }
3550
    nl = [self.cfg.GetMasterNode(),
3551
          self.op.node_name]
3552
    return env, nl, nl
3553

    
3554
  def CheckPrereq(self):
3555
    """Check prerequisites.
3556

3557
    This only checks the instance list against the existing names.
3558

3559
    """
3560
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3561

    
3562
    if (self.op.master_candidate is not None or
3563
        self.op.drained is not None or
3564
        self.op.offline is not None):
3565
      # we can't change the master's node flags
3566
      if self.op.node_name == self.cfg.GetMasterNode():
3567
        raise errors.OpPrereqError("The master role can be changed"
3568
                                   " only via masterfailover",
3569
                                   errors.ECODE_INVAL)
3570

    
3571

    
3572
    if node.master_candidate and self.might_demote and not self.lock_all:
3573
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3574
      # check if after removing the current node, we're missing master
3575
      # candidates
3576
      (mc_remaining, mc_should, _) = \
3577
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3578
      if mc_remaining < mc_should:
3579
        raise errors.OpPrereqError("Not enough master candidates, please"
3580
                                   " pass auto_promote to allow promotion",
3581
                                   errors.ECODE_INVAL)
3582

    
3583
    if (self.op.master_candidate == True and
3584
        ((node.offline and not self.op.offline == False) or
3585
         (node.drained and not self.op.drained == False))):
3586
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3587
                                 " to master_candidate" % node.name,
3588
                                 errors.ECODE_INVAL)
3589

    
3590
    # If we're being deofflined/drained, we'll MC ourself if needed
3591
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3592
        self.op.master_candidate == True and not node.master_candidate):
3593
      self.op.master_candidate = _DecideSelfPromotion(self)
3594
      if self.op.master_candidate:
3595
        self.LogInfo("Autopromoting node to master candidate")
3596

    
3597
    return
3598

    
3599
  def Exec(self, feedback_fn):
3600
    """Modifies a node.
3601

3602
    """
3603
    node = self.node
3604

    
3605
    result = []
3606
    changed_mc = False
3607

    
3608
    if self.op.offline is not None:
3609
      node.offline = self.op.offline
3610
      result.append(("offline", str(self.op.offline)))
3611
      if self.op.offline == True:
3612
        if node.master_candidate:
3613
          node.master_candidate = False
3614
          changed_mc = True
3615
          result.append(("master_candidate", "auto-demotion due to offline"))
3616
        if node.drained:
3617
          node.drained = False
3618
          result.append(("drained", "clear drained status due to offline"))
3619

    
3620
    if self.op.master_candidate is not None:
3621
      node.master_candidate = self.op.master_candidate
3622
      changed_mc = True
3623
      result.append(("master_candidate", str(self.op.master_candidate)))
3624
      if self.op.master_candidate == False:
3625
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3626
        msg = rrc.fail_msg
3627
        if msg:
3628
          self.LogWarning("Node failed to demote itself: %s" % msg)
3629

    
3630
    if self.op.drained is not None:
3631
      node.drained = self.op.drained
3632
      result.append(("drained", str(self.op.drained)))
3633
      if self.op.drained == True:
3634
        if node.master_candidate:
3635
          node.master_candidate = False
3636
          changed_mc = True
3637
          result.append(("master_candidate", "auto-demotion due to drain"))
3638
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3639
          msg = rrc.fail_msg
3640
          if msg:
3641
            self.LogWarning("Node failed to demote itself: %s" % msg)
3642
        if node.offline:
3643
          node.offline = False
3644
          result.append(("offline", "clear offline status due to drain"))
3645

    
3646
    # we locked all nodes, we adjust the CP before updating this node
3647
    if self.lock_all:
3648
      _AdjustCandidatePool(self, [node.name])
3649

    
3650
    # this will trigger configuration file update, if needed
3651
    self.cfg.Update(node, feedback_fn)
3652

    
3653
    # this will trigger job queue propagation or cleanup
3654
    if changed_mc:
3655
      self.context.ReaddNode(node)
3656

    
3657
    return result
3658

    
3659

    
3660
class LUPowercycleNode(NoHooksLU):
3661
  """Powercycles a node.
3662

3663
  """
3664
  _OP_REQP = ["node_name", "force"]
3665
  REQ_BGL = False
3666

    
3667
  def CheckArguments(self):
3668
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3669
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3670
      raise errors.OpPrereqError("The node is the master and the force"
3671
                                 " parameter was not set",
3672
                                 errors.ECODE_INVAL)
3673

    
3674
  def ExpandNames(self):
3675
    """Locking for PowercycleNode.
3676

3677
    This is a last-resort option and shouldn't block on other
3678
    jobs. Therefore, we grab no locks.
3679

3680
    """
3681
    self.needed_locks = {}
3682

    
3683
  def CheckPrereq(self):
3684
    """Check prerequisites.
3685

3686
    This LU has no prereqs.
3687

3688
    """
3689
    pass
3690

    
3691
  def Exec(self, feedback_fn):
3692
    """Reboots a node.
3693

3694
    """
3695
    result = self.rpc.call_node_powercycle(self.op.node_name,
3696
                                           self.cfg.GetHypervisorType())
3697
    result.Raise("Failed to schedule the reboot")
3698
    return result.payload
3699

    
3700

    
3701
class LUQueryClusterInfo(NoHooksLU):
3702
  """Query cluster configuration.
3703

3704
  """
3705
  _OP_REQP = []
3706
  REQ_BGL = False
3707

    
3708
  def ExpandNames(self):
3709
    self.needed_locks = {}
3710

    
3711
  def CheckPrereq(self):
3712
    """No prerequsites needed for this LU.
3713

3714
    """
3715
    pass
3716

    
3717
  def Exec(self, feedback_fn):
3718
    """Return cluster config.
3719

3720
    """
3721
    cluster = self.cfg.GetClusterInfo()
3722
    os_hvp = {}
3723

    
3724
    # Filter just for enabled hypervisors
3725
    for os_name, hv_dict in cluster.os_hvp.items():
3726
      os_hvp[os_name] = {}
3727
      for hv_name, hv_params in hv_dict.items():
3728
        if hv_name in cluster.enabled_hypervisors:
3729
          os_hvp[os_name][hv_name] = hv_params
3730

    
3731
    result = {
3732
      "software_version": constants.RELEASE_VERSION,
3733
      "protocol_version": constants.PROTOCOL_VERSION,
3734
      "config_version": constants.CONFIG_VERSION,
3735
      "os_api_version": max(constants.OS_API_VERSIONS),
3736
      "export_version": constants.EXPORT_VERSION,
3737
      "architecture": (platform.architecture()[0], platform.machine()),
3738
      "name": cluster.cluster_name,
3739
      "master": cluster.master_node,
3740
      "default_hypervisor": cluster.enabled_hypervisors[0],
3741
      "enabled_hypervisors": cluster.enabled_hypervisors,
3742
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
3743
                        for hypervisor_name in cluster.enabled_hypervisors]),
3744
      "os_hvp": os_hvp,
3745
      "beparams": cluster.beparams,
3746
      "nicparams": cluster.nicparams,
3747
      "candidate_pool_size": cluster.candidate_pool_size,
3748
      "master_netdev": cluster.master_netdev,
3749
      "volume_group_name": cluster.volume_group_name,
3750
      "file_storage_dir": cluster.file_storage_dir,
3751
      "maintain_node_health": cluster.maintain_node_health,
3752
      "ctime": cluster.ctime,
3753
      "mtime": cluster.mtime,
3754
      "uuid": cluster.uuid,
3755
      "tags": list(cluster.GetTags()),
3756
      "uid_pool": cluster.uid_pool,
3757
      }
3758

    
3759
    return result
3760

    
3761

    
3762
class LUQueryConfigValues(NoHooksLU):
3763
  """Return configuration values.
3764

3765
  """
3766
  _OP_REQP = []
3767
  REQ_BGL = False
3768
  _FIELDS_DYNAMIC = utils.FieldSet()
3769
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
3770
                                  "watcher_pause")
3771

    
3772
  def ExpandNames(self):
3773
    self.needed_locks = {}
3774

    
3775
    _CheckOutputFields(static=self._FIELDS_STATIC,
3776
                       dynamic=self._FIELDS_DYNAMIC,
3777
                       selected=self.op.output_fields)
3778

    
3779
  def CheckPrereq(self):
3780
    """No prerequisites.
3781

3782
    """
3783
    pass
3784

    
3785
  def Exec(self, feedback_fn):
3786
    """Dump a representation of the cluster config to the standard output.
3787

3788
    """
3789
    values = []
3790
    for field in self.op.output_fields:
3791
      if field == "cluster_name":
3792
        entry = self.cfg.GetClusterName()
3793
      elif field == "master_node":
3794
        entry = self.cfg.GetMasterNode()
3795
      elif field == "drain_flag":
3796
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
3797
      elif field == "watcher_pause":
3798
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
3799
      else:
3800
        raise errors.ParameterError(field)
3801
      values.append(entry)
3802
    return values
3803

    
3804

    
3805
class LUActivateInstanceDisks(NoHooksLU):
3806
  """Bring up an instance's disks.
3807

3808
  """
3809
  _OP_REQP = ["instance_name"]
3810
  REQ_BGL = False
3811

    
3812
  def ExpandNames(self):
3813
    self._ExpandAndLockInstance()
3814
    self.needed_locks[locking.LEVEL_NODE] = []
3815
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3816

    
3817
  def DeclareLocks(self, level):
3818
    if level == locking.LEVEL_NODE:
3819
      self._LockInstancesNodes()
3820

    
3821
  def CheckPrereq(self):
3822
    """Check prerequisites.
3823

3824
    This checks that the instance is in the cluster.
3825

3826
    """
3827
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3828
    assert self.instance is not None, \
3829
      "Cannot retrieve locked instance %s" % self.op.instance_name
3830
    _CheckNodeOnline(self, self.instance.primary_node)
3831
    if not hasattr(self.op, "ignore_size"):
3832
      self.op.ignore_size = False
3833

    
3834
  def Exec(self, feedback_fn):
3835
    """Activate the disks.
3836

3837
    """
3838
    disks_ok, disks_info = \
3839
              _AssembleInstanceDisks(self, self.instance,
3840
                                     ignore_size=self.op.ignore_size)
3841
    if not disks_ok:
3842
      raise errors.OpExecError("Cannot activate block devices")
3843

    
3844
    return disks_info
3845

    
3846

    
3847
def _AssembleInstanceDisks(lu, instance, ignore_secondaries=False,
3848
                           ignore_size=False):
3849
  """Prepare the block devices for an instance.
3850

3851
  This sets up the block devices on all nodes.
3852

3853
  @type lu: L{LogicalUnit}
3854
  @param lu: the logical unit on whose behalf we execute
3855
  @type instance: L{objects.Instance}
3856
  @param instance: the instance for whose disks we assemble
3857
  @type ignore_secondaries: boolean
3858
  @param ignore_secondaries: if true, errors on secondary nodes
3859
      won't result in an error return from the function
3860
  @type ignore_size: boolean
3861
  @param ignore_size: if true, the current known size of the disk
3862
      will not be used during the disk activation, useful for cases
3863
      when the size is wrong
3864
  @return: False if the operation failed, otherwise a list of
3865
      (host, instance_visible_name, node_visible_name)
3866
      with the mapping from node devices to instance devices
3867

3868
  """
3869
  device_info = []
3870
  disks_ok = True
3871
  iname = instance.name
3872
  # With the two passes mechanism we try to reduce the window of
3873
  # opportunity for the race condition of switching DRBD to primary
3874
  # before handshaking occured, but we do not eliminate it
3875

    
3876
  # The proper fix would be to wait (with some limits) until the
3877
  # connection has been made and drbd transitions from WFConnection
3878
  # into any other network-connected state (Connected, SyncTarget,
3879
  # SyncSource, etc.)
3880

    
3881
  # 1st pass, assemble on all nodes in secondary mode
3882
  for inst_disk in instance.disks:
3883
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3884
      if ignore_size:
3885
        node_disk = node_disk.Copy()
3886
        node_disk.UnsetSize()
3887
      lu.cfg.SetDiskID(node_disk, node)
3888
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
3889
      msg = result.fail_msg
3890
      if msg:
3891
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3892
                           " (is_primary=False, pass=1): %s",
3893
                           inst_disk.iv_name, node, msg)
3894
        if not ignore_secondaries:
3895
          disks_ok = False
3896

    
3897
  # FIXME: race condition on drbd migration to primary
3898

    
3899
  # 2nd pass, do only the primary node
3900
  for inst_disk in instance.disks:
3901
    dev_path = None
3902

    
3903
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
3904
      if node != instance.primary_node:
3905
        continue
3906
      if ignore_size:
3907
        node_disk = node_disk.Copy()
3908
        node_disk.UnsetSize()
3909
      lu.cfg.SetDiskID(node_disk, node)
3910
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
3911
      msg = result.fail_msg
3912
      if msg:
3913
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
3914
                           " (is_primary=True, pass=2): %s",
3915
                           inst_disk.iv_name, node, msg)
3916
        disks_ok = False
3917
      else:
3918
        dev_path = result.payload
3919

    
3920
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
3921

    
3922
  # leave the disks configured for the primary node
3923
  # this is a workaround that would be fixed better by
3924
  # improving the logical/physical id handling
3925
  for disk in instance.disks:
3926
    lu.cfg.SetDiskID(disk, instance.primary_node)
3927

    
3928
  return disks_ok, device_info
3929

    
3930

    
3931
def _StartInstanceDisks(lu, instance, force):
3932
  """Start the disks of an instance.
3933

3934
  """
3935
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
3936
                                           ignore_secondaries=force)
3937
  if not disks_ok:
3938
    _ShutdownInstanceDisks(lu, instance)
3939
    if force is not None and not force:
3940
      lu.proc.LogWarning("", hint="If the message above refers to a"
3941
                         " secondary node,"
3942
                         " you can retry the operation using '--force'.")
3943
    raise errors.OpExecError("Disk consistency error")
3944

    
3945

    
3946
class LUDeactivateInstanceDisks(NoHooksLU):
3947
  """Shutdown an instance's disks.
3948

3949
  """
3950
  _OP_REQP = ["instance_name"]
3951
  REQ_BGL = False
3952

    
3953
  def ExpandNames(self):
3954
    self._ExpandAndLockInstance()
3955
    self.needed_locks[locking.LEVEL_NODE] = []
3956
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
3957

    
3958
  def DeclareLocks(self, level):
3959
    if level == locking.LEVEL_NODE:
3960
      self._LockInstancesNodes()
3961

    
3962
  def CheckPrereq(self):
3963
    """Check prerequisites.
3964

3965
    This checks that the instance is in the cluster.
3966

3967
    """
3968
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
3969
    assert self.instance is not None, \
3970
      "Cannot retrieve locked instance %s" % self.op.instance_name
3971

    
3972
  def Exec(self, feedback_fn):
3973
    """Deactivate the disks
3974

3975
    """
3976
    instance = self.instance
3977
    _SafeShutdownInstanceDisks(self, instance)
3978

    
3979

    
3980
def _SafeShutdownInstanceDisks(lu, instance):
3981
  """Shutdown block devices of an instance.
3982

3983
  This function checks if an instance is running, before calling
3984
  _ShutdownInstanceDisks.
3985

3986
  """
3987
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
3988
  _ShutdownInstanceDisks(lu, instance)
3989

    
3990

    
3991
def _ShutdownInstanceDisks(lu, instance, ignore_primary=False):
3992
  """Shutdown block devices of an instance.
3993

3994
  This does the shutdown on all nodes of the instance.
3995

3996
  If the ignore_primary is false, errors on the primary node are
3997
  ignored.
3998

3999
  """
4000
  all_result = True
4001
  for disk in instance.disks:
4002
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4003
      lu.cfg.SetDiskID(top_disk, node)
4004
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4005
      msg = result.fail_msg
4006
      if msg:
4007
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4008
                      disk.iv_name, node, msg)
4009
        if not ignore_primary or node != instance.primary_node:
4010
          all_result = False
4011
  return all_result
4012

    
4013

    
4014
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4015
  """Checks if a node has enough free memory.
4016

4017
  This function check if a given node has the needed amount of free
4018
  memory. In case the node has less memory or we cannot get the
4019
  information from the node, this function raise an OpPrereqError
4020
  exception.
4021

4022
  @type lu: C{LogicalUnit}
4023
  @param lu: a logical unit from which we get configuration data
4024
  @type node: C{str}
4025
  @param node: the node to check
4026
  @type reason: C{str}
4027
  @param reason: string to use in the error message
4028
  @type requested: C{int}
4029
  @param requested: the amount of memory in MiB to check for
4030
  @type hypervisor_name: C{str}
4031
  @param hypervisor_name: the hypervisor to ask for memory stats
4032
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4033
      we cannot check the node
4034

4035
  """
4036
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4037
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4038
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4039
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4040
  if not isinstance(free_mem, int):
4041
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4042
                               " was '%s'" % (node, free_mem),
4043
                               errors.ECODE_ENVIRON)
4044
  if requested > free_mem:
4045
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4046
                               " needed %s MiB, available %s MiB" %
4047
                               (node, reason, requested, free_mem),
4048
                               errors.ECODE_NORES)
4049

    
4050

    
4051
def _CheckNodesFreeDisk(lu, nodenames, requested):
4052
  """Checks if nodes have enough free disk space in the default VG.
4053

4054
  This function check if all given nodes have the needed amount of
4055
  free disk. In case any node has less disk or we cannot get the
4056
  information from the node, this function raise an OpPrereqError
4057
  exception.
4058

4059
  @type lu: C{LogicalUnit}
4060
  @param lu: a logical unit from which we get configuration data
4061
  @type nodenames: C{list}
4062
  @param nodenames: the list of node names to check
4063
  @type requested: C{int}
4064
  @param requested: the amount of disk in MiB to check for
4065
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4066
      we cannot check the node
4067

4068
  """
4069
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4070
                                   lu.cfg.GetHypervisorType())
4071
  for node in nodenames:
4072
    info = nodeinfo[node]
4073
    info.Raise("Cannot get current information from node %s" % node,
4074
               prereq=True, ecode=errors.ECODE_ENVIRON)
4075
    vg_free = info.payload.get("vg_free", None)
4076
    if not isinstance(vg_free, int):
4077
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4078
                                 " result was '%s'" % (node, vg_free),
4079
                                 errors.ECODE_ENVIRON)
4080
    if requested > vg_free:
4081
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4082
                                 " required %d MiB, available %d MiB" %
4083
                                 (node, requested, vg_free),
4084
                                 errors.ECODE_NORES)
4085

    
4086

    
4087
class LUStartupInstance(LogicalUnit):
4088
  """Starts an instance.
4089

4090
  """
4091
  HPATH = "instance-start"
4092
  HTYPE = constants.HTYPE_INSTANCE
4093
  _OP_REQP = ["instance_name", "force"]
4094
  REQ_BGL = False
4095

    
4096
  def ExpandNames(self):
4097
    self._ExpandAndLockInstance()
4098

    
4099
  def BuildHooksEnv(self):
4100
    """Build hooks env.
4101

4102
    This runs on master, primary and secondary nodes of the instance.
4103

4104
    """
4105
    env = {
4106
      "FORCE": self.op.force,
4107
      }
4108
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4109
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4110
    return env, nl, nl
4111

    
4112
  def CheckPrereq(self):
4113
    """Check prerequisites.
4114

4115
    This checks that the instance is in the cluster.
4116

4117
    """
4118
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4119
    assert self.instance is not None, \
4120
      "Cannot retrieve locked instance %s" % self.op.instance_name
4121

    
4122
    # extra beparams
4123
    self.beparams = getattr(self.op, "beparams", {})
4124
    if self.beparams:
4125
      if not isinstance(self.beparams, dict):
4126
        raise errors.OpPrereqError("Invalid beparams passed: %s, expected"
4127
                                   " dict" % (type(self.beparams), ),
4128
                                   errors.ECODE_INVAL)
4129
      # fill the beparams dict
4130
      utils.ForceDictType(self.beparams, constants.BES_PARAMETER_TYPES)
4131
      self.op.beparams = self.beparams
4132

    
4133
    # extra hvparams
4134
    self.hvparams = getattr(self.op, "hvparams", {})
4135
    if self.hvparams:
4136
      if not isinstance(self.hvparams, dict):
4137
        raise errors.OpPrereqError("Invalid hvparams passed: %s, expected"
4138
                                   " dict" % (type(self.hvparams), ),
4139
                                   errors.ECODE_INVAL)
4140

    
4141
      # check hypervisor parameter syntax (locally)
4142
      cluster = self.cfg.GetClusterInfo()
4143
      utils.ForceDictType(self.hvparams, constants.HVS_PARAMETER_TYPES)
4144
      filled_hvp = objects.FillDict(cluster.hvparams[instance.hypervisor],
4145
                                    instance.hvparams)
4146
      filled_hvp.update(self.hvparams)
4147
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4148
      hv_type.CheckParameterSyntax(filled_hvp)
4149
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4150
      self.op.hvparams = self.hvparams
4151

    
4152
    _CheckNodeOnline(self, instance.primary_node)
4153

    
4154
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4155
    # check bridges existence
4156
    _CheckInstanceBridgesExist(self, instance)
4157

    
4158
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4159
                                              instance.name,
4160
                                              instance.hypervisor)
4161
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4162
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4163
    if not remote_info.payload: # not running already
4164
      _CheckNodeFreeMemory(self, instance.primary_node,
4165
                           "starting instance %s" % instance.name,
4166
                           bep[constants.BE_MEMORY], instance.hypervisor)
4167

    
4168
  def Exec(self, feedback_fn):
4169
    """Start the instance.
4170

4171
    """
4172
    instance = self.instance
4173
    force = self.op.force
4174

    
4175
    self.cfg.MarkInstanceUp(instance.name)
4176

    
4177
    node_current = instance.primary_node
4178

    
4179
    _StartInstanceDisks(self, instance, force)
4180

    
4181
    result = self.rpc.call_instance_start(node_current, instance,
4182
                                          self.hvparams, self.beparams)
4183
    msg = result.fail_msg
4184
    if msg:
4185
      _ShutdownInstanceDisks(self, instance)
4186
      raise errors.OpExecError("Could not start instance: %s" % msg)
4187

    
4188

    
4189
class LURebootInstance(LogicalUnit):
4190
  """Reboot an instance.
4191

4192
  """
4193
  HPATH = "instance-reboot"
4194
  HTYPE = constants.HTYPE_INSTANCE
4195
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
4196
  REQ_BGL = False
4197

    
4198
  def CheckArguments(self):
4199
    """Check the arguments.
4200

4201
    """
4202
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4203
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4204

    
4205
  def ExpandNames(self):
4206
    if self.op.reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
4207
                                   constants.INSTANCE_REBOOT_HARD,
4208
                                   constants.INSTANCE_REBOOT_FULL]:
4209
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
4210
                                  (constants.INSTANCE_REBOOT_SOFT,
4211
                                   constants.INSTANCE_REBOOT_HARD,
4212
                                   constants.INSTANCE_REBOOT_FULL))
4213
    self._ExpandAndLockInstance()
4214

    
4215
  def BuildHooksEnv(self):
4216
    """Build hooks env.
4217

4218
    This runs on master, primary and secondary nodes of the instance.
4219

4220
    """
4221
    env = {
4222
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4223
      "REBOOT_TYPE": self.op.reboot_type,
4224
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4225
      }
4226
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4227
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4228
    return env, nl, nl
4229

    
4230
  def CheckPrereq(self):
4231
    """Check prerequisites.
4232

4233
    This checks that the instance is in the cluster.
4234

4235
    """
4236
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4237
    assert self.instance is not None, \
4238
      "Cannot retrieve locked instance %s" % self.op.instance_name
4239

    
4240
    _CheckNodeOnline(self, instance.primary_node)
4241

    
4242
    # check bridges existence
4243
    _CheckInstanceBridgesExist(self, instance)
4244

    
4245
  def Exec(self, feedback_fn):
4246
    """Reboot the instance.
4247

4248
    """
4249
    instance = self.instance
4250
    ignore_secondaries = self.op.ignore_secondaries
4251
    reboot_type = self.op.reboot_type
4252

    
4253
    node_current = instance.primary_node
4254

    
4255
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4256
                       constants.INSTANCE_REBOOT_HARD]:
4257
      for disk in instance.disks:
4258
        self.cfg.SetDiskID(disk, node_current)
4259
      result = self.rpc.call_instance_reboot(node_current, instance,
4260
                                             reboot_type,
4261
                                             self.shutdown_timeout)
4262
      result.Raise("Could not reboot instance")
4263
    else:
4264
      result = self.rpc.call_instance_shutdown(node_current, instance,
4265
                                               self.shutdown_timeout)
4266
      result.Raise("Could not shutdown instance for full reboot")
4267
      _ShutdownInstanceDisks(self, instance)
4268
      _StartInstanceDisks(self, instance, ignore_secondaries)
4269
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4270
      msg = result.fail_msg
4271
      if msg:
4272
        _ShutdownInstanceDisks(self, instance)
4273
        raise errors.OpExecError("Could not start instance for"
4274
                                 " full reboot: %s" % msg)
4275

    
4276
    self.cfg.MarkInstanceUp(instance.name)
4277

    
4278

    
4279
class LUShutdownInstance(LogicalUnit):
4280
  """Shutdown an instance.
4281

4282
  """
4283
  HPATH = "instance-stop"
4284
  HTYPE = constants.HTYPE_INSTANCE
4285
  _OP_REQP = ["instance_name"]
4286
  REQ_BGL = False
4287

    
4288
  def CheckArguments(self):
4289
    """Check the arguments.
4290

4291
    """
4292
    self.timeout = getattr(self.op, "timeout",
4293
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
4294

    
4295
  def ExpandNames(self):
4296
    self._ExpandAndLockInstance()
4297

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

4301
    This runs on master, primary and secondary nodes of the instance.
4302

4303
    """
4304
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4305
    env["TIMEOUT"] = self.timeout
4306
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4307
    return env, nl, nl
4308

    
4309
  def CheckPrereq(self):
4310
    """Check prerequisites.
4311

4312
    This checks that the instance is in the cluster.
4313

4314
    """
4315
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4316
    assert self.instance is not None, \
4317
      "Cannot retrieve locked instance %s" % self.op.instance_name
4318
    _CheckNodeOnline(self, self.instance.primary_node)
4319

    
4320
  def Exec(self, feedback_fn):
4321
    """Shutdown the instance.
4322

4323
    """
4324
    instance = self.instance
4325
    node_current = instance.primary_node
4326
    timeout = self.timeout
4327
    self.cfg.MarkInstanceDown(instance.name)
4328
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4329
    msg = result.fail_msg
4330
    if msg:
4331
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4332

    
4333
    _ShutdownInstanceDisks(self, instance)
4334

    
4335

    
4336
class LUReinstallInstance(LogicalUnit):
4337
  """Reinstall an instance.
4338

4339
  """
4340
  HPATH = "instance-reinstall"
4341
  HTYPE = constants.HTYPE_INSTANCE
4342
  _OP_REQP = ["instance_name"]
4343
  REQ_BGL = False
4344

    
4345
  def ExpandNames(self):
4346
    self._ExpandAndLockInstance()
4347

    
4348
  def BuildHooksEnv(self):
4349
    """Build hooks env.
4350

4351
    This runs on master, primary and secondary nodes of the instance.
4352

4353
    """
4354
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4355
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4356
    return env, nl, nl
4357

    
4358
  def CheckPrereq(self):
4359
    """Check prerequisites.
4360

4361
    This checks that the instance is in the cluster and is not running.
4362

4363
    """
4364
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4365
    assert instance is not None, \
4366
      "Cannot retrieve locked instance %s" % self.op.instance_name
4367
    _CheckNodeOnline(self, instance.primary_node)
4368

    
4369
    if instance.disk_template == constants.DT_DISKLESS:
4370
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4371
                                 self.op.instance_name,
4372
                                 errors.ECODE_INVAL)
4373
    _CheckInstanceDown(self, instance, "cannot reinstall")
4374

    
4375
    self.op.os_type = getattr(self.op, "os_type", None)
4376
    self.op.force_variant = getattr(self.op, "force_variant", False)
4377
    if self.op.os_type is not None:
4378
      # OS verification
4379
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4380
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4381

    
4382
    self.instance = instance
4383

    
4384
  def Exec(self, feedback_fn):
4385
    """Reinstall the instance.
4386

4387
    """
4388
    inst = self.instance
4389

    
4390
    if self.op.os_type is not None:
4391
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4392
      inst.os = self.op.os_type
4393
      self.cfg.Update(inst, feedback_fn)
4394

    
4395
    _StartInstanceDisks(self, inst, None)
4396
    try:
4397
      feedback_fn("Running the instance OS create scripts...")
4398
      # FIXME: pass debug option from opcode to backend
4399
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4400
                                             self.op.debug_level)
4401
      result.Raise("Could not install OS for instance %s on node %s" %
4402
                   (inst.name, inst.primary_node))
4403
    finally:
4404
      _ShutdownInstanceDisks(self, inst)
4405

    
4406

    
4407
class LURecreateInstanceDisks(LogicalUnit):
4408
  """Recreate an instance's missing disks.
4409

4410
  """
4411
  HPATH = "instance-recreate-disks"
4412
  HTYPE = constants.HTYPE_INSTANCE
4413
  _OP_REQP = ["instance_name", "disks"]
4414
  REQ_BGL = False
4415

    
4416
  def CheckArguments(self):
4417
    """Check the arguments.
4418

4419
    """
4420
    if not isinstance(self.op.disks, list):
4421
      raise errors.OpPrereqError("Invalid disks parameter", errors.ECODE_INVAL)
4422
    for item in self.op.disks:
4423
      if (not isinstance(item, int) or
4424
          item < 0):
4425
        raise errors.OpPrereqError("Invalid disk specification '%s'" %
4426
                                   str(item), errors.ECODE_INVAL)
4427

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

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

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

4436
    """
4437
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4438
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4439
    return env, nl, nl
4440

    
4441
  def CheckPrereq(self):
4442
    """Check prerequisites.
4443

4444
    This checks that the instance is in the cluster and is not running.
4445

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

    
4452
    if instance.disk_template == constants.DT_DISKLESS:
4453
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4454
                                 self.op.instance_name, errors.ECODE_INVAL)
4455
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4456

    
4457
    if not self.op.disks:
4458
      self.op.disks = range(len(instance.disks))
4459
    else:
4460
      for idx in self.op.disks:
4461
        if idx >= len(instance.disks):
4462
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4463
                                     errors.ECODE_INVAL)
4464

    
4465
    self.instance = instance
4466

    
4467
  def Exec(self, feedback_fn):
4468
    """Recreate the disks.
4469

4470
    """
4471
    to_skip = []
4472
    for idx, _ in enumerate(self.instance.disks):
4473
      if idx not in self.op.disks: # disk idx has not been passed in
4474
        to_skip.append(idx)
4475
        continue
4476

    
4477
    _CreateDisks(self, self.instance, to_skip=to_skip)
4478

    
4479

    
4480
class LURenameInstance(LogicalUnit):
4481
  """Rename an instance.
4482

4483
  """
4484
  HPATH = "instance-rename"
4485
  HTYPE = constants.HTYPE_INSTANCE
4486
  _OP_REQP = ["instance_name", "new_name"]
4487

    
4488
  def BuildHooksEnv(self):
4489
    """Build hooks env.
4490

4491
    This runs on master, primary and secondary nodes of the instance.
4492

4493
    """
4494
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4495
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4496
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4497
    return env, nl, nl
4498

    
4499
  def CheckPrereq(self):
4500
    """Check prerequisites.
4501

4502
    This checks that the instance is in the cluster and is not running.
4503

4504
    """
4505
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4506
                                                self.op.instance_name)
4507
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4508
    assert instance is not None
4509
    _CheckNodeOnline(self, instance.primary_node)
4510
    _CheckInstanceDown(self, instance, "cannot rename")
4511
    self.instance = instance
4512

    
4513
    # new name verification
4514
    name_info = utils.GetHostInfo(self.op.new_name)
4515

    
4516
    self.op.new_name = new_name = name_info.name
4517
    instance_list = self.cfg.GetInstanceList()
4518
    if new_name in instance_list:
4519
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4520
                                 new_name, errors.ECODE_EXISTS)
4521

    
4522
    if not getattr(self.op, "ignore_ip", False):
4523
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4524
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4525
                                   (name_info.ip, new_name),
4526
                                   errors.ECODE_NOTUNIQUE)
4527

    
4528

    
4529
  def Exec(self, feedback_fn):
4530
    """Reinstall the instance.
4531

4532
    """
4533
    inst = self.instance
4534
    old_name = inst.name
4535

    
4536
    if inst.disk_template == constants.DT_FILE:
4537
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4538

    
4539
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4540
    # Change the instance lock. This is definitely safe while we hold the BGL
4541
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4542
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4543

    
4544
    # re-read the instance from the configuration after rename
4545
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4546

    
4547
    if inst.disk_template == constants.DT_FILE:
4548
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4549
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4550
                                                     old_file_storage_dir,
4551
                                                     new_file_storage_dir)
4552
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4553
                   " (but the instance has been renamed in Ganeti)" %
4554
                   (inst.primary_node, old_file_storage_dir,
4555
                    new_file_storage_dir))
4556

    
4557
    _StartInstanceDisks(self, inst, None)
4558
    try:
4559
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4560
                                                 old_name, self.op.debug_level)
4561
      msg = result.fail_msg
4562
      if msg:
4563
        msg = ("Could not run OS rename script for instance %s on node %s"
4564
               " (but the instance has been renamed in Ganeti): %s" %
4565
               (inst.name, inst.primary_node, msg))
4566
        self.proc.LogWarning(msg)
4567
    finally:
4568
      _ShutdownInstanceDisks(self, inst)
4569

    
4570

    
4571
class LURemoveInstance(LogicalUnit):
4572
  """Remove an instance.
4573

4574
  """
4575
  HPATH = "instance-remove"
4576
  HTYPE = constants.HTYPE_INSTANCE
4577
  _OP_REQP = ["instance_name", "ignore_failures"]
4578
  REQ_BGL = False
4579

    
4580
  def CheckArguments(self):
4581
    """Check the arguments.
4582

4583
    """
4584
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4585
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4586

    
4587
  def ExpandNames(self):
4588
    self._ExpandAndLockInstance()
4589
    self.needed_locks[locking.LEVEL_NODE] = []
4590
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4591

    
4592
  def DeclareLocks(self, level):
4593
    if level == locking.LEVEL_NODE:
4594
      self._LockInstancesNodes()
4595

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

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

4601
    """
4602
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4603
    env["SHUTDOWN_TIMEOUT"] = self.shutdown_timeout
4604
    nl = [self.cfg.GetMasterNode()]
4605
    nl_post = list(self.instance.all_nodes) + nl
4606
    return env, nl, nl_post
4607

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

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

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

    
4618
  def Exec(self, feedback_fn):
4619
    """Remove the instance.
4620

4621
    """
4622
    instance = self.instance
4623
    logging.info("Shutting down instance %s on node %s",
4624
                 instance.name, instance.primary_node)
4625

    
4626
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4627
                                             self.shutdown_timeout)
4628
    msg = result.fail_msg
4629
    if msg:
4630
      if self.op.ignore_failures:
4631
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4632
      else:
4633
        raise errors.OpExecError("Could not shutdown instance %s on"
4634
                                 " node %s: %s" %
4635
                                 (instance.name, instance.primary_node, msg))
4636

    
4637
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
4638

    
4639

    
4640
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
4641
  """Utility function to remove an instance.
4642

4643
  """
4644
  logging.info("Removing block devices for instance %s", instance.name)
4645

    
4646
  if not _RemoveDisks(lu, instance):
4647
    if not ignore_failures:
4648
      raise errors.OpExecError("Can't remove instance's disks")
4649
    feedback_fn("Warning: can't remove instance's disks")
4650

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

    
4653
  lu.cfg.RemoveInstance(instance.name)
4654

    
4655
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
4656
    "Instance lock removal conflict"
4657

    
4658
  # Remove lock for the instance
4659
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4660

    
4661

    
4662
class LUQueryInstances(NoHooksLU):
4663
  """Logical unit for querying instances.
4664

4665
  """
4666
  # pylint: disable-msg=W0142
4667
  _OP_REQP = ["output_fields", "names", "use_locking"]
4668
  REQ_BGL = False
4669
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4670
                    "serial_no", "ctime", "mtime", "uuid"]
4671
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4672
                                    "admin_state",
4673
                                    "disk_template", "ip", "mac", "bridge",
4674
                                    "nic_mode", "nic_link",
4675
                                    "sda_size", "sdb_size", "vcpus", "tags",
4676
                                    "network_port", "beparams",
4677
                                    r"(disk)\.(size)/([0-9]+)",
4678
                                    r"(disk)\.(sizes)", "disk_usage",
4679
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4680
                                    r"(nic)\.(bridge)/([0-9]+)",
4681
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4682
                                    r"(disk|nic)\.(count)",
4683
                                    "hvparams",
4684
                                    ] + _SIMPLE_FIELDS +
4685
                                  ["hv/%s" % name
4686
                                   for name in constants.HVS_PARAMETERS
4687
                                   if name not in constants.HVC_GLOBALS] +
4688
                                  ["be/%s" % name
4689
                                   for name in constants.BES_PARAMETERS])
4690
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4691

    
4692

    
4693
  def ExpandNames(self):
4694
    _CheckOutputFields(static=self._FIELDS_STATIC,
4695
                       dynamic=self._FIELDS_DYNAMIC,
4696
                       selected=self.op.output_fields)
4697

    
4698
    self.needed_locks = {}
4699
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4700
    self.share_locks[locking.LEVEL_NODE] = 1
4701

    
4702
    if self.op.names:
4703
      self.wanted = _GetWantedInstances(self, self.op.names)
4704
    else:
4705
      self.wanted = locking.ALL_SET
4706

    
4707
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4708
    self.do_locking = self.do_node_query and self.op.use_locking
4709
    if self.do_locking:
4710
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4711
      self.needed_locks[locking.LEVEL_NODE] = []
4712
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4713

    
4714
  def DeclareLocks(self, level):
4715
    if level == locking.LEVEL_NODE and self.do_locking:
4716
      self._LockInstancesNodes()
4717

    
4718
  def CheckPrereq(self):
4719
    """Check prerequisites.
4720

4721
    """
4722
    pass
4723

    
4724
  def Exec(self, feedback_fn):
4725
    """Computes the list of nodes and their attributes.
4726

4727
    """
4728
    # pylint: disable-msg=R0912
4729
    # way too many branches here
4730
    all_info = self.cfg.GetAllInstancesInfo()
4731
    if self.wanted == locking.ALL_SET:
4732
      # caller didn't specify instance names, so ordering is not important
4733
      if self.do_locking:
4734
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
4735
      else:
4736
        instance_names = all_info.keys()
4737
      instance_names = utils.NiceSort(instance_names)
4738
    else:
4739
      # caller did specify names, so we must keep the ordering
4740
      if self.do_locking:
4741
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
4742
      else:
4743
        tgt_set = all_info.keys()
4744
      missing = set(self.wanted).difference(tgt_set)
4745
      if missing:
4746
        raise errors.OpExecError("Some instances were removed before"
4747
                                 " retrieving their data: %s" % missing)
4748
      instance_names = self.wanted
4749

    
4750
    instance_list = [all_info[iname] for iname in instance_names]
4751

    
4752
    # begin data gathering
4753

    
4754
    nodes = frozenset([inst.primary_node for inst in instance_list])
4755
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4756

    
4757
    bad_nodes = []
4758
    off_nodes = []
4759
    if self.do_node_query:
4760
      live_data = {}
4761
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
4762
      for name in nodes:
4763
        result = node_data[name]
4764
        if result.offline:
4765
          # offline nodes will be in both lists
4766
          off_nodes.append(name)
4767
        if result.fail_msg:
4768
          bad_nodes.append(name)
4769
        else:
4770
          if result.payload:
4771
            live_data.update(result.payload)
4772
          # else no instance is alive
4773
    else:
4774
      live_data = dict([(name, {}) for name in instance_names])
4775

    
4776
    # end data gathering
4777

    
4778
    HVPREFIX = "hv/"
4779
    BEPREFIX = "be/"
4780
    output = []
4781
    cluster = self.cfg.GetClusterInfo()
4782
    for instance in instance_list:
4783
      iout = []
4784
      i_hv = cluster.FillHV(instance, skip_globals=True)
4785
      i_be = cluster.FillBE(instance)
4786
      i_nicp = [objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
4787
                                 nic.nicparams) for nic in instance.nics]
4788
      for field in self.op.output_fields:
4789
        st_match = self._FIELDS_STATIC.Matches(field)
4790
        if field in self._SIMPLE_FIELDS:
4791
          val = getattr(instance, field)
4792
        elif field == "pnode":
4793
          val = instance.primary_node
4794
        elif field == "snodes":
4795
          val = list(instance.secondary_nodes)
4796
        elif field == "admin_state":
4797
          val = instance.admin_up
4798
        elif field == "oper_state":
4799
          if instance.primary_node in bad_nodes:
4800
            val = None
4801
          else:
4802
            val = bool(live_data.get(instance.name))
4803
        elif field == "status":
4804
          if instance.primary_node in off_nodes:
4805
            val = "ERROR_nodeoffline"
4806
          elif instance.primary_node in bad_nodes:
4807
            val = "ERROR_nodedown"
4808
          else:
4809
            running = bool(live_data.get(instance.name))
4810
            if running:
4811
              if instance.admin_up:
4812
                val = "running"
4813
              else:
4814
                val = "ERROR_up"
4815
            else:
4816
              if instance.admin_up:
4817
                val = "ERROR_down"
4818
              else:
4819
                val = "ADMIN_down"
4820
        elif field == "oper_ram":
4821
          if instance.primary_node in bad_nodes:
4822
            val = None
4823
          elif instance.name in live_data:
4824
            val = live_data[instance.name].get("memory", "?")
4825
          else:
4826
            val = "-"
4827
        elif field == "vcpus":
4828
          val = i_be[constants.BE_VCPUS]
4829
        elif field == "disk_template":
4830
          val = instance.disk_template
4831
        elif field == "ip":
4832
          if instance.nics:
4833
            val = instance.nics[0].ip
4834
          else:
4835
            val = None
4836
        elif field == "nic_mode":
4837
          if instance.nics:
4838
            val = i_nicp[0][constants.NIC_MODE]
4839
          else:
4840
            val = None
4841
        elif field == "nic_link":
4842
          if instance.nics:
4843
            val = i_nicp[0][constants.NIC_LINK]
4844
          else:
4845
            val = None
4846
        elif field == "bridge":
4847
          if (instance.nics and
4848
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
4849
            val = i_nicp[0][constants.NIC_LINK]
4850
          else:
4851
            val = None
4852
        elif field == "mac":
4853
          if instance.nics:
4854
            val = instance.nics[0].mac
4855
          else:
4856
            val = None
4857
        elif field == "sda_size" or field == "sdb_size":
4858
          idx = ord(field[2]) - ord('a')
4859
          try:
4860
            val = instance.FindDisk(idx).size
4861
          except errors.OpPrereqError:
4862
            val = None
4863
        elif field == "disk_usage": # total disk usage per node
4864
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
4865
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
4866
        elif field == "tags":
4867
          val = list(instance.GetTags())
4868
        elif field == "hvparams":
4869
          val = i_hv
4870
        elif (field.startswith(HVPREFIX) and
4871
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
4872
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
4873
          val = i_hv.get(field[len(HVPREFIX):], None)
4874
        elif field == "beparams":
4875
          val = i_be
4876
        elif (field.startswith(BEPREFIX) and
4877
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
4878
          val = i_be.get(field[len(BEPREFIX):], None)
4879
        elif st_match and st_match.groups():
4880
          # matches a variable list
4881
          st_groups = st_match.groups()
4882
          if st_groups and st_groups[0] == "disk":
4883
            if st_groups[1] == "count":
4884
              val = len(instance.disks)
4885
            elif st_groups[1] == "sizes":
4886
              val = [disk.size for disk in instance.disks]
4887
            elif st_groups[1] == "size":
4888
              try:
4889
                val = instance.FindDisk(st_groups[2]).size
4890
              except errors.OpPrereqError:
4891
                val = None
4892
            else:
4893
              assert False, "Unhandled disk parameter"
4894
          elif st_groups[0] == "nic":
4895
            if st_groups[1] == "count":
4896
              val = len(instance.nics)
4897
            elif st_groups[1] == "macs":
4898
              val = [nic.mac for nic in instance.nics]
4899
            elif st_groups[1] == "ips":
4900
              val = [nic.ip for nic in instance.nics]
4901
            elif st_groups[1] == "modes":
4902
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
4903
            elif st_groups[1] == "links":
4904
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
4905
            elif st_groups[1] == "bridges":
4906
              val = []
4907
              for nicp in i_nicp:
4908
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
4909
                  val.append(nicp[constants.NIC_LINK])
4910
                else:
4911
                  val.append(None)
4912
            else:
4913
              # index-based item
4914
              nic_idx = int(st_groups[2])
4915
              if nic_idx >= len(instance.nics):
4916
                val = None
4917
              else:
4918
                if st_groups[1] == "mac":
4919
                  val = instance.nics[nic_idx].mac
4920
                elif st_groups[1] == "ip":
4921
                  val = instance.nics[nic_idx].ip
4922
                elif st_groups[1] == "mode":
4923
                  val = i_nicp[nic_idx][constants.NIC_MODE]
4924
                elif st_groups[1] == "link":
4925
                  val = i_nicp[nic_idx][constants.NIC_LINK]
4926
                elif st_groups[1] == "bridge":
4927
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
4928
                  if nic_mode == constants.NIC_MODE_BRIDGED:
4929
                    val = i_nicp[nic_idx][constants.NIC_LINK]
4930
                  else:
4931
                    val = None
4932
                else:
4933
                  assert False, "Unhandled NIC parameter"
4934
          else:
4935
            assert False, ("Declared but unhandled variable parameter '%s'" %
4936
                           field)
4937
        else:
4938
          assert False, "Declared but unhandled parameter '%s'" % field
4939
        iout.append(val)
4940
      output.append(iout)
4941

    
4942
    return output
4943

    
4944

    
4945
class LUFailoverInstance(LogicalUnit):
4946
  """Failover an instance.
4947

4948
  """
4949
  HPATH = "instance-failover"
4950
  HTYPE = constants.HTYPE_INSTANCE
4951
  _OP_REQP = ["instance_name", "ignore_consistency"]
4952
  REQ_BGL = False
4953

    
4954
  def CheckArguments(self):
4955
    """Check the arguments.
4956

4957
    """
4958
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
4959
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
4960

    
4961
  def ExpandNames(self):
4962
    self._ExpandAndLockInstance()
4963
    self.needed_locks[locking.LEVEL_NODE] = []
4964
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4965

    
4966
  def DeclareLocks(self, level):
4967
    if level == locking.LEVEL_NODE:
4968
      self._LockInstancesNodes()
4969

    
4970
  def BuildHooksEnv(self):
4971
    """Build hooks env.
4972

4973
    This runs on master, primary and secondary nodes of the instance.
4974

4975
    """
4976
    instance = self.instance
4977
    source_node = instance.primary_node
4978
    target_node = instance.secondary_nodes[0]
4979
    env = {
4980
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
4981
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
4982
      "OLD_PRIMARY": source_node,
4983
      "OLD_SECONDARY": target_node,
4984
      "NEW_PRIMARY": target_node,
4985
      "NEW_SECONDARY": source_node,
4986
      }
4987
    env.update(_BuildInstanceHookEnvByObject(self, instance))
4988
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
4989
    nl_post = list(nl)
4990
    nl_post.append(source_node)
4991
    return env, nl, nl_post
4992

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

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

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

    
5003
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5004
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5005
      raise errors.OpPrereqError("Instance's disk layout is not"
5006
                                 " network mirrored, cannot failover.",
5007
                                 errors.ECODE_STATE)
5008

    
5009
    secondary_nodes = instance.secondary_nodes
5010
    if not secondary_nodes:
5011
      raise errors.ProgrammerError("no secondary node but using "
5012
                                   "a mirrored disk template")
5013

    
5014
    target_node = secondary_nodes[0]
5015
    _CheckNodeOnline(self, target_node)
5016
    _CheckNodeNotDrained(self, target_node)
5017
    if instance.admin_up:
5018
      # check memory requirements on the secondary node
5019
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5020
                           instance.name, bep[constants.BE_MEMORY],
5021
                           instance.hypervisor)
5022
    else:
5023
      self.LogInfo("Not checking memory on the secondary node as"
5024
                   " instance will not be started")
5025

    
5026
    # check bridge existance
5027
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5028

    
5029
  def Exec(self, feedback_fn):
5030
    """Failover an instance.
5031

5032
    The failover is done by shutting it down on its present node and
5033
    starting it on the secondary.
5034

5035
    """
5036
    instance = self.instance
5037

    
5038
    source_node = instance.primary_node
5039
    target_node = instance.secondary_nodes[0]
5040

    
5041
    if instance.admin_up:
5042
      feedback_fn("* checking disk consistency between source and target")
5043
      for dev in instance.disks:
5044
        # for drbd, these are drbd over lvm
5045
        if not _CheckDiskConsistency(self, dev, target_node, False):
5046
          if not self.op.ignore_consistency:
5047
            raise errors.OpExecError("Disk %s is degraded on target node,"
5048
                                     " aborting failover." % dev.iv_name)
5049
    else:
5050
      feedback_fn("* not checking disk consistency as instance is not running")
5051

    
5052
    feedback_fn("* shutting down instance on source node")
5053
    logging.info("Shutting down instance %s on node %s",
5054
                 instance.name, source_node)
5055

    
5056
    result = self.rpc.call_instance_shutdown(source_node, instance,
5057
                                             self.shutdown_timeout)
5058
    msg = result.fail_msg
5059
    if msg:
5060
      if self.op.ignore_consistency:
5061
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5062
                             " Proceeding anyway. Please make sure node"
5063
                             " %s is down. Error details: %s",
5064
                             instance.name, source_node, source_node, msg)
5065
      else:
5066
        raise errors.OpExecError("Could not shutdown instance %s on"
5067
                                 " node %s: %s" %
5068
                                 (instance.name, source_node, msg))
5069

    
5070
    feedback_fn("* deactivating the instance's disks on source node")
5071
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5072
      raise errors.OpExecError("Can't shut down the instance's disks.")
5073

    
5074
    instance.primary_node = target_node
5075
    # distribute new instance config to the other nodes
5076
    self.cfg.Update(instance, feedback_fn)
5077

    
5078
    # Only start the instance if it's marked as up
5079
    if instance.admin_up:
5080
      feedback_fn("* activating the instance's disks on target node")
5081
      logging.info("Starting instance %s on node %s",
5082
                   instance.name, target_node)
5083

    
5084
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5085
                                               ignore_secondaries=True)
5086
      if not disks_ok:
5087
        _ShutdownInstanceDisks(self, instance)
5088
        raise errors.OpExecError("Can't activate the instance's disks")
5089

    
5090
      feedback_fn("* starting the instance on the target node")
5091
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5092
      msg = result.fail_msg
5093
      if msg:
5094
        _ShutdownInstanceDisks(self, instance)
5095
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5096
                                 (instance.name, target_node, msg))
5097

    
5098

    
5099
class LUMigrateInstance(LogicalUnit):
5100
  """Migrate an instance.
5101

5102
  This is migration without shutting down, compared to the failover,
5103
  which is done with shutdown.
5104

5105
  """
5106
  HPATH = "instance-migrate"
5107
  HTYPE = constants.HTYPE_INSTANCE
5108
  _OP_REQP = ["instance_name", "live", "cleanup"]
5109

    
5110
  REQ_BGL = False
5111

    
5112
  def ExpandNames(self):
5113
    self._ExpandAndLockInstance()
5114

    
5115
    self.needed_locks[locking.LEVEL_NODE] = []
5116
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5117

    
5118
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5119
                                       self.op.live, self.op.cleanup)
5120
    self.tasklets = [self._migrater]
5121

    
5122
  def DeclareLocks(self, level):
5123
    if level == locking.LEVEL_NODE:
5124
      self._LockInstancesNodes()
5125

    
5126
  def BuildHooksEnv(self):
5127
    """Build hooks env.
5128

5129
    This runs on master, primary and secondary nodes of the instance.
5130

5131
    """
5132
    instance = self._migrater.instance
5133
    source_node = instance.primary_node
5134
    target_node = instance.secondary_nodes[0]
5135
    env = _BuildInstanceHookEnvByObject(self, instance)
5136
    env["MIGRATE_LIVE"] = self.op.live
5137
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5138
    env.update({
5139
        "OLD_PRIMARY": source_node,
5140
        "OLD_SECONDARY": target_node,
5141
        "NEW_PRIMARY": target_node,
5142
        "NEW_SECONDARY": source_node,
5143
        })
5144
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5145
    nl_post = list(nl)
5146
    nl_post.append(source_node)
5147
    return env, nl, nl_post
5148

    
5149

    
5150
class LUMoveInstance(LogicalUnit):
5151
  """Move an instance by data-copying.
5152

5153
  """
5154
  HPATH = "instance-move"
5155
  HTYPE = constants.HTYPE_INSTANCE
5156
  _OP_REQP = ["instance_name", "target_node"]
5157
  REQ_BGL = False
5158

    
5159
  def CheckArguments(self):
5160
    """Check the arguments.
5161

5162
    """
5163
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
5164
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
5165

    
5166
  def ExpandNames(self):
5167
    self._ExpandAndLockInstance()
5168
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5169
    self.op.target_node = target_node
5170
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5171
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5172

    
5173
  def DeclareLocks(self, level):
5174
    if level == locking.LEVEL_NODE:
5175
      self._LockInstancesNodes(primary_only=True)
5176

    
5177
  def BuildHooksEnv(self):
5178
    """Build hooks env.
5179

5180
    This runs on master, primary and secondary nodes of the instance.
5181

5182
    """
5183
    env = {
5184
      "TARGET_NODE": self.op.target_node,
5185
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
5186
      }
5187
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5188
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5189
                                       self.op.target_node]
5190
    return env, nl, nl
5191

    
5192
  def CheckPrereq(self):
5193
    """Check prerequisites.
5194

5195
    This checks that the instance is in the cluster.
5196

5197
    """
5198
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5199
    assert self.instance is not None, \
5200
      "Cannot retrieve locked instance %s" % self.op.instance_name
5201

    
5202
    node = self.cfg.GetNodeInfo(self.op.target_node)
5203
    assert node is not None, \
5204
      "Cannot retrieve locked node %s" % self.op.target_node
5205

    
5206
    self.target_node = target_node = node.name
5207

    
5208
    if target_node == instance.primary_node:
5209
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5210
                                 (instance.name, target_node),
5211
                                 errors.ECODE_STATE)
5212

    
5213
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5214

    
5215
    for idx, dsk in enumerate(instance.disks):
5216
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5217
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5218
                                   " cannot copy" % idx, errors.ECODE_STATE)
5219

    
5220
    _CheckNodeOnline(self, target_node)
5221
    _CheckNodeNotDrained(self, target_node)
5222

    
5223
    if instance.admin_up:
5224
      # check memory requirements on the secondary node
5225
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5226
                           instance.name, bep[constants.BE_MEMORY],
5227
                           instance.hypervisor)
5228
    else:
5229
      self.LogInfo("Not checking memory on the secondary node as"
5230
                   " instance will not be started")
5231

    
5232
    # check bridge existance
5233
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5234

    
5235
  def Exec(self, feedback_fn):
5236
    """Move an instance.
5237

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

5241
    """
5242
    instance = self.instance
5243

    
5244
    source_node = instance.primary_node
5245
    target_node = self.target_node
5246

    
5247
    self.LogInfo("Shutting down instance %s on source node %s",
5248
                 instance.name, source_node)
5249

    
5250
    result = self.rpc.call_instance_shutdown(source_node, instance,
5251
                                             self.shutdown_timeout)
5252
    msg = result.fail_msg
5253
    if msg:
5254
      if self.op.ignore_consistency:
5255
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5256
                             " Proceeding anyway. Please make sure node"
5257
                             " %s is down. Error details: %s",
5258
                             instance.name, source_node, source_node, msg)
5259
      else:
5260
        raise errors.OpExecError("Could not shutdown instance %s on"
5261
                                 " node %s: %s" %
5262
                                 (instance.name, source_node, msg))
5263

    
5264
    # create the target disks
5265
    try:
5266
      _CreateDisks(self, instance, target_node=target_node)
5267
    except errors.OpExecError:
5268
      self.LogWarning("Device creation failed, reverting...")
5269
      try:
5270
        _RemoveDisks(self, instance, target_node=target_node)
5271
      finally:
5272
        self.cfg.ReleaseDRBDMinors(instance.name)
5273
        raise
5274

    
5275
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5276

    
5277
    errs = []
5278
    # activate, get path, copy the data over
5279
    for idx, disk in enumerate(instance.disks):
5280
      self.LogInfo("Copying data for disk %d", idx)
5281
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5282
                                               instance.name, True)
5283
      if result.fail_msg:
5284
        self.LogWarning("Can't assemble newly created disk %d: %s",
5285
                        idx, result.fail_msg)
5286
        errs.append(result.fail_msg)
5287
        break
5288
      dev_path = result.payload
5289
      result = self.rpc.call_blockdev_export(source_node, disk,
5290
                                             target_node, dev_path,
5291
                                             cluster_name)
5292
      if result.fail_msg:
5293
        self.LogWarning("Can't copy data over for disk %d: %s",
5294
                        idx, result.fail_msg)
5295
        errs.append(result.fail_msg)
5296
        break
5297

    
5298
    if errs:
5299
      self.LogWarning("Some disks failed to copy, aborting")
5300
      try:
5301
        _RemoveDisks(self, instance, target_node=target_node)
5302
      finally:
5303
        self.cfg.ReleaseDRBDMinors(instance.name)
5304
        raise errors.OpExecError("Errors during disk copy: %s" %
5305
                                 (",".join(errs),))
5306

    
5307
    instance.primary_node = target_node
5308
    self.cfg.Update(instance, feedback_fn)
5309

    
5310
    self.LogInfo("Removing the disks on the original node")
5311
    _RemoveDisks(self, instance, target_node=source_node)
5312

    
5313
    # Only start the instance if it's marked as up
5314
    if instance.admin_up:
5315
      self.LogInfo("Starting instance %s on node %s",
5316
                   instance.name, target_node)
5317

    
5318
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5319
                                           ignore_secondaries=True)
5320
      if not disks_ok:
5321
        _ShutdownInstanceDisks(self, instance)
5322
        raise errors.OpExecError("Can't activate the instance's disks")
5323

    
5324
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5325
      msg = result.fail_msg
5326
      if msg:
5327
        _ShutdownInstanceDisks(self, instance)
5328
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5329
                                 (instance.name, target_node, msg))
5330

    
5331

    
5332
class LUMigrateNode(LogicalUnit):
5333
  """Migrate all instances from a node.
5334

5335
  """
5336
  HPATH = "node-migrate"
5337
  HTYPE = constants.HTYPE_NODE
5338
  _OP_REQP = ["node_name", "live"]
5339
  REQ_BGL = False
5340

    
5341
  def ExpandNames(self):
5342
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5343

    
5344
    self.needed_locks = {
5345
      locking.LEVEL_NODE: [self.op.node_name],
5346
      }
5347

    
5348
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5349

    
5350
    # Create tasklets for migrating instances for all instances on this node
5351
    names = []
5352
    tasklets = []
5353

    
5354
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5355
      logging.debug("Migrating instance %s", inst.name)
5356
      names.append(inst.name)
5357

    
5358
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5359

    
5360
    self.tasklets = tasklets
5361

    
5362
    # Declare instance locks
5363
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5364

    
5365
  def DeclareLocks(self, level):
5366
    if level == locking.LEVEL_NODE:
5367
      self._LockInstancesNodes()
5368

    
5369
  def BuildHooksEnv(self):
5370
    """Build hooks env.
5371

5372
    This runs on the master, the primary and all the secondaries.
5373

5374
    """
5375
    env = {
5376
      "NODE_NAME": self.op.node_name,
5377
      }
5378

    
5379
    nl = [self.cfg.GetMasterNode()]
5380

    
5381
    return (env, nl, nl)
5382

    
5383

    
5384
class TLMigrateInstance(Tasklet):
5385
  def __init__(self, lu, instance_name, live, cleanup):
5386
    """Initializes this class.
5387

5388
    """
5389
    Tasklet.__init__(self, lu)
5390

    
5391
    # Parameters
5392
    self.instance_name = instance_name
5393
    self.live = live
5394
    self.cleanup = cleanup
5395

    
5396
  def CheckPrereq(self):
5397
    """Check prerequisites.
5398

5399
    This checks that the instance is in the cluster.
5400

5401
    """
5402
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5403
    instance = self.cfg.GetInstanceInfo(instance_name)
5404
    assert instance is not None
5405

    
5406
    if instance.disk_template != constants.DT_DRBD8:
5407
      raise errors.OpPrereqError("Instance's disk layout is not"
5408
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5409

    
5410
    secondary_nodes = instance.secondary_nodes
5411
    if not secondary_nodes:
5412
      raise errors.ConfigurationError("No secondary node but using"
5413
                                      " drbd8 disk template")
5414

    
5415
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5416

    
5417
    target_node = secondary_nodes[0]
5418
    # check memory requirements on the secondary node
5419
    _CheckNodeFreeMemory(self, target_node, "migrating instance %s" %
5420
                         instance.name, i_be[constants.BE_MEMORY],
5421
                         instance.hypervisor)
5422

    
5423
    # check bridge existance
5424
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5425

    
5426
    if not self.cleanup:
5427
      _CheckNodeNotDrained(self, target_node)
5428
      result = self.rpc.call_instance_migratable(instance.primary_node,
5429
                                                 instance)
5430
      result.Raise("Can't migrate, please use failover",
5431
                   prereq=True, ecode=errors.ECODE_STATE)
5432

    
5433
    self.instance = instance
5434

    
5435
  def _WaitUntilSync(self):
5436
    """Poll with custom rpc for disk sync.
5437

5438
    This uses our own step-based rpc call.
5439

5440
    """
5441
    self.feedback_fn("* wait until resync is done")
5442
    all_done = False
5443
    while not all_done:
5444
      all_done = True
5445
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5446
                                            self.nodes_ip,
5447
                                            self.instance.disks)
5448
      min_percent = 100
5449
      for node, nres in result.items():
5450
        nres.Raise("Cannot resync disks on node %s" % node)
5451
        node_done, node_percent = nres.payload
5452
        all_done = all_done and node_done
5453
        if node_percent is not None:
5454
          min_percent = min(min_percent, node_percent)
5455
      if not all_done:
5456
        if min_percent < 100:
5457
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5458
        time.sleep(2)
5459

    
5460
  def _EnsureSecondary(self, node):
5461
    """Demote a node to secondary.
5462

5463
    """
5464
    self.feedback_fn("* switching node %s to secondary mode" % node)
5465

    
5466
    for dev in self.instance.disks:
5467
      self.cfg.SetDiskID(dev, node)
5468

    
5469
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5470
                                          self.instance.disks)
5471
    result.Raise("Cannot change disk to secondary on node %s" % node)
5472

    
5473
  def _GoStandalone(self):
5474
    """Disconnect from the network.
5475

5476
    """
5477
    self.feedback_fn("* changing into standalone mode")
5478
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5479
                                               self.instance.disks)
5480
    for node, nres in result.items():
5481
      nres.Raise("Cannot disconnect disks node %s" % node)
5482

    
5483
  def _GoReconnect(self, multimaster):
5484
    """Reconnect to the network.
5485

5486
    """
5487
    if multimaster:
5488
      msg = "dual-master"
5489
    else:
5490
      msg = "single-master"
5491
    self.feedback_fn("* changing disks into %s mode" % msg)
5492
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5493
                                           self.instance.disks,
5494
                                           self.instance.name, multimaster)
5495
    for node, nres in result.items():
5496
      nres.Raise("Cannot change disks config on node %s" % node)
5497

    
5498
  def _ExecCleanup(self):
5499
    """Try to cleanup after a failed migration.
5500

5501
    The cleanup is done by:
5502
      - check that the instance is running only on one node
5503
        (and update the config if needed)
5504
      - change disks on its secondary node to secondary
5505
      - wait until disks are fully synchronized
5506
      - disconnect from the network
5507
      - change disks into single-master mode
5508
      - wait again until disks are fully synchronized
5509

5510
    """
5511
    instance = self.instance
5512
    target_node = self.target_node
5513
    source_node = self.source_node
5514

    
5515
    # check running on only one node
5516
    self.feedback_fn("* checking where the instance actually runs"
5517
                     " (if this hangs, the hypervisor might be in"
5518
                     " a bad state)")
5519
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5520
    for node, result in ins_l.items():
5521
      result.Raise("Can't contact node %s" % node)
5522

    
5523
    runningon_source = instance.name in ins_l[source_node].payload
5524
    runningon_target = instance.name in ins_l[target_node].payload
5525

    
5526
    if runningon_source and runningon_target:
5527
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5528
                               " or the hypervisor is confused. You will have"
5529
                               " to ensure manually that it runs only on one"
5530
                               " and restart this operation.")
5531

    
5532
    if not (runningon_source or runningon_target):
5533
      raise errors.OpExecError("Instance does not seem to be running at all."
5534
                               " In this case, it's safer to repair by"
5535
                               " running 'gnt-instance stop' to ensure disk"
5536
                               " shutdown, and then restarting it.")
5537

    
5538
    if runningon_target:
5539
      # the migration has actually succeeded, we need to update the config
5540
      self.feedback_fn("* instance running on secondary node (%s),"
5541
                       " updating config" % target_node)
5542
      instance.primary_node = target_node
5543
      self.cfg.Update(instance, self.feedback_fn)
5544
      demoted_node = source_node
5545
    else:
5546
      self.feedback_fn("* instance confirmed to be running on its"
5547
                       " primary node (%s)" % source_node)
5548
      demoted_node = target_node
5549

    
5550
    self._EnsureSecondary(demoted_node)
5551
    try:
5552
      self._WaitUntilSync()
5553
    except errors.OpExecError:
5554
      # we ignore here errors, since if the device is standalone, it
5555
      # won't be able to sync
5556
      pass
5557
    self._GoStandalone()
5558
    self._GoReconnect(False)
5559
    self._WaitUntilSync()
5560

    
5561
    self.feedback_fn("* done")
5562

    
5563
  def _RevertDiskStatus(self):
5564
    """Try to revert the disk status after a failed migration.
5565

5566
    """
5567
    target_node = self.target_node
5568
    try:
5569
      self._EnsureSecondary(target_node)
5570
      self._GoStandalone()
5571
      self._GoReconnect(False)
5572
      self._WaitUntilSync()
5573
    except errors.OpExecError, err:
5574
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5575
                         " drives: error '%s'\n"
5576
                         "Please look and recover the instance status" %
5577
                         str(err))
5578

    
5579
  def _AbortMigration(self):
5580
    """Call the hypervisor code to abort a started migration.
5581

5582
    """
5583
    instance = self.instance
5584
    target_node = self.target_node
5585
    migration_info = self.migration_info
5586

    
5587
    abort_result = self.rpc.call_finalize_migration(target_node,
5588
                                                    instance,
5589
                                                    migration_info,
5590
                                                    False)
5591
    abort_msg = abort_result.fail_msg
5592
    if abort_msg:
5593
      logging.error("Aborting migration failed on target node %s: %s",
5594
                    target_node, abort_msg)
5595
      # Don't raise an exception here, as we stil have to try to revert the
5596
      # disk status, even if this step failed.
5597

    
5598
  def _ExecMigration(self):
5599
    """Migrate an instance.
5600

5601
    The migrate is done by:
5602
      - change the disks into dual-master mode
5603
      - wait until disks are fully synchronized again
5604
      - migrate the instance
5605
      - change disks on the new secondary node (the old primary) to secondary
5606
      - wait until disks are fully synchronized
5607
      - change disks into single-master mode
5608

5609
    """
5610
    instance = self.instance
5611
    target_node = self.target_node
5612
    source_node = self.source_node
5613

    
5614
    self.feedback_fn("* checking disk consistency between source and target")
5615
    for dev in instance.disks:
5616
      if not _CheckDiskConsistency(self, dev, target_node, False):
5617
        raise errors.OpExecError("Disk %s is degraded or not fully"
5618
                                 " synchronized on target node,"
5619
                                 " aborting migrate." % dev.iv_name)
5620

    
5621
    # First get the migration information from the remote node
5622
    result = self.rpc.call_migration_info(source_node, instance)
5623
    msg = result.fail_msg
5624
    if msg:
5625
      log_err = ("Failed fetching source migration information from %s: %s" %
5626
                 (source_node, msg))
5627
      logging.error(log_err)
5628
      raise errors.OpExecError(log_err)
5629

    
5630
    self.migration_info = migration_info = result.payload
5631

    
5632
    # Then switch the disks to master/master mode
5633
    self._EnsureSecondary(target_node)
5634
    self._GoStandalone()
5635
    self._GoReconnect(True)
5636
    self._WaitUntilSync()
5637

    
5638
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5639
    result = self.rpc.call_accept_instance(target_node,
5640
                                           instance,
5641
                                           migration_info,
5642
                                           self.nodes_ip[target_node])
5643

    
5644
    msg = result.fail_msg
5645
    if msg:
5646
      logging.error("Instance pre-migration failed, trying to revert"
5647
                    " disk status: %s", msg)
5648
      self.feedback_fn("Pre-migration failed, aborting")
5649
      self._AbortMigration()
5650
      self._RevertDiskStatus()
5651
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5652
                               (instance.name, msg))
5653

    
5654
    self.feedback_fn("* migrating instance to %s" % target_node)
5655
    time.sleep(10)
5656
    result = self.rpc.call_instance_migrate(source_node, instance,
5657
                                            self.nodes_ip[target_node],
5658
                                            self.live)
5659
    msg = result.fail_msg
5660
    if msg:
5661
      logging.error("Instance migration failed, trying to revert"
5662
                    " disk status: %s", msg)
5663
      self.feedback_fn("Migration failed, aborting")
5664
      self._AbortMigration()
5665
      self._RevertDiskStatus()
5666
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5667
                               (instance.name, msg))
5668
    time.sleep(10)
5669

    
5670
    instance.primary_node = target_node
5671
    # distribute new instance config to the other nodes
5672
    self.cfg.Update(instance, self.feedback_fn)
5673

    
5674
    result = self.rpc.call_finalize_migration(target_node,
5675
                                              instance,
5676
                                              migration_info,
5677
                                              True)
5678
    msg = result.fail_msg
5679
    if msg:
5680
      logging.error("Instance migration succeeded, but finalization failed:"
5681
                    " %s", msg)
5682
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5683
                               msg)
5684

    
5685
    self._EnsureSecondary(source_node)
5686
    self._WaitUntilSync()
5687
    self._GoStandalone()
5688
    self._GoReconnect(False)
5689
    self._WaitUntilSync()
5690

    
5691
    self.feedback_fn("* done")
5692

    
5693
  def Exec(self, feedback_fn):
5694
    """Perform the migration.
5695

5696
    """
5697
    feedback_fn("Migrating instance %s" % self.instance.name)
5698

    
5699
    self.feedback_fn = feedback_fn
5700

    
5701
    self.source_node = self.instance.primary_node
5702
    self.target_node = self.instance.secondary_nodes[0]
5703
    self.all_nodes = [self.source_node, self.target_node]
5704
    self.nodes_ip = {
5705
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5706
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5707
      }
5708

    
5709
    if self.cleanup:
5710
      return self._ExecCleanup()
5711
    else:
5712
      return self._ExecMigration()
5713

    
5714

    
5715
def _CreateBlockDev(lu, node, instance, device, force_create,
5716
                    info, force_open):
5717
  """Create a tree of block devices on a given node.
5718

5719
  If this device type has to be created on secondaries, create it and
5720
  all its children.
5721

5722
  If not, just recurse to children keeping the same 'force' value.
5723

5724
  @param lu: the lu on whose behalf we execute
5725
  @param node: the node on which to create the device
5726
  @type instance: L{objects.Instance}
5727
  @param instance: the instance which owns the device
5728
  @type device: L{objects.Disk}
5729
  @param device: the device to create
5730
  @type force_create: boolean
5731
  @param force_create: whether to force creation of this device; this
5732
      will be change to True whenever we find a device which has
5733
      CreateOnSecondary() attribute
5734
  @param info: the extra 'metadata' we should attach to the device
5735
      (this will be represented as a LVM tag)
5736
  @type force_open: boolean
5737
  @param force_open: this parameter will be passes to the
5738
      L{backend.BlockdevCreate} function where it specifies
5739
      whether we run on primary or not, and it affects both
5740
      the child assembly and the device own Open() execution
5741

5742
  """
5743
  if device.CreateOnSecondary():
5744
    force_create = True
5745

    
5746
  if device.children:
5747
    for child in device.children:
5748
      _CreateBlockDev(lu, node, instance, child, force_create,
5749
                      info, force_open)
5750

    
5751
  if not force_create:
5752
    return
5753

    
5754
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
5755

    
5756

    
5757
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
5758
  """Create a single block device on a given node.
5759

5760
  This will not recurse over children of the device, so they must be
5761
  created in advance.
5762

5763
  @param lu: the lu on whose behalf we execute
5764
  @param node: the node on which to create the device
5765
  @type instance: L{objects.Instance}
5766
  @param instance: the instance which owns the device
5767
  @type device: L{objects.Disk}
5768
  @param device: the device to create
5769
  @param info: the extra 'metadata' we should attach to the device
5770
      (this will be represented as a LVM tag)
5771
  @type force_open: boolean
5772
  @param force_open: this parameter will be passes to the
5773
      L{backend.BlockdevCreate} function where it specifies
5774
      whether we run on primary or not, and it affects both
5775
      the child assembly and the device own Open() execution
5776

5777
  """
5778
  lu.cfg.SetDiskID(device, node)
5779
  result = lu.rpc.call_blockdev_create(node, device, device.size,
5780
                                       instance.name, force_open, info)
5781
  result.Raise("Can't create block device %s on"
5782
               " node %s for instance %s" % (device, node, instance.name))
5783
  if device.physical_id is None:
5784
    device.physical_id = result.payload
5785

    
5786

    
5787
def _GenerateUniqueNames(lu, exts):
5788
  """Generate a suitable LV name.
5789

5790
  This will generate a logical volume name for the given instance.
5791

5792
  """
5793
  results = []
5794
  for val in exts:
5795
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
5796
    results.append("%s%s" % (new_id, val))
5797
  return results
5798

    
5799

    
5800
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
5801
                         p_minor, s_minor):
5802
  """Generate a drbd8 device complete with its children.
5803

5804
  """
5805
  port = lu.cfg.AllocatePort()
5806
  vgname = lu.cfg.GetVGName()
5807
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
5808
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
5809
                          logical_id=(vgname, names[0]))
5810
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
5811
                          logical_id=(vgname, names[1]))
5812
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
5813
                          logical_id=(primary, secondary, port,
5814
                                      p_minor, s_minor,
5815
                                      shared_secret),
5816
                          children=[dev_data, dev_meta],
5817
                          iv_name=iv_name)
5818
  return drbd_dev
5819

    
5820

    
5821
def _GenerateDiskTemplate(lu, template_name,
5822
                          instance_name, primary_node,
5823
                          secondary_nodes, disk_info,
5824
                          file_storage_dir, file_driver,
5825
                          base_index):
5826
  """Generate the entire disk layout for a given template type.
5827

5828
  """
5829
  #TODO: compute space requirements
5830

    
5831
  vgname = lu.cfg.GetVGName()
5832
  disk_count = len(disk_info)
5833
  disks = []
5834
  if template_name == constants.DT_DISKLESS:
5835
    pass
5836
  elif template_name == constants.DT_PLAIN:
5837
    if len(secondary_nodes) != 0:
5838
      raise errors.ProgrammerError("Wrong template configuration")
5839

    
5840
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5841
                                      for i in range(disk_count)])
5842
    for idx, disk in enumerate(disk_info):
5843
      disk_index = idx + base_index
5844
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
5845
                              logical_id=(vgname, names[idx]),
5846
                              iv_name="disk/%d" % disk_index,
5847
                              mode=disk["mode"])
5848
      disks.append(disk_dev)
5849
  elif template_name == constants.DT_DRBD8:
5850
    if len(secondary_nodes) != 1:
5851
      raise errors.ProgrammerError("Wrong template configuration")
5852
    remote_node = secondary_nodes[0]
5853
    minors = lu.cfg.AllocateDRBDMinor(
5854
      [primary_node, remote_node] * len(disk_info), instance_name)
5855

    
5856
    names = []
5857
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
5858
                                               for i in range(disk_count)]):
5859
      names.append(lv_prefix + "_data")
5860
      names.append(lv_prefix + "_meta")
5861
    for idx, disk in enumerate(disk_info):
5862
      disk_index = idx + base_index
5863
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
5864
                                      disk["size"], names[idx*2:idx*2+2],
5865
                                      "disk/%d" % disk_index,
5866
                                      minors[idx*2], minors[idx*2+1])
5867
      disk_dev.mode = disk["mode"]
5868
      disks.append(disk_dev)
5869
  elif template_name == constants.DT_FILE:
5870
    if len(secondary_nodes) != 0:
5871
      raise errors.ProgrammerError("Wrong template configuration")
5872

    
5873
    _RequireFileStorage()
5874

    
5875
    for idx, disk in enumerate(disk_info):
5876
      disk_index = idx + base_index
5877
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
5878
                              iv_name="disk/%d" % disk_index,
5879
                              logical_id=(file_driver,
5880
                                          "%s/disk%d" % (file_storage_dir,
5881
                                                         disk_index)),
5882
                              mode=disk["mode"])
5883
      disks.append(disk_dev)
5884
  else:
5885
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
5886
  return disks
5887

    
5888

    
5889
def _GetInstanceInfoText(instance):
5890
  """Compute that text that should be added to the disk's metadata.
5891

5892
  """
5893
  return "originstname+%s" % instance.name
5894

    
5895

    
5896
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
5897
  """Create all disks for an instance.
5898

5899
  This abstracts away some work from AddInstance.
5900

5901
  @type lu: L{LogicalUnit}
5902
  @param lu: the logical unit on whose behalf we execute
5903
  @type instance: L{objects.Instance}
5904
  @param instance: the instance whose disks we should create
5905
  @type to_skip: list
5906
  @param to_skip: list of indices to skip
5907
  @type target_node: string
5908
  @param target_node: if passed, overrides the target node for creation
5909
  @rtype: boolean
5910
  @return: the success of the creation
5911

5912
  """
5913
  info = _GetInstanceInfoText(instance)
5914
  if target_node is None:
5915
    pnode = instance.primary_node
5916
    all_nodes = instance.all_nodes
5917
  else:
5918
    pnode = target_node
5919
    all_nodes = [pnode]
5920

    
5921
  if instance.disk_template == constants.DT_FILE:
5922
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5923
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
5924

    
5925
    result.Raise("Failed to create directory '%s' on"
5926
                 " node %s" % (file_storage_dir, pnode))
5927

    
5928
  # Note: this needs to be kept in sync with adding of disks in
5929
  # LUSetInstanceParams
5930
  for idx, device in enumerate(instance.disks):
5931
    if to_skip and idx in to_skip:
5932
      continue
5933
    logging.info("Creating volume %s for instance %s",
5934
                 device.iv_name, instance.name)
5935
    #HARDCODE
5936
    for node in all_nodes:
5937
      f_create = node == pnode
5938
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
5939

    
5940

    
5941
def _RemoveDisks(lu, instance, target_node=None):
5942
  """Remove all disks for an instance.
5943

5944
  This abstracts away some work from `AddInstance()` and
5945
  `RemoveInstance()`. Note that in case some of the devices couldn't
5946
  be removed, the removal will continue with the other ones (compare
5947
  with `_CreateDisks()`).
5948

5949
  @type lu: L{LogicalUnit}
5950
  @param lu: the logical unit on whose behalf we execute
5951
  @type instance: L{objects.Instance}
5952
  @param instance: the instance whose disks we should remove
5953
  @type target_node: string
5954
  @param target_node: used to override the node on which to remove the disks
5955
  @rtype: boolean
5956
  @return: the success of the removal
5957

5958
  """
5959
  logging.info("Removing block devices for instance %s", instance.name)
5960

    
5961
  all_result = True
5962
  for device in instance.disks:
5963
    if target_node:
5964
      edata = [(target_node, device)]
5965
    else:
5966
      edata = device.ComputeNodeTree(instance.primary_node)
5967
    for node, disk in edata:
5968
      lu.cfg.SetDiskID(disk, node)
5969
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
5970
      if msg:
5971
        lu.LogWarning("Could not remove block device %s on node %s,"
5972
                      " continuing anyway: %s", device.iv_name, node, msg)
5973
        all_result = False
5974

    
5975
  if instance.disk_template == constants.DT_FILE:
5976
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
5977
    if target_node:
5978
      tgt = target_node
5979
    else:
5980
      tgt = instance.primary_node
5981
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
5982
    if result.fail_msg:
5983
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
5984
                    file_storage_dir, instance.primary_node, result.fail_msg)
5985
      all_result = False
5986

    
5987
  return all_result
5988

    
5989

    
5990
def _ComputeDiskSize(disk_template, disks):
5991
  """Compute disk size requirements in the volume group
5992

5993
  """
5994
  # Required free disk space as a function of disk and swap space
5995
  req_size_dict = {
5996
    constants.DT_DISKLESS: None,
5997
    constants.DT_PLAIN: sum(d["size"] for d in disks),
5998
    # 128 MB are added for drbd metadata for each disk
5999
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6000
    constants.DT_FILE: None,
6001
  }
6002

    
6003
  if disk_template not in req_size_dict:
6004
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6005
                                 " is unknown" %  disk_template)
6006

    
6007
  return req_size_dict[disk_template]
6008

    
6009

    
6010
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6011
  """Hypervisor parameter validation.
6012

6013
  This function abstract the hypervisor parameter validation to be
6014
  used in both instance create and instance modify.
6015

6016
  @type lu: L{LogicalUnit}
6017
  @param lu: the logical unit for which we check
6018
  @type nodenames: list
6019
  @param nodenames: the list of nodes on which we should check
6020
  @type hvname: string
6021
  @param hvname: the name of the hypervisor we should use
6022
  @type hvparams: dict
6023
  @param hvparams: the parameters which we need to check
6024
  @raise errors.OpPrereqError: if the parameters are not valid
6025

6026
  """
6027
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6028
                                                  hvname,
6029
                                                  hvparams)
6030
  for node in nodenames:
6031
    info = hvinfo[node]
6032
    if info.offline:
6033
      continue
6034
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6035

    
6036

    
6037
class LUCreateInstance(LogicalUnit):
6038
  """Create an instance.
6039

6040
  """
6041
  HPATH = "instance-add"
6042
  HTYPE = constants.HTYPE_INSTANCE
6043
  _OP_REQP = ["instance_name", "disks",
6044
              "mode", "start",
6045
              "wait_for_sync", "ip_check", "nics",
6046
              "hvparams", "beparams"]
6047
  REQ_BGL = False
6048

    
6049
  def CheckArguments(self):
6050
    """Check arguments.
6051

6052
    """
6053
    # set optional parameters to none if they don't exist
6054
    for attr in ["pnode", "snode", "iallocator", "hypervisor",
6055
                 "disk_template", "identify_defaults"]:
6056
      if not hasattr(self.op, attr):
6057
        setattr(self.op, attr, None)
6058

    
6059
    # do not require name_check to ease forward/backward compatibility
6060
    # for tools
6061
    if not hasattr(self.op, "name_check"):
6062
      self.op.name_check = True
6063
    if not hasattr(self.op, "no_install"):
6064
      self.op.no_install = False
6065
    if self.op.no_install and self.op.start:
6066
      self.LogInfo("No-installation mode selected, disabling startup")
6067
      self.op.start = False
6068
    # validate/normalize the instance name
6069
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
6070
    if self.op.ip_check and not self.op.name_check:
6071
      # TODO: make the ip check more flexible and not depend on the name check
6072
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6073
                                 errors.ECODE_INVAL)
6074
    # check disk information: either all adopt, or no adopt
6075
    has_adopt = has_no_adopt = False
6076
    for disk in self.op.disks:
6077
      if "adopt" in disk:
6078
        has_adopt = True
6079
      else:
6080
        has_no_adopt = True
6081
    if has_adopt and has_no_adopt:
6082
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6083
                                 errors.ECODE_INVAL)
6084
    if has_adopt:
6085
      if self.op.disk_template != constants.DT_PLAIN:
6086
        raise errors.OpPrereqError("Disk adoption is only supported for the"
6087
                                   " 'plain' disk template",
6088
                                   errors.ECODE_INVAL)
6089
      if self.op.iallocator is not None:
6090
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6091
                                   " iallocator script", errors.ECODE_INVAL)
6092
      if self.op.mode == constants.INSTANCE_IMPORT:
6093
        raise errors.OpPrereqError("Disk adoption not allowed for"
6094
                                   " instance import", errors.ECODE_INVAL)
6095

    
6096
    self.adopt_disks = has_adopt
6097

    
6098
    # verify creation mode
6099
    if self.op.mode not in (constants.INSTANCE_CREATE,
6100
                            constants.INSTANCE_IMPORT):
6101
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
6102
                                 self.op.mode, errors.ECODE_INVAL)
6103

    
6104
    # instance name verification
6105
    if self.op.name_check:
6106
      self.hostname1 = utils.GetHostInfo(self.op.instance_name)
6107
      self.op.instance_name = self.hostname1.name
6108
      # used in CheckPrereq for ip ping check
6109
      self.check_ip = self.hostname1.ip
6110
    else:
6111
      self.check_ip = None
6112

    
6113
    # file storage checks
6114
    if (self.op.file_driver and
6115
        not self.op.file_driver in constants.FILE_DRIVER):
6116
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6117
                                 self.op.file_driver, errors.ECODE_INVAL)
6118

    
6119
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6120
      raise errors.OpPrereqError("File storage directory path not absolute",
6121
                                 errors.ECODE_INVAL)
6122

    
6123
    ### Node/iallocator related checks
6124
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
6125
      raise errors.OpPrereqError("One and only one of iallocator and primary"
6126
                                 " node must be given",
6127
                                 errors.ECODE_INVAL)
6128

    
6129
    if self.op.mode == constants.INSTANCE_IMPORT:
6130
      # On import force_variant must be True, because if we forced it at
6131
      # initial install, our only chance when importing it back is that it
6132
      # works again!
6133
      self.op.force_variant = True
6134

    
6135
      if self.op.no_install:
6136
        self.LogInfo("No-installation mode has no effect during import")
6137

    
6138
    else: # INSTANCE_CREATE
6139
      if getattr(self.op, "os_type", None) is None:
6140
        raise errors.OpPrereqError("No guest OS specified",
6141
                                   errors.ECODE_INVAL)
6142
      self.op.force_variant = getattr(self.op, "force_variant", False)
6143
      if self.op.disk_template is None:
6144
        raise errors.OpPrereqError("No disk template specified",
6145
                                   errors.ECODE_INVAL)
6146

    
6147
  def ExpandNames(self):
6148
    """ExpandNames for CreateInstance.
6149

6150
    Figure out the right locks for instance creation.
6151

6152
    """
6153
    self.needed_locks = {}
6154

    
6155
    instance_name = self.op.instance_name
6156
    # this is just a preventive check, but someone might still add this
6157
    # instance in the meantime, and creation will fail at lock-add time
6158
    if instance_name in self.cfg.GetInstanceList():
6159
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6160
                                 instance_name, errors.ECODE_EXISTS)
6161

    
6162
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6163

    
6164
    if self.op.iallocator:
6165
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6166
    else:
6167
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6168
      nodelist = [self.op.pnode]
6169
      if self.op.snode is not None:
6170
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6171
        nodelist.append(self.op.snode)
6172
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6173

    
6174
    # in case of import lock the source node too
6175
    if self.op.mode == constants.INSTANCE_IMPORT:
6176
      src_node = getattr(self.op, "src_node", None)
6177
      src_path = getattr(self.op, "src_path", None)
6178

    
6179
      if src_path is None:
6180
        self.op.src_path = src_path = self.op.instance_name
6181

    
6182
      if src_node is None:
6183
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6184
        self.op.src_node = None
6185
        if os.path.isabs(src_path):
6186
          raise errors.OpPrereqError("Importing an instance from an absolute"
6187
                                     " path requires a source node option.",
6188
                                     errors.ECODE_INVAL)
6189
      else:
6190
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6191
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6192
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6193
        if not os.path.isabs(src_path):
6194
          self.op.src_path = src_path = \
6195
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6196

    
6197
  def _RunAllocator(self):
6198
    """Run the allocator based on input opcode.
6199

6200
    """
6201
    nics = [n.ToDict() for n in self.nics]
6202
    ial = IAllocator(self.cfg, self.rpc,
6203
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6204
                     name=self.op.instance_name,
6205
                     disk_template=self.op.disk_template,
6206
                     tags=[],
6207
                     os=self.op.os_type,
6208
                     vcpus=self.be_full[constants.BE_VCPUS],
6209
                     mem_size=self.be_full[constants.BE_MEMORY],
6210
                     disks=self.disks,
6211
                     nics=nics,
6212
                     hypervisor=self.op.hypervisor,
6213
                     )
6214

    
6215
    ial.Run(self.op.iallocator)
6216

    
6217
    if not ial.success:
6218
      raise errors.OpPrereqError("Can't compute nodes using"
6219
                                 " iallocator '%s': %s" %
6220
                                 (self.op.iallocator, ial.info),
6221
                                 errors.ECODE_NORES)
6222
    if len(ial.result) != ial.required_nodes:
6223
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6224
                                 " of nodes (%s), required %s" %
6225
                                 (self.op.iallocator, len(ial.result),
6226
                                  ial.required_nodes), errors.ECODE_FAULT)
6227
    self.op.pnode = ial.result[0]
6228
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6229
                 self.op.instance_name, self.op.iallocator,
6230
                 utils.CommaJoin(ial.result))
6231
    if ial.required_nodes == 2:
6232
      self.op.snode = ial.result[1]
6233

    
6234
  def BuildHooksEnv(self):
6235
    """Build hooks env.
6236

6237
    This runs on master, primary and secondary nodes of the instance.
6238

6239
    """
6240
    env = {
6241
      "ADD_MODE": self.op.mode,
6242
      }
6243
    if self.op.mode == constants.INSTANCE_IMPORT:
6244
      env["SRC_NODE"] = self.op.src_node
6245
      env["SRC_PATH"] = self.op.src_path
6246
      env["SRC_IMAGES"] = self.src_images
6247

    
6248
    env.update(_BuildInstanceHookEnv(
6249
      name=self.op.instance_name,
6250
      primary_node=self.op.pnode,
6251
      secondary_nodes=self.secondaries,
6252
      status=self.op.start,
6253
      os_type=self.op.os_type,
6254
      memory=self.be_full[constants.BE_MEMORY],
6255
      vcpus=self.be_full[constants.BE_VCPUS],
6256
      nics=_NICListToTuple(self, self.nics),
6257
      disk_template=self.op.disk_template,
6258
      disks=[(d["size"], d["mode"]) for d in self.disks],
6259
      bep=self.be_full,
6260
      hvp=self.hv_full,
6261
      hypervisor_name=self.op.hypervisor,
6262
    ))
6263

    
6264
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6265
          self.secondaries)
6266
    return env, nl, nl
6267

    
6268
  def _ReadExportInfo(self):
6269
    """Reads the export information from disk.
6270

6271
    It will override the opcode source node and path with the actual
6272
    information, if these two were not specified before.
6273

6274
    @return: the export information
6275

6276
    """
6277
    assert self.op.mode == constants.INSTANCE_IMPORT
6278

    
6279
    src_node = self.op.src_node
6280
    src_path = self.op.src_path
6281

    
6282
    if src_node is None:
6283
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6284
      exp_list = self.rpc.call_export_list(locked_nodes)
6285
      found = False
6286
      for node in exp_list:
6287
        if exp_list[node].fail_msg:
6288
          continue
6289
        if src_path in exp_list[node].payload:
6290
          found = True
6291
          self.op.src_node = src_node = node
6292
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6293
                                                       src_path)
6294
          break
6295
      if not found:
6296
        raise errors.OpPrereqError("No export found for relative path %s" %
6297
                                    src_path, errors.ECODE_INVAL)
6298

    
6299
    _CheckNodeOnline(self, src_node)
6300
    result = self.rpc.call_export_info(src_node, src_path)
6301
    result.Raise("No export or invalid export found in dir %s" % src_path)
6302

    
6303
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6304
    if not export_info.has_section(constants.INISECT_EXP):
6305
      raise errors.ProgrammerError("Corrupted export config",
6306
                                   errors.ECODE_ENVIRON)
6307

    
6308
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6309
    if (int(ei_version) != constants.EXPORT_VERSION):
6310
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6311
                                 (ei_version, constants.EXPORT_VERSION),
6312
                                 errors.ECODE_ENVIRON)
6313
    return export_info
6314

    
6315
  def _ReadExportParams(self, einfo):
6316
    """Use export parameters as defaults.
6317

6318
    In case the opcode doesn't specify (as in override) some instance
6319
    parameters, then try to use them from the export information, if
6320
    that declares them.
6321

6322
    """
6323
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6324

    
6325
    if self.op.disk_template is None:
6326
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6327
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6328
                                          "disk_template")
6329
      else:
6330
        raise errors.OpPrereqError("No disk template specified and the export"
6331
                                   " is missing the disk_template information",
6332
                                   errors.ECODE_INVAL)
6333

    
6334
    if not self.op.disks:
6335
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6336
        disks = []
6337
        # TODO: import the disk iv_name too
6338
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6339
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6340
          disks.append({"size": disk_sz})
6341
        self.op.disks = disks
6342
      else:
6343
        raise errors.OpPrereqError("No disk info specified and the export"
6344
                                   " is missing the disk information",
6345
                                   errors.ECODE_INVAL)
6346

    
6347
    if (not self.op.nics and
6348
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6349
      nics = []
6350
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6351
        ndict = {}
6352
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6353
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6354
          ndict[name] = v
6355
        nics.append(ndict)
6356
      self.op.nics = nics
6357

    
6358
    if (self.op.hypervisor is None and
6359
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6360
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6361
    if einfo.has_section(constants.INISECT_HYP):
6362
      # use the export parameters but do not override the ones
6363
      # specified by the user
6364
      for name, value in einfo.items(constants.INISECT_HYP):
6365
        if name not in self.op.hvparams:
6366
          self.op.hvparams[name] = value
6367

    
6368
    if einfo.has_section(constants.INISECT_BEP):
6369
      # use the parameters, without overriding
6370
      for name, value in einfo.items(constants.INISECT_BEP):
6371
        if name not in self.op.beparams:
6372
          self.op.beparams[name] = value
6373
    else:
6374
      # try to read the parameters old style, from the main section
6375
      for name in constants.BES_PARAMETERS:
6376
        if (name not in self.op.beparams and
6377
            einfo.has_option(constants.INISECT_INS, name)):
6378
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6379

    
6380
  def _RevertToDefaults(self, cluster):
6381
    """Revert the instance parameters to the default values.
6382

6383
    """
6384
    # hvparams
6385
    hv_defs = cluster.GetHVDefaults(self.op.hypervisor, self.op.os_type)
6386
    for name in self.op.hvparams.keys():
6387
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6388
        del self.op.hvparams[name]
6389
    # beparams
6390
    be_defs = cluster.beparams.get(constants.PP_DEFAULT, {})
6391
    for name in self.op.beparams.keys():
6392
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6393
        del self.op.beparams[name]
6394
    # nic params
6395
    nic_defs = cluster.nicparams.get(constants.PP_DEFAULT, {})
6396
    for nic in self.op.nics:
6397
      for name in constants.NICS_PARAMETERS:
6398
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6399
          del nic[name]
6400

    
6401
  def CheckPrereq(self):
6402
    """Check prerequisites.
6403

6404
    """
6405
    if self.op.mode == constants.INSTANCE_IMPORT:
6406
      export_info = self._ReadExportInfo()
6407
      self._ReadExportParams(export_info)
6408

    
6409
    _CheckDiskTemplate(self.op.disk_template)
6410

    
6411
    if (not self.cfg.GetVGName() and
6412
        self.op.disk_template not in constants.DTS_NOT_LVM):
6413
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6414
                                 " instances", errors.ECODE_STATE)
6415

    
6416
    if self.op.hypervisor is None:
6417
      self.op.hypervisor = self.cfg.GetHypervisorType()
6418

    
6419
    cluster = self.cfg.GetClusterInfo()
6420
    enabled_hvs = cluster.enabled_hypervisors
6421
    if self.op.hypervisor not in enabled_hvs:
6422
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6423
                                 " cluster (%s)" % (self.op.hypervisor,
6424
                                  ",".join(enabled_hvs)),
6425
                                 errors.ECODE_STATE)
6426

    
6427
    # check hypervisor parameter syntax (locally)
6428
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6429
    filled_hvp = objects.FillDict(cluster.GetHVDefaults(self.op.hypervisor,
6430
                                                        self.op.os_type),
6431
                                  self.op.hvparams)
6432
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6433
    hv_type.CheckParameterSyntax(filled_hvp)
6434
    self.hv_full = filled_hvp
6435
    # check that we don't specify global parameters on an instance
6436
    _CheckGlobalHvParams(self.op.hvparams)
6437

    
6438
    # fill and remember the beparams dict
6439
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6440
    self.be_full = objects.FillDict(cluster.beparams[constants.PP_DEFAULT],
6441
                                    self.op.beparams)
6442

    
6443
    # now that hvp/bep are in final format, let's reset to defaults,
6444
    # if told to do so
6445
    if self.op.identify_defaults:
6446
      self._RevertToDefaults(cluster)
6447

    
6448
    # NIC buildup
6449
    self.nics = []
6450
    for idx, nic in enumerate(self.op.nics):
6451
      nic_mode_req = nic.get("mode", None)
6452
      nic_mode = nic_mode_req
6453
      if nic_mode is None:
6454
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6455

    
6456
      # in routed mode, for the first nic, the default ip is 'auto'
6457
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6458
        default_ip_mode = constants.VALUE_AUTO
6459
      else:
6460
        default_ip_mode = constants.VALUE_NONE
6461

    
6462
      # ip validity checks
6463
      ip = nic.get("ip", default_ip_mode)
6464
      if ip is None or ip.lower() == constants.VALUE_NONE:
6465
        nic_ip = None
6466
      elif ip.lower() == constants.VALUE_AUTO:
6467
        if not self.op.name_check:
6468
          raise errors.OpPrereqError("IP address set to auto but name checks"
6469
                                     " have been skipped. Aborting.",
6470
                                     errors.ECODE_INVAL)
6471
        nic_ip = self.hostname1.ip
6472
      else:
6473
        if not utils.IsValidIP(ip):
6474
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6475
                                     " like a valid IP" % ip,
6476
                                     errors.ECODE_INVAL)
6477
        nic_ip = ip
6478

    
6479
      # TODO: check the ip address for uniqueness
6480
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6481
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6482
                                   errors.ECODE_INVAL)
6483

    
6484
      # MAC address verification
6485
      mac = nic.get("mac", constants.VALUE_AUTO)
6486
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6487
        mac = utils.NormalizeAndValidateMac(mac)
6488

    
6489
        try:
6490
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6491
        except errors.ReservationError:
6492
          raise errors.OpPrereqError("MAC address %s already in use"
6493
                                     " in cluster" % mac,
6494
                                     errors.ECODE_NOTUNIQUE)
6495

    
6496
      # bridge verification
6497
      bridge = nic.get("bridge", None)
6498
      link = nic.get("link", None)
6499
      if bridge and link:
6500
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6501
                                   " at the same time", errors.ECODE_INVAL)
6502
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6503
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6504
                                   errors.ECODE_INVAL)
6505
      elif bridge:
6506
        link = bridge
6507

    
6508
      nicparams = {}
6509
      if nic_mode_req:
6510
        nicparams[constants.NIC_MODE] = nic_mode_req
6511
      if link:
6512
        nicparams[constants.NIC_LINK] = link
6513

    
6514
      check_params = objects.FillDict(cluster.nicparams[constants.PP_DEFAULT],
6515
                                      nicparams)
6516
      objects.NIC.CheckParameterSyntax(check_params)
6517
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6518

    
6519
    # disk checks/pre-build
6520
    self.disks = []
6521
    for disk in self.op.disks:
6522
      mode = disk.get("mode", constants.DISK_RDWR)
6523
      if mode not in constants.DISK_ACCESS_SET:
6524
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6525
                                   mode, errors.ECODE_INVAL)
6526
      size = disk.get("size", None)
6527
      if size is None:
6528
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6529
      try:
6530
        size = int(size)
6531
      except (TypeError, ValueError):
6532
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6533
                                   errors.ECODE_INVAL)
6534
      new_disk = {"size": size, "mode": mode}
6535
      if "adopt" in disk:
6536
        new_disk["adopt"] = disk["adopt"]
6537
      self.disks.append(new_disk)
6538

    
6539
    if self.op.mode == constants.INSTANCE_IMPORT:
6540

    
6541
      # Check that the new instance doesn't have less disks than the export
6542
      instance_disks = len(self.disks)
6543
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6544
      if instance_disks < export_disks:
6545
        raise errors.OpPrereqError("Not enough disks to import."
6546
                                   " (instance: %d, export: %d)" %
6547
                                   (instance_disks, export_disks),
6548
                                   errors.ECODE_INVAL)
6549

    
6550
      disk_images = []
6551
      for idx in range(export_disks):
6552
        option = 'disk%d_dump' % idx
6553
        if export_info.has_option(constants.INISECT_INS, option):
6554
          # FIXME: are the old os-es, disk sizes, etc. useful?
6555
          export_name = export_info.get(constants.INISECT_INS, option)
6556
          image = utils.PathJoin(self.op.src_path, export_name)
6557
          disk_images.append(image)
6558
        else:
6559
          disk_images.append(False)
6560

    
6561
      self.src_images = disk_images
6562

    
6563
      old_name = export_info.get(constants.INISECT_INS, 'name')
6564
      try:
6565
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
6566
      except (TypeError, ValueError), err:
6567
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
6568
                                   " an integer: %s" % str(err),
6569
                                   errors.ECODE_STATE)
6570
      if self.op.instance_name == old_name:
6571
        for idx, nic in enumerate(self.nics):
6572
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6573
            nic_mac_ini = 'nic%d_mac' % idx
6574
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6575

    
6576
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6577

    
6578
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6579
    if self.op.ip_check:
6580
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6581
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6582
                                   (self.check_ip, self.op.instance_name),
6583
                                   errors.ECODE_NOTUNIQUE)
6584

    
6585
    #### mac address generation
6586
    # By generating here the mac address both the allocator and the hooks get
6587
    # the real final mac address rather than the 'auto' or 'generate' value.
6588
    # There is a race condition between the generation and the instance object
6589
    # creation, which means that we know the mac is valid now, but we're not
6590
    # sure it will be when we actually add the instance. If things go bad
6591
    # adding the instance will abort because of a duplicate mac, and the
6592
    # creation job will fail.
6593
    for nic in self.nics:
6594
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6595
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6596

    
6597
    #### allocator run
6598

    
6599
    if self.op.iallocator is not None:
6600
      self._RunAllocator()
6601

    
6602
    #### node related checks
6603

    
6604
    # check primary node
6605
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6606
    assert self.pnode is not None, \
6607
      "Cannot retrieve locked node %s" % self.op.pnode
6608
    if pnode.offline:
6609
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6610
                                 pnode.name, errors.ECODE_STATE)
6611
    if pnode.drained:
6612
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6613
                                 pnode.name, errors.ECODE_STATE)
6614

    
6615
    self.secondaries = []
6616

    
6617
    # mirror node verification
6618
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6619
      if self.op.snode is None:
6620
        raise errors.OpPrereqError("The networked disk templates need"
6621
                                   " a mirror node", errors.ECODE_INVAL)
6622
      if self.op.snode == pnode.name:
6623
        raise errors.OpPrereqError("The secondary node cannot be the"
6624
                                   " primary node.", errors.ECODE_INVAL)
6625
      _CheckNodeOnline(self, self.op.snode)
6626
      _CheckNodeNotDrained(self, self.op.snode)
6627
      self.secondaries.append(self.op.snode)
6628

    
6629
    nodenames = [pnode.name] + self.secondaries
6630

    
6631
    req_size = _ComputeDiskSize(self.op.disk_template,
6632
                                self.disks)
6633

    
6634
    # Check lv size requirements, if not adopting
6635
    if req_size is not None and not self.adopt_disks:
6636
      _CheckNodesFreeDisk(self, nodenames, req_size)
6637

    
6638
    if self.adopt_disks: # instead, we must check the adoption data
6639
      all_lvs = set([i["adopt"] for i in self.disks])
6640
      if len(all_lvs) != len(self.disks):
6641
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
6642
                                   errors.ECODE_INVAL)
6643
      for lv_name in all_lvs:
6644
        try:
6645
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
6646
        except errors.ReservationError:
6647
          raise errors.OpPrereqError("LV named %s used by another instance" %
6648
                                     lv_name, errors.ECODE_NOTUNIQUE)
6649

    
6650
      node_lvs = self.rpc.call_lv_list([pnode.name],
6651
                                       self.cfg.GetVGName())[pnode.name]
6652
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
6653
      node_lvs = node_lvs.payload
6654
      delta = all_lvs.difference(node_lvs.keys())
6655
      if delta:
6656
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
6657
                                   utils.CommaJoin(delta),
6658
                                   errors.ECODE_INVAL)
6659
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
6660
      if online_lvs:
6661
        raise errors.OpPrereqError("Online logical volumes found, cannot"
6662
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
6663
                                   errors.ECODE_STATE)
6664
      # update the size of disk based on what is found
6665
      for dsk in self.disks:
6666
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
6667

    
6668
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
6669

    
6670
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
6671

    
6672
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
6673

    
6674
    # memory check on primary node
6675
    if self.op.start:
6676
      _CheckNodeFreeMemory(self, self.pnode.name,
6677
                           "creating instance %s" % self.op.instance_name,
6678
                           self.be_full[constants.BE_MEMORY],
6679
                           self.op.hypervisor)
6680

    
6681
    self.dry_run_result = list(nodenames)
6682

    
6683
  def Exec(self, feedback_fn):
6684
    """Create and add the instance to the cluster.
6685

6686
    """
6687
    instance = self.op.instance_name
6688
    pnode_name = self.pnode.name
6689

    
6690
    ht_kind = self.op.hypervisor
6691
    if ht_kind in constants.HTS_REQ_PORT:
6692
      network_port = self.cfg.AllocatePort()
6693
    else:
6694
      network_port = None
6695

    
6696
    if constants.ENABLE_FILE_STORAGE:
6697
      # this is needed because os.path.join does not accept None arguments
6698
      if self.op.file_storage_dir is None:
6699
        string_file_storage_dir = ""
6700
      else:
6701
        string_file_storage_dir = self.op.file_storage_dir
6702

    
6703
      # build the full file storage dir path
6704
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
6705
                                        string_file_storage_dir, instance)
6706
    else:
6707
      file_storage_dir = ""
6708

    
6709
    disks = _GenerateDiskTemplate(self,
6710
                                  self.op.disk_template,
6711
                                  instance, pnode_name,
6712
                                  self.secondaries,
6713
                                  self.disks,
6714
                                  file_storage_dir,
6715
                                  self.op.file_driver,
6716
                                  0)
6717

    
6718
    iobj = objects.Instance(name=instance, os=self.op.os_type,
6719
                            primary_node=pnode_name,
6720
                            nics=self.nics, disks=disks,
6721
                            disk_template=self.op.disk_template,
6722
                            admin_up=False,
6723
                            network_port=network_port,
6724
                            beparams=self.op.beparams,
6725
                            hvparams=self.op.hvparams,
6726
                            hypervisor=self.op.hypervisor,
6727
                            )
6728

    
6729
    if self.adopt_disks:
6730
      # rename LVs to the newly-generated names; we need to construct
6731
      # 'fake' LV disks with the old data, plus the new unique_id
6732
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
6733
      rename_to = []
6734
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
6735
        rename_to.append(t_dsk.logical_id)
6736
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
6737
        self.cfg.SetDiskID(t_dsk, pnode_name)
6738
      result = self.rpc.call_blockdev_rename(pnode_name,
6739
                                             zip(tmp_disks, rename_to))
6740
      result.Raise("Failed to rename adoped LVs")
6741
    else:
6742
      feedback_fn("* creating instance disks...")
6743
      try:
6744
        _CreateDisks(self, iobj)
6745
      except errors.OpExecError:
6746
        self.LogWarning("Device creation failed, reverting...")
6747
        try:
6748
          _RemoveDisks(self, iobj)
6749
        finally:
6750
          self.cfg.ReleaseDRBDMinors(instance)
6751
          raise
6752

    
6753
    feedback_fn("adding instance %s to cluster config" % instance)
6754

    
6755
    self.cfg.AddInstance(iobj, self.proc.GetECId())
6756

    
6757
    # Declare that we don't want to remove the instance lock anymore, as we've
6758
    # added the instance to the config
6759
    del self.remove_locks[locking.LEVEL_INSTANCE]
6760
    # Unlock all the nodes
6761
    if self.op.mode == constants.INSTANCE_IMPORT:
6762
      nodes_keep = [self.op.src_node]
6763
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
6764
                       if node != self.op.src_node]
6765
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
6766
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
6767
    else:
6768
      self.context.glm.release(locking.LEVEL_NODE)
6769
      del self.acquired_locks[locking.LEVEL_NODE]
6770

    
6771
    if self.op.wait_for_sync:
6772
      disk_abort = not _WaitForSync(self, iobj)
6773
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
6774
      # make sure the disks are not degraded (still sync-ing is ok)
6775
      time.sleep(15)
6776
      feedback_fn("* checking mirrors status")
6777
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
6778
    else:
6779
      disk_abort = False
6780

    
6781
    if disk_abort:
6782
      _RemoveDisks(self, iobj)
6783
      self.cfg.RemoveInstance(iobj.name)
6784
      # Make sure the instance lock gets removed
6785
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
6786
      raise errors.OpExecError("There are some degraded disks for"
6787
                               " this instance")
6788

    
6789
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
6790
      if self.op.mode == constants.INSTANCE_CREATE:
6791
        if not self.op.no_install:
6792
          feedback_fn("* running the instance OS create scripts...")
6793
          # FIXME: pass debug option from opcode to backend
6794
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
6795
                                                 self.op.debug_level)
6796
          result.Raise("Could not add os for instance %s"
6797
                       " on node %s" % (instance, pnode_name))
6798

    
6799
      elif self.op.mode == constants.INSTANCE_IMPORT:
6800
        feedback_fn("* running the instance OS import scripts...")
6801

    
6802
        transfers = []
6803

    
6804
        for idx, image in enumerate(self.src_images):
6805
          if not image:
6806
            continue
6807

    
6808
          # FIXME: pass debug option from opcode to backend
6809
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
6810
                                             constants.IEIO_FILE, (image, ),
6811
                                             constants.IEIO_SCRIPT,
6812
                                             (iobj.disks[idx], idx),
6813
                                             None)
6814
          transfers.append(dt)
6815

    
6816
        import_result = \
6817
          masterd.instance.TransferInstanceData(self, feedback_fn,
6818
                                                self.op.src_node, pnode_name,
6819
                                                self.pnode.secondary_ip,
6820
                                                iobj, transfers)
6821
        if not compat.all(import_result):
6822
          self.LogWarning("Some disks for instance %s on node %s were not"
6823
                          " imported successfully" % (instance, pnode_name))
6824

    
6825
      else:
6826
        # also checked in the prereq part
6827
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
6828
                                     % self.op.mode)
6829

    
6830
    if self.op.start:
6831
      iobj.admin_up = True
6832
      self.cfg.Update(iobj, feedback_fn)
6833
      logging.info("Starting instance %s on node %s", instance, pnode_name)
6834
      feedback_fn("* starting instance...")
6835
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
6836
      result.Raise("Could not start instance")
6837

    
6838
    return list(iobj.all_nodes)
6839

    
6840

    
6841
class LUConnectConsole(NoHooksLU):
6842
  """Connect to an instance's console.
6843

6844
  This is somewhat special in that it returns the command line that
6845
  you need to run on the master node in order to connect to the
6846
  console.
6847

6848
  """
6849
  _OP_REQP = ["instance_name"]
6850
  REQ_BGL = False
6851

    
6852
  def ExpandNames(self):
6853
    self._ExpandAndLockInstance()
6854

    
6855
  def CheckPrereq(self):
6856
    """Check prerequisites.
6857

6858
    This checks that the instance is in the cluster.
6859

6860
    """
6861
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6862
    assert self.instance is not None, \
6863
      "Cannot retrieve locked instance %s" % self.op.instance_name
6864
    _CheckNodeOnline(self, self.instance.primary_node)
6865

    
6866
  def Exec(self, feedback_fn):
6867
    """Connect to the console of an instance
6868

6869
    """
6870
    instance = self.instance
6871
    node = instance.primary_node
6872

    
6873
    node_insts = self.rpc.call_instance_list([node],
6874
                                             [instance.hypervisor])[node]
6875
    node_insts.Raise("Can't get node information from %s" % node)
6876

    
6877
    if instance.name not in node_insts.payload:
6878
      raise errors.OpExecError("Instance %s is not running." % instance.name)
6879

    
6880
    logging.debug("Connecting to console of %s on %s", instance.name, node)
6881

    
6882
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
6883
    cluster = self.cfg.GetClusterInfo()
6884
    # beparams and hvparams are passed separately, to avoid editing the
6885
    # instance and then saving the defaults in the instance itself.
6886
    hvparams = cluster.FillHV(instance)
6887
    beparams = cluster.FillBE(instance)
6888
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
6889

    
6890
    # build ssh cmdline
6891
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
6892

    
6893

    
6894
class LUReplaceDisks(LogicalUnit):
6895
  """Replace the disks of an instance.
6896

6897
  """
6898
  HPATH = "mirrors-replace"
6899
  HTYPE = constants.HTYPE_INSTANCE
6900
  _OP_REQP = ["instance_name", "mode", "disks"]
6901
  REQ_BGL = False
6902

    
6903
  def CheckArguments(self):
6904
    if not hasattr(self.op, "remote_node"):
6905
      self.op.remote_node = None
6906
    if not hasattr(self.op, "iallocator"):
6907
      self.op.iallocator = None
6908
    if not hasattr(self.op, "early_release"):
6909
      self.op.early_release = False
6910

    
6911
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
6912
                                  self.op.iallocator)
6913

    
6914
  def ExpandNames(self):
6915
    self._ExpandAndLockInstance()
6916

    
6917
    if self.op.iallocator is not None:
6918
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6919

    
6920
    elif self.op.remote_node is not None:
6921
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
6922
      self.op.remote_node = remote_node
6923

    
6924
      # Warning: do not remove the locking of the new secondary here
6925
      # unless DRBD8.AddChildren is changed to work in parallel;
6926
      # currently it doesn't since parallel invocations of
6927
      # FindUnusedMinor will conflict
6928
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
6929
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6930

    
6931
    else:
6932
      self.needed_locks[locking.LEVEL_NODE] = []
6933
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6934

    
6935
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
6936
                                   self.op.iallocator, self.op.remote_node,
6937
                                   self.op.disks, False, self.op.early_release)
6938

    
6939
    self.tasklets = [self.replacer]
6940

    
6941
  def DeclareLocks(self, level):
6942
    # If we're not already locking all nodes in the set we have to declare the
6943
    # instance's primary/secondary nodes.
6944
    if (level == locking.LEVEL_NODE and
6945
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
6946
      self._LockInstancesNodes()
6947

    
6948
  def BuildHooksEnv(self):
6949
    """Build hooks env.
6950

6951
    This runs on the master, the primary and all the secondaries.
6952

6953
    """
6954
    instance = self.replacer.instance
6955
    env = {
6956
      "MODE": self.op.mode,
6957
      "NEW_SECONDARY": self.op.remote_node,
6958
      "OLD_SECONDARY": instance.secondary_nodes[0],
6959
      }
6960
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6961
    nl = [
6962
      self.cfg.GetMasterNode(),
6963
      instance.primary_node,
6964
      ]
6965
    if self.op.remote_node is not None:
6966
      nl.append(self.op.remote_node)
6967
    return env, nl, nl
6968

    
6969

    
6970
class LUEvacuateNode(LogicalUnit):
6971
  """Relocate the secondary instances from a node.
6972

6973
  """
6974
  HPATH = "node-evacuate"
6975
  HTYPE = constants.HTYPE_NODE
6976
  _OP_REQP = ["node_name"]
6977
  REQ_BGL = False
6978

    
6979
  def CheckArguments(self):
6980
    if not hasattr(self.op, "remote_node"):
6981
      self.op.remote_node = None
6982
    if not hasattr(self.op, "iallocator"):
6983
      self.op.iallocator = None
6984
    if not hasattr(self.op, "early_release"):
6985
      self.op.early_release = False
6986

    
6987
    TLReplaceDisks.CheckArguments(constants.REPLACE_DISK_CHG,
6988
                                  self.op.remote_node,
6989
                                  self.op.iallocator)
6990

    
6991
  def ExpandNames(self):
6992
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6993

    
6994
    self.needed_locks = {}
6995

    
6996
    # Declare node locks
6997
    if self.op.iallocator is not None:
6998
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6999

    
7000
    elif self.op.remote_node is not None:
7001
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7002

    
7003
      # Warning: do not remove the locking of the new secondary here
7004
      # unless DRBD8.AddChildren is changed to work in parallel;
7005
      # currently it doesn't since parallel invocations of
7006
      # FindUnusedMinor will conflict
7007
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
7008
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7009

    
7010
    else:
7011
      raise errors.OpPrereqError("Invalid parameters", errors.ECODE_INVAL)
7012

    
7013
    # Create tasklets for replacing disks for all secondary instances on this
7014
    # node
7015
    names = []
7016
    tasklets = []
7017

    
7018
    for inst in _GetNodeSecondaryInstances(self.cfg, self.op.node_name):
7019
      logging.debug("Replacing disks for instance %s", inst.name)
7020
      names.append(inst.name)
7021

    
7022
      replacer = TLReplaceDisks(self, inst.name, constants.REPLACE_DISK_CHG,
7023
                                self.op.iallocator, self.op.remote_node, [],
7024
                                True, self.op.early_release)
7025
      tasklets.append(replacer)
7026

    
7027
    self.tasklets = tasklets
7028
    self.instance_names = names
7029

    
7030
    # Declare instance locks
7031
    self.needed_locks[locking.LEVEL_INSTANCE] = self.instance_names
7032

    
7033
  def DeclareLocks(self, level):
7034
    # If we're not already locking all nodes in the set we have to declare the
7035
    # instance's primary/secondary nodes.
7036
    if (level == locking.LEVEL_NODE and
7037
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7038
      self._LockInstancesNodes()
7039

    
7040
  def BuildHooksEnv(self):
7041
    """Build hooks env.
7042

7043
    This runs on the master, the primary and all the secondaries.
7044

7045
    """
7046
    env = {
7047
      "NODE_NAME": self.op.node_name,
7048
      }
7049

    
7050
    nl = [self.cfg.GetMasterNode()]
7051

    
7052
    if self.op.remote_node is not None:
7053
      env["NEW_SECONDARY"] = self.op.remote_node
7054
      nl.append(self.op.remote_node)
7055

    
7056
    return (env, nl, nl)
7057

    
7058

    
7059
class TLReplaceDisks(Tasklet):
7060
  """Replaces disks for an instance.
7061

7062
  Note: Locking is not within the scope of this class.
7063

7064
  """
7065
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7066
               disks, delay_iallocator, early_release):
7067
    """Initializes this class.
7068

7069
    """
7070
    Tasklet.__init__(self, lu)
7071

    
7072
    # Parameters
7073
    self.instance_name = instance_name
7074
    self.mode = mode
7075
    self.iallocator_name = iallocator_name
7076
    self.remote_node = remote_node
7077
    self.disks = disks
7078
    self.delay_iallocator = delay_iallocator
7079
    self.early_release = early_release
7080

    
7081
    # Runtime data
7082
    self.instance = None
7083
    self.new_node = None
7084
    self.target_node = None
7085
    self.other_node = None
7086
    self.remote_node_info = None
7087
    self.node_secondary_ip = None
7088

    
7089
  @staticmethod
7090
  def CheckArguments(mode, remote_node, iallocator):
7091
    """Helper function for users of this class.
7092

7093
    """
7094
    # check for valid parameter combination
7095
    if mode == constants.REPLACE_DISK_CHG:
7096
      if remote_node is None and iallocator is None:
7097
        raise errors.OpPrereqError("When changing the secondary either an"
7098
                                   " iallocator script must be used or the"
7099
                                   " new node given", errors.ECODE_INVAL)
7100

    
7101
      if remote_node is not None and iallocator is not None:
7102
        raise errors.OpPrereqError("Give either the iallocator or the new"
7103
                                   " secondary, not both", errors.ECODE_INVAL)
7104

    
7105
    elif remote_node is not None or iallocator is not None:
7106
      # Not replacing the secondary
7107
      raise errors.OpPrereqError("The iallocator and new node options can"
7108
                                 " only be used when changing the"
7109
                                 " secondary node", errors.ECODE_INVAL)
7110

    
7111
  @staticmethod
7112
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7113
    """Compute a new secondary node using an IAllocator.
7114

7115
    """
7116
    ial = IAllocator(lu.cfg, lu.rpc,
7117
                     mode=constants.IALLOCATOR_MODE_RELOC,
7118
                     name=instance_name,
7119
                     relocate_from=relocate_from)
7120

    
7121
    ial.Run(iallocator_name)
7122

    
7123
    if not ial.success:
7124
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7125
                                 " %s" % (iallocator_name, ial.info),
7126
                                 errors.ECODE_NORES)
7127

    
7128
    if len(ial.result) != ial.required_nodes:
7129
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7130
                                 " of nodes (%s), required %s" %
7131
                                 (iallocator_name,
7132
                                  len(ial.result), ial.required_nodes),
7133
                                 errors.ECODE_FAULT)
7134

    
7135
    remote_node_name = ial.result[0]
7136

    
7137
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7138
               instance_name, remote_node_name)
7139

    
7140
    return remote_node_name
7141

    
7142
  def _FindFaultyDisks(self, node_name):
7143
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7144
                                    node_name, True)
7145

    
7146
  def CheckPrereq(self):
7147
    """Check prerequisites.
7148

7149
    This checks that the instance is in the cluster.
7150

7151
    """
7152
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7153
    assert instance is not None, \
7154
      "Cannot retrieve locked instance %s" % self.instance_name
7155

    
7156
    if instance.disk_template != constants.DT_DRBD8:
7157
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7158
                                 " instances", errors.ECODE_INVAL)
7159

    
7160
    if len(instance.secondary_nodes) != 1:
7161
      raise errors.OpPrereqError("The instance has a strange layout,"
7162
                                 " expected one secondary but found %d" %
7163
                                 len(instance.secondary_nodes),
7164
                                 errors.ECODE_FAULT)
7165

    
7166
    if not self.delay_iallocator:
7167
      self._CheckPrereq2()
7168

    
7169
  def _CheckPrereq2(self):
7170
    """Check prerequisites, second part.
7171

7172
    This function should always be part of CheckPrereq. It was separated and is
7173
    now called from Exec because during node evacuation iallocator was only
7174
    called with an unmodified cluster model, not taking planned changes into
7175
    account.
7176

7177
    """
7178
    instance = self.instance
7179
    secondary_node = instance.secondary_nodes[0]
7180

    
7181
    if self.iallocator_name is None:
7182
      remote_node = self.remote_node
7183
    else:
7184
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7185
                                       instance.name, instance.secondary_nodes)
7186

    
7187
    if remote_node is not None:
7188
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7189
      assert self.remote_node_info is not None, \
7190
        "Cannot retrieve locked node %s" % remote_node
7191
    else:
7192
      self.remote_node_info = None
7193

    
7194
    if remote_node == self.instance.primary_node:
7195
      raise errors.OpPrereqError("The specified node is the primary node of"
7196
                                 " the instance.", errors.ECODE_INVAL)
7197

    
7198
    if remote_node == secondary_node:
7199
      raise errors.OpPrereqError("The specified node is already the"
7200
                                 " secondary node of the instance.",
7201
                                 errors.ECODE_INVAL)
7202

    
7203
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7204
                                    constants.REPLACE_DISK_CHG):
7205
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7206
                                 errors.ECODE_INVAL)
7207

    
7208
    if self.mode == constants.REPLACE_DISK_AUTO:
7209
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7210
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7211

    
7212
      if faulty_primary and faulty_secondary:
7213
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7214
                                   " one node and can not be repaired"
7215
                                   " automatically" % self.instance_name,
7216
                                   errors.ECODE_STATE)
7217

    
7218
      if faulty_primary:
7219
        self.disks = faulty_primary
7220
        self.target_node = instance.primary_node
7221
        self.other_node = secondary_node
7222
        check_nodes = [self.target_node, self.other_node]
7223
      elif faulty_secondary:
7224
        self.disks = faulty_secondary
7225
        self.target_node = secondary_node
7226
        self.other_node = instance.primary_node
7227
        check_nodes = [self.target_node, self.other_node]
7228
      else:
7229
        self.disks = []
7230
        check_nodes = []
7231

    
7232
    else:
7233
      # Non-automatic modes
7234
      if self.mode == constants.REPLACE_DISK_PRI:
7235
        self.target_node = instance.primary_node
7236
        self.other_node = secondary_node
7237
        check_nodes = [self.target_node, self.other_node]
7238

    
7239
      elif self.mode == constants.REPLACE_DISK_SEC:
7240
        self.target_node = secondary_node
7241
        self.other_node = instance.primary_node
7242
        check_nodes = [self.target_node, self.other_node]
7243

    
7244
      elif self.mode == constants.REPLACE_DISK_CHG:
7245
        self.new_node = remote_node
7246
        self.other_node = instance.primary_node
7247
        self.target_node = secondary_node
7248
        check_nodes = [self.new_node, self.other_node]
7249

    
7250
        _CheckNodeNotDrained(self.lu, remote_node)
7251

    
7252
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7253
        assert old_node_info is not None
7254
        if old_node_info.offline and not self.early_release:
7255
          # doesn't make sense to delay the release
7256
          self.early_release = True
7257
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7258
                          " early-release mode", secondary_node)
7259

    
7260
      else:
7261
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7262
                                     self.mode)
7263

    
7264
      # If not specified all disks should be replaced
7265
      if not self.disks:
7266
        self.disks = range(len(self.instance.disks))
7267

    
7268
    for node in check_nodes:
7269
      _CheckNodeOnline(self.lu, node)
7270

    
7271
    # Check whether disks are valid
7272
    for disk_idx in self.disks:
7273
      instance.FindDisk(disk_idx)
7274

    
7275
    # Get secondary node IP addresses
7276
    node_2nd_ip = {}
7277

    
7278
    for node_name in [self.target_node, self.other_node, self.new_node]:
7279
      if node_name is not None:
7280
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7281

    
7282
    self.node_secondary_ip = node_2nd_ip
7283

    
7284
  def Exec(self, feedback_fn):
7285
    """Execute disk replacement.
7286

7287
    This dispatches the disk replacement to the appropriate handler.
7288

7289
    """
7290
    if self.delay_iallocator:
7291
      self._CheckPrereq2()
7292

    
7293
    if not self.disks:
7294
      feedback_fn("No disks need replacement")
7295
      return
7296

    
7297
    feedback_fn("Replacing disk(s) %s for %s" %
7298
                (utils.CommaJoin(self.disks), self.instance.name))
7299

    
7300
    activate_disks = (not self.instance.admin_up)
7301

    
7302
    # Activate the instance disks if we're replacing them on a down instance
7303
    if activate_disks:
7304
      _StartInstanceDisks(self.lu, self.instance, True)
7305

    
7306
    try:
7307
      # Should we replace the secondary node?
7308
      if self.new_node is not None:
7309
        fn = self._ExecDrbd8Secondary
7310
      else:
7311
        fn = self._ExecDrbd8DiskOnly
7312

    
7313
      return fn(feedback_fn)
7314

    
7315
    finally:
7316
      # Deactivate the instance disks if we're replacing them on a
7317
      # down instance
7318
      if activate_disks:
7319
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7320

    
7321
  def _CheckVolumeGroup(self, nodes):
7322
    self.lu.LogInfo("Checking volume groups")
7323

    
7324
    vgname = self.cfg.GetVGName()
7325

    
7326
    # Make sure volume group exists on all involved nodes
7327
    results = self.rpc.call_vg_list(nodes)
7328
    if not results:
7329
      raise errors.OpExecError("Can't list volume groups on the nodes")
7330

    
7331
    for node in nodes:
7332
      res = results[node]
7333
      res.Raise("Error checking node %s" % node)
7334
      if vgname not in res.payload:
7335
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7336
                                 (vgname, node))
7337

    
7338
  def _CheckDisksExistence(self, nodes):
7339
    # Check disk existence
7340
    for idx, dev in enumerate(self.instance.disks):
7341
      if idx not in self.disks:
7342
        continue
7343

    
7344
      for node in nodes:
7345
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7346
        self.cfg.SetDiskID(dev, node)
7347

    
7348
        result = self.rpc.call_blockdev_find(node, dev)
7349

    
7350
        msg = result.fail_msg
7351
        if msg or not result.payload:
7352
          if not msg:
7353
            msg = "disk not found"
7354
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7355
                                   (idx, node, msg))
7356

    
7357
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7358
    for idx, dev in enumerate(self.instance.disks):
7359
      if idx not in self.disks:
7360
        continue
7361

    
7362
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7363
                      (idx, node_name))
7364

    
7365
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7366
                                   ldisk=ldisk):
7367
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7368
                                 " replace disks for instance %s" %
7369
                                 (node_name, self.instance.name))
7370

    
7371
  def _CreateNewStorage(self, node_name):
7372
    vgname = self.cfg.GetVGName()
7373
    iv_names = {}
7374

    
7375
    for idx, dev in enumerate(self.instance.disks):
7376
      if idx not in self.disks:
7377
        continue
7378

    
7379
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7380

    
7381
      self.cfg.SetDiskID(dev, node_name)
7382

    
7383
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7384
      names = _GenerateUniqueNames(self.lu, lv_names)
7385

    
7386
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7387
                             logical_id=(vgname, names[0]))
7388
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7389
                             logical_id=(vgname, names[1]))
7390

    
7391
      new_lvs = [lv_data, lv_meta]
7392
      old_lvs = dev.children
7393
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7394

    
7395
      # we pass force_create=True to force the LVM creation
7396
      for new_lv in new_lvs:
7397
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7398
                        _GetInstanceInfoText(self.instance), False)
7399

    
7400
    return iv_names
7401

    
7402
  def _CheckDevices(self, node_name, iv_names):
7403
    for name, (dev, _, _) in iv_names.iteritems():
7404
      self.cfg.SetDiskID(dev, node_name)
7405

    
7406
      result = self.rpc.call_blockdev_find(node_name, dev)
7407

    
7408
      msg = result.fail_msg
7409
      if msg or not result.payload:
7410
        if not msg:
7411
          msg = "disk not found"
7412
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7413
                                 (name, msg))
7414

    
7415
      if result.payload.is_degraded:
7416
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7417

    
7418
  def _RemoveOldStorage(self, node_name, iv_names):
7419
    for name, (_, old_lvs, _) in iv_names.iteritems():
7420
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7421

    
7422
      for lv in old_lvs:
7423
        self.cfg.SetDiskID(lv, node_name)
7424

    
7425
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7426
        if msg:
7427
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7428
                             hint="remove unused LVs manually")
7429

    
7430
  def _ReleaseNodeLock(self, node_name):
7431
    """Releases the lock for a given node."""
7432
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7433

    
7434
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7435
    """Replace a disk on the primary or secondary for DRBD 8.
7436

7437
    The algorithm for replace is quite complicated:
7438

7439
      1. for each disk to be replaced:
7440

7441
        1. create new LVs on the target node with unique names
7442
        1. detach old LVs from the drbd device
7443
        1. rename old LVs to name_replaced.<time_t>
7444
        1. rename new LVs to old LVs
7445
        1. attach the new LVs (with the old names now) to the drbd device
7446

7447
      1. wait for sync across all devices
7448

7449
      1. for each modified disk:
7450

7451
        1. remove old LVs (which have the name name_replaces.<time_t>)
7452

7453
    Failures are not very well handled.
7454

7455
    """
7456
    steps_total = 6
7457

    
7458
    # Step: check device activation
7459
    self.lu.LogStep(1, steps_total, "Check device existence")
7460
    self._CheckDisksExistence([self.other_node, self.target_node])
7461
    self._CheckVolumeGroup([self.target_node, self.other_node])
7462

    
7463
    # Step: check other node consistency
7464
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7465
    self._CheckDisksConsistency(self.other_node,
7466
                                self.other_node == self.instance.primary_node,
7467
                                False)
7468

    
7469
    # Step: create new storage
7470
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7471
    iv_names = self._CreateNewStorage(self.target_node)
7472

    
7473
    # Step: for each lv, detach+rename*2+attach
7474
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7475
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7476
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7477

    
7478
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7479
                                                     old_lvs)
7480
      result.Raise("Can't detach drbd from local storage on node"
7481
                   " %s for device %s" % (self.target_node, dev.iv_name))
7482
      #dev.children = []
7483
      #cfg.Update(instance)
7484

    
7485
      # ok, we created the new LVs, so now we know we have the needed
7486
      # storage; as such, we proceed on the target node to rename
7487
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7488
      # using the assumption that logical_id == physical_id (which in
7489
      # turn is the unique_id on that node)
7490

    
7491
      # FIXME(iustin): use a better name for the replaced LVs
7492
      temp_suffix = int(time.time())
7493
      ren_fn = lambda d, suff: (d.physical_id[0],
7494
                                d.physical_id[1] + "_replaced-%s" % suff)
7495

    
7496
      # Build the rename list based on what LVs exist on the node
7497
      rename_old_to_new = []
7498
      for to_ren in old_lvs:
7499
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7500
        if not result.fail_msg and result.payload:
7501
          # device exists
7502
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7503

    
7504
      self.lu.LogInfo("Renaming the old LVs on the target node")
7505
      result = self.rpc.call_blockdev_rename(self.target_node,
7506
                                             rename_old_to_new)
7507
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7508

    
7509
      # Now we rename the new LVs to the old LVs
7510
      self.lu.LogInfo("Renaming the new LVs on the target node")
7511
      rename_new_to_old = [(new, old.physical_id)
7512
                           for old, new in zip(old_lvs, new_lvs)]
7513
      result = self.rpc.call_blockdev_rename(self.target_node,
7514
                                             rename_new_to_old)
7515
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7516

    
7517
      for old, new in zip(old_lvs, new_lvs):
7518
        new.logical_id = old.logical_id
7519
        self.cfg.SetDiskID(new, self.target_node)
7520

    
7521
      for disk in old_lvs:
7522
        disk.logical_id = ren_fn(disk, temp_suffix)
7523
        self.cfg.SetDiskID(disk, self.target_node)
7524

    
7525
      # Now that the new lvs have the old name, we can add them to the device
7526
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7527
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7528
                                                  new_lvs)
7529
      msg = result.fail_msg
7530
      if msg:
7531
        for new_lv in new_lvs:
7532
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7533
                                               new_lv).fail_msg
7534
          if msg2:
7535
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7536
                               hint=("cleanup manually the unused logical"
7537
                                     "volumes"))
7538
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7539

    
7540
      dev.children = new_lvs
7541

    
7542
      self.cfg.Update(self.instance, feedback_fn)
7543

    
7544
    cstep = 5
7545
    if self.early_release:
7546
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7547
      cstep += 1
7548
      self._RemoveOldStorage(self.target_node, iv_names)
7549
      # WARNING: we release both node locks here, do not do other RPCs
7550
      # than WaitForSync to the primary node
7551
      self._ReleaseNodeLock([self.target_node, self.other_node])
7552

    
7553
    # Wait for sync
7554
    # This can fail as the old devices are degraded and _WaitForSync
7555
    # does a combined result over all disks, so we don't check its return value
7556
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7557
    cstep += 1
7558
    _WaitForSync(self.lu, self.instance)
7559

    
7560
    # Check all devices manually
7561
    self._CheckDevices(self.instance.primary_node, iv_names)
7562

    
7563
    # Step: remove old storage
7564
    if not self.early_release:
7565
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7566
      cstep += 1
7567
      self._RemoveOldStorage(self.target_node, iv_names)
7568

    
7569
  def _ExecDrbd8Secondary(self, feedback_fn):
7570
    """Replace the secondary node for DRBD 8.
7571

7572
    The algorithm for replace is quite complicated:
7573
      - for all disks of the instance:
7574
        - create new LVs on the new node with same names
7575
        - shutdown the drbd device on the old secondary
7576
        - disconnect the drbd network on the primary
7577
        - create the drbd device on the new secondary
7578
        - network attach the drbd on the primary, using an artifice:
7579
          the drbd code for Attach() will connect to the network if it
7580
          finds a device which is connected to the good local disks but
7581
          not network enabled
7582
      - wait for sync across all devices
7583
      - remove all disks from the old secondary
7584

7585
    Failures are not very well handled.
7586

7587
    """
7588
    steps_total = 6
7589

    
7590
    # Step: check device activation
7591
    self.lu.LogStep(1, steps_total, "Check device existence")
7592
    self._CheckDisksExistence([self.instance.primary_node])
7593
    self._CheckVolumeGroup([self.instance.primary_node])
7594

    
7595
    # Step: check other node consistency
7596
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7597
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7598

    
7599
    # Step: create new storage
7600
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7601
    for idx, dev in enumerate(self.instance.disks):
7602
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7603
                      (self.new_node, idx))
7604
      # we pass force_create=True to force LVM creation
7605
      for new_lv in dev.children:
7606
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7607
                        _GetInstanceInfoText(self.instance), False)
7608

    
7609
    # Step 4: dbrd minors and drbd setups changes
7610
    # after this, we must manually remove the drbd minors on both the
7611
    # error and the success paths
7612
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7613
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7614
                                         for dev in self.instance.disks],
7615
                                        self.instance.name)
7616
    logging.debug("Allocated minors %r", minors)
7617

    
7618
    iv_names = {}
7619
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7620
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7621
                      (self.new_node, idx))
7622
      # create new devices on new_node; note that we create two IDs:
7623
      # one without port, so the drbd will be activated without
7624
      # networking information on the new node at this stage, and one
7625
      # with network, for the latter activation in step 4
7626
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7627
      if self.instance.primary_node == o_node1:
7628
        p_minor = o_minor1
7629
      else:
7630
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7631
        p_minor = o_minor2
7632

    
7633
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7634
                      p_minor, new_minor, o_secret)
7635
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7636
                    p_minor, new_minor, o_secret)
7637

    
7638
      iv_names[idx] = (dev, dev.children, new_net_id)
7639
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7640
                    new_net_id)
7641
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7642
                              logical_id=new_alone_id,
7643
                              children=dev.children,
7644
                              size=dev.size)
7645
      try:
7646
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7647
                              _GetInstanceInfoText(self.instance), False)
7648
      except errors.GenericError:
7649
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7650
        raise
7651

    
7652
    # We have new devices, shutdown the drbd on the old secondary
7653
    for idx, dev in enumerate(self.instance.disks):
7654
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7655
      self.cfg.SetDiskID(dev, self.target_node)
7656
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7657
      if msg:
7658
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7659
                           "node: %s" % (idx, msg),
7660
                           hint=("Please cleanup this device manually as"
7661
                                 " soon as possible"))
7662

    
7663
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7664
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7665
                                               self.node_secondary_ip,
7666
                                               self.instance.disks)\
7667
                                              [self.instance.primary_node]
7668

    
7669
    msg = result.fail_msg
7670
    if msg:
7671
      # detaches didn't succeed (unlikely)
7672
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7673
      raise errors.OpExecError("Can't detach the disks from the network on"
7674
                               " old node: %s" % (msg,))
7675

    
7676
    # if we managed to detach at least one, we update all the disks of
7677
    # the instance to point to the new secondary
7678
    self.lu.LogInfo("Updating instance configuration")
7679
    for dev, _, new_logical_id in iv_names.itervalues():
7680
      dev.logical_id = new_logical_id
7681
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7682

    
7683
    self.cfg.Update(self.instance, feedback_fn)
7684

    
7685
    # and now perform the drbd attach
7686
    self.lu.LogInfo("Attaching primary drbds to new secondary"
7687
                    " (standalone => connected)")
7688
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
7689
                                            self.new_node],
7690
                                           self.node_secondary_ip,
7691
                                           self.instance.disks,
7692
                                           self.instance.name,
7693
                                           False)
7694
    for to_node, to_result in result.items():
7695
      msg = to_result.fail_msg
7696
      if msg:
7697
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
7698
                           to_node, msg,
7699
                           hint=("please do a gnt-instance info to see the"
7700
                                 " status of disks"))
7701
    cstep = 5
7702
    if self.early_release:
7703
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7704
      cstep += 1
7705
      self._RemoveOldStorage(self.target_node, iv_names)
7706
      # WARNING: we release all node locks here, do not do other RPCs
7707
      # than WaitForSync to the primary node
7708
      self._ReleaseNodeLock([self.instance.primary_node,
7709
                             self.target_node,
7710
                             self.new_node])
7711

    
7712
    # Wait for sync
7713
    # This can fail as the old devices are degraded and _WaitForSync
7714
    # does a combined result over all disks, so we don't check its return value
7715
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7716
    cstep += 1
7717
    _WaitForSync(self.lu, self.instance)
7718

    
7719
    # Check all devices manually
7720
    self._CheckDevices(self.instance.primary_node, iv_names)
7721

    
7722
    # Step: remove old storage
7723
    if not self.early_release:
7724
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7725
      self._RemoveOldStorage(self.target_node, iv_names)
7726

    
7727

    
7728
class LURepairNodeStorage(NoHooksLU):
7729
  """Repairs the volume group on a node.
7730

7731
  """
7732
  _OP_REQP = ["node_name"]
7733
  REQ_BGL = False
7734

    
7735
  def CheckArguments(self):
7736
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
7737

    
7738
    _CheckStorageType(self.op.storage_type)
7739

    
7740
  def ExpandNames(self):
7741
    self.needed_locks = {
7742
      locking.LEVEL_NODE: [self.op.node_name],
7743
      }
7744

    
7745
  def _CheckFaultyDisks(self, instance, node_name):
7746
    """Ensure faulty disks abort the opcode or at least warn."""
7747
    try:
7748
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
7749
                                  node_name, True):
7750
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
7751
                                   " node '%s'" % (instance.name, node_name),
7752
                                   errors.ECODE_STATE)
7753
    except errors.OpPrereqError, err:
7754
      if self.op.ignore_consistency:
7755
        self.proc.LogWarning(str(err.args[0]))
7756
      else:
7757
        raise
7758

    
7759
  def CheckPrereq(self):
7760
    """Check prerequisites.
7761

7762
    """
7763
    storage_type = self.op.storage_type
7764

    
7765
    if (constants.SO_FIX_CONSISTENCY not in
7766
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
7767
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
7768
                                 " repaired" % storage_type,
7769
                                 errors.ECODE_INVAL)
7770

    
7771
    # Check whether any instance on this node has faulty disks
7772
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
7773
      if not inst.admin_up:
7774
        continue
7775
      check_nodes = set(inst.all_nodes)
7776
      check_nodes.discard(self.op.node_name)
7777
      for inst_node_name in check_nodes:
7778
        self._CheckFaultyDisks(inst, inst_node_name)
7779

    
7780
  def Exec(self, feedback_fn):
7781
    feedback_fn("Repairing storage unit '%s' on %s ..." %
7782
                (self.op.name, self.op.node_name))
7783

    
7784
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
7785
    result = self.rpc.call_storage_execute(self.op.node_name,
7786
                                           self.op.storage_type, st_args,
7787
                                           self.op.name,
7788
                                           constants.SO_FIX_CONSISTENCY)
7789
    result.Raise("Failed to repair storage unit '%s' on %s" %
7790
                 (self.op.name, self.op.node_name))
7791

    
7792

    
7793
class LUNodeEvacuationStrategy(NoHooksLU):
7794
  """Computes the node evacuation strategy.
7795

7796
  """
7797
  _OP_REQP = ["nodes"]
7798
  REQ_BGL = False
7799

    
7800
  def CheckArguments(self):
7801
    if not hasattr(self.op, "remote_node"):
7802
      self.op.remote_node = None
7803
    if not hasattr(self.op, "iallocator"):
7804
      self.op.iallocator = None
7805
    if self.op.remote_node is not None and self.op.iallocator is not None:
7806
      raise errors.OpPrereqError("Give either the iallocator or the new"
7807
                                 " secondary, not both", errors.ECODE_INVAL)
7808

    
7809
  def ExpandNames(self):
7810
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
7811
    self.needed_locks = locks = {}
7812
    if self.op.remote_node is None:
7813
      locks[locking.LEVEL_NODE] = locking.ALL_SET
7814
    else:
7815
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7816
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
7817

    
7818
  def CheckPrereq(self):
7819
    pass
7820

    
7821
  def Exec(self, feedback_fn):
7822
    if self.op.remote_node is not None:
7823
      instances = []
7824
      for node in self.op.nodes:
7825
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
7826
      result = []
7827
      for i in instances:
7828
        if i.primary_node == self.op.remote_node:
7829
          raise errors.OpPrereqError("Node %s is the primary node of"
7830
                                     " instance %s, cannot use it as"
7831
                                     " secondary" %
7832
                                     (self.op.remote_node, i.name),
7833
                                     errors.ECODE_INVAL)
7834
        result.append([i.name, self.op.remote_node])
7835
    else:
7836
      ial = IAllocator(self.cfg, self.rpc,
7837
                       mode=constants.IALLOCATOR_MODE_MEVAC,
7838
                       evac_nodes=self.op.nodes)
7839
      ial.Run(self.op.iallocator, validate=True)
7840
      if not ial.success:
7841
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
7842
                                 errors.ECODE_NORES)
7843
      result = ial.result
7844
    return result
7845

    
7846

    
7847
class LUGrowDisk(LogicalUnit):
7848
  """Grow a disk of an instance.
7849

7850
  """
7851
  HPATH = "disk-grow"
7852
  HTYPE = constants.HTYPE_INSTANCE
7853
  _OP_REQP = ["instance_name", "disk", "amount", "wait_for_sync"]
7854
  REQ_BGL = False
7855

    
7856
  def ExpandNames(self):
7857
    self._ExpandAndLockInstance()
7858
    self.needed_locks[locking.LEVEL_NODE] = []
7859
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7860

    
7861
  def DeclareLocks(self, level):
7862
    if level == locking.LEVEL_NODE:
7863
      self._LockInstancesNodes()
7864

    
7865
  def BuildHooksEnv(self):
7866
    """Build hooks env.
7867

7868
    This runs on the master, the primary and all the secondaries.
7869

7870
    """
7871
    env = {
7872
      "DISK": self.op.disk,
7873
      "AMOUNT": self.op.amount,
7874
      }
7875
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
7876
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
7877
    return env, nl, nl
7878

    
7879
  def CheckPrereq(self):
7880
    """Check prerequisites.
7881

7882
    This checks that the instance is in the cluster.
7883

7884
    """
7885
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7886
    assert instance is not None, \
7887
      "Cannot retrieve locked instance %s" % self.op.instance_name
7888
    nodenames = list(instance.all_nodes)
7889
    for node in nodenames:
7890
      _CheckNodeOnline(self, node)
7891

    
7892

    
7893
    self.instance = instance
7894

    
7895
    if instance.disk_template not in constants.DTS_GROWABLE:
7896
      raise errors.OpPrereqError("Instance's disk layout does not support"
7897
                                 " growing.", errors.ECODE_INVAL)
7898

    
7899
    self.disk = instance.FindDisk(self.op.disk)
7900

    
7901
    if instance.disk_template != constants.DT_FILE:
7902
      # TODO: check the free disk space for file, when that feature will be
7903
      # supported
7904
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
7905

    
7906
  def Exec(self, feedback_fn):
7907
    """Execute disk grow.
7908

7909
    """
7910
    instance = self.instance
7911
    disk = self.disk
7912
    for node in instance.all_nodes:
7913
      self.cfg.SetDiskID(disk, node)
7914
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
7915
      result.Raise("Grow request failed to node %s" % node)
7916

    
7917
      # TODO: Rewrite code to work properly
7918
      # DRBD goes into sync mode for a short amount of time after executing the
7919
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
7920
      # calling "resize" in sync mode fails. Sleeping for a short amount of
7921
      # time is a work-around.
7922
      time.sleep(5)
7923

    
7924
    disk.RecordGrow(self.op.amount)
7925
    self.cfg.Update(instance, feedback_fn)
7926
    if self.op.wait_for_sync:
7927
      disk_abort = not _WaitForSync(self, instance)
7928
      if disk_abort:
7929
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
7930
                             " status.\nPlease check the instance.")
7931

    
7932

    
7933
class LUQueryInstanceData(NoHooksLU):
7934
  """Query runtime instance data.
7935

7936
  """
7937
  _OP_REQP = ["instances", "static"]
7938
  REQ_BGL = False
7939

    
7940
  def ExpandNames(self):
7941
    self.needed_locks = {}
7942
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
7943

    
7944
    if not isinstance(self.op.instances, list):
7945
      raise errors.OpPrereqError("Invalid argument type 'instances'",
7946
                                 errors.ECODE_INVAL)
7947

    
7948
    if self.op.instances:
7949
      self.wanted_names = []
7950
      for name in self.op.instances:
7951
        full_name = _ExpandInstanceName(self.cfg, name)
7952
        self.wanted_names.append(full_name)
7953
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
7954
    else:
7955
      self.wanted_names = None
7956
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
7957

    
7958
    self.needed_locks[locking.LEVEL_NODE] = []
7959
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7960

    
7961
  def DeclareLocks(self, level):
7962
    if level == locking.LEVEL_NODE:
7963
      self._LockInstancesNodes()
7964

    
7965
  def CheckPrereq(self):
7966
    """Check prerequisites.
7967

7968
    This only checks the optional instance list against the existing names.
7969

7970
    """
7971
    if self.wanted_names is None:
7972
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
7973

    
7974
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
7975
                             in self.wanted_names]
7976
    return
7977

    
7978
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
7979
    """Returns the status of a block device
7980

7981
    """
7982
    if self.op.static or not node:
7983
      return None
7984

    
7985
    self.cfg.SetDiskID(dev, node)
7986

    
7987
    result = self.rpc.call_blockdev_find(node, dev)
7988
    if result.offline:
7989
      return None
7990

    
7991
    result.Raise("Can't compute disk status for %s" % instance_name)
7992

    
7993
    status = result.payload
7994
    if status is None:
7995
      return None
7996

    
7997
    return (status.dev_path, status.major, status.minor,
7998
            status.sync_percent, status.estimated_time,
7999
            status.is_degraded, status.ldisk_status)
8000

    
8001
  def _ComputeDiskStatus(self, instance, snode, dev):
8002
    """Compute block device status.
8003

8004
    """
8005
    if dev.dev_type in constants.LDS_DRBD:
8006
      # we change the snode then (otherwise we use the one passed in)
8007
      if dev.logical_id[0] == instance.primary_node:
8008
        snode = dev.logical_id[1]
8009
      else:
8010
        snode = dev.logical_id[0]
8011

    
8012
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8013
                                              instance.name, dev)
8014
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8015

    
8016
    if dev.children:
8017
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8018
                      for child in dev.children]
8019
    else:
8020
      dev_children = []
8021

    
8022
    data = {
8023
      "iv_name": dev.iv_name,
8024
      "dev_type": dev.dev_type,
8025
      "logical_id": dev.logical_id,
8026
      "physical_id": dev.physical_id,
8027
      "pstatus": dev_pstatus,
8028
      "sstatus": dev_sstatus,
8029
      "children": dev_children,
8030
      "mode": dev.mode,
8031
      "size": dev.size,
8032
      }
8033

    
8034
    return data
8035

    
8036
  def Exec(self, feedback_fn):
8037
    """Gather and return data"""
8038
    result = {}
8039

    
8040
    cluster = self.cfg.GetClusterInfo()
8041

    
8042
    for instance in self.wanted_instances:
8043
      if not self.op.static:
8044
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8045
                                                  instance.name,
8046
                                                  instance.hypervisor)
8047
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8048
        remote_info = remote_info.payload
8049
        if remote_info and "state" in remote_info:
8050
          remote_state = "up"
8051
        else:
8052
          remote_state = "down"
8053
      else:
8054
        remote_state = None
8055
      if instance.admin_up:
8056
        config_state = "up"
8057
      else:
8058
        config_state = "down"
8059

    
8060
      disks = [self._ComputeDiskStatus(instance, None, device)
8061
               for device in instance.disks]
8062

    
8063
      idict = {
8064
        "name": instance.name,
8065
        "config_state": config_state,
8066
        "run_state": remote_state,
8067
        "pnode": instance.primary_node,
8068
        "snodes": instance.secondary_nodes,
8069
        "os": instance.os,
8070
        # this happens to be the same format used for hooks
8071
        "nics": _NICListToTuple(self, instance.nics),
8072
        "disk_template": instance.disk_template,
8073
        "disks": disks,
8074
        "hypervisor": instance.hypervisor,
8075
        "network_port": instance.network_port,
8076
        "hv_instance": instance.hvparams,
8077
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8078
        "be_instance": instance.beparams,
8079
        "be_actual": cluster.FillBE(instance),
8080
        "serial_no": instance.serial_no,
8081
        "mtime": instance.mtime,
8082
        "ctime": instance.ctime,
8083
        "uuid": instance.uuid,
8084
        }
8085

    
8086
      result[instance.name] = idict
8087

    
8088
    return result
8089

    
8090

    
8091
class LUSetInstanceParams(LogicalUnit):
8092
  """Modifies an instances's parameters.
8093

8094
  """
8095
  HPATH = "instance-modify"
8096
  HTYPE = constants.HTYPE_INSTANCE
8097
  _OP_REQP = ["instance_name"]
8098
  REQ_BGL = False
8099

    
8100
  def CheckArguments(self):
8101
    if not hasattr(self.op, 'nics'):
8102
      self.op.nics = []
8103
    if not hasattr(self.op, 'disks'):
8104
      self.op.disks = []
8105
    if not hasattr(self.op, 'beparams'):
8106
      self.op.beparams = {}
8107
    if not hasattr(self.op, 'hvparams'):
8108
      self.op.hvparams = {}
8109
    if not hasattr(self.op, "disk_template"):
8110
      self.op.disk_template = None
8111
    if not hasattr(self.op, "remote_node"):
8112
      self.op.remote_node = None
8113
    if not hasattr(self.op, "os_name"):
8114
      self.op.os_name = None
8115
    if not hasattr(self.op, "force_variant"):
8116
      self.op.force_variant = False
8117
    self.op.force = getattr(self.op, "force", False)
8118
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8119
            self.op.hvparams or self.op.beparams or self.op.os_name):
8120
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8121

    
8122
    if self.op.hvparams:
8123
      _CheckGlobalHvParams(self.op.hvparams)
8124

    
8125
    # Disk validation
8126
    disk_addremove = 0
8127
    for disk_op, disk_dict in self.op.disks:
8128
      if disk_op == constants.DDM_REMOVE:
8129
        disk_addremove += 1
8130
        continue
8131
      elif disk_op == constants.DDM_ADD:
8132
        disk_addremove += 1
8133
      else:
8134
        if not isinstance(disk_op, int):
8135
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8136
        if not isinstance(disk_dict, dict):
8137
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8138
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8139

    
8140
      if disk_op == constants.DDM_ADD:
8141
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8142
        if mode not in constants.DISK_ACCESS_SET:
8143
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8144
                                     errors.ECODE_INVAL)
8145
        size = disk_dict.get('size', None)
8146
        if size is None:
8147
          raise errors.OpPrereqError("Required disk parameter size missing",
8148
                                     errors.ECODE_INVAL)
8149
        try:
8150
          size = int(size)
8151
        except (TypeError, ValueError), err:
8152
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8153
                                     str(err), errors.ECODE_INVAL)
8154
        disk_dict['size'] = size
8155
      else:
8156
        # modification of disk
8157
        if 'size' in disk_dict:
8158
          raise errors.OpPrereqError("Disk size change not possible, use"
8159
                                     " grow-disk", errors.ECODE_INVAL)
8160

    
8161
    if disk_addremove > 1:
8162
      raise errors.OpPrereqError("Only one disk add or remove operation"
8163
                                 " supported at a time", errors.ECODE_INVAL)
8164

    
8165
    if self.op.disks and self.op.disk_template is not None:
8166
      raise errors.OpPrereqError("Disk template conversion and other disk"
8167
                                 " changes not supported at the same time",
8168
                                 errors.ECODE_INVAL)
8169

    
8170
    if self.op.disk_template:
8171
      _CheckDiskTemplate(self.op.disk_template)
8172
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8173
          self.op.remote_node is None):
8174
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8175
                                   " one requires specifying a secondary node",
8176
                                   errors.ECODE_INVAL)
8177

    
8178
    # NIC validation
8179
    nic_addremove = 0
8180
    for nic_op, nic_dict in self.op.nics:
8181
      if nic_op == constants.DDM_REMOVE:
8182
        nic_addremove += 1
8183
        continue
8184
      elif nic_op == constants.DDM_ADD:
8185
        nic_addremove += 1
8186
      else:
8187
        if not isinstance(nic_op, int):
8188
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8189
        if not isinstance(nic_dict, dict):
8190
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8191
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8192

    
8193
      # nic_dict should be a dict
8194
      nic_ip = nic_dict.get('ip', None)
8195
      if nic_ip is not None:
8196
        if nic_ip.lower() == constants.VALUE_NONE:
8197
          nic_dict['ip'] = None
8198
        else:
8199
          if not utils.IsValidIP(nic_ip):
8200
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8201
                                       errors.ECODE_INVAL)
8202

    
8203
      nic_bridge = nic_dict.get('bridge', None)
8204
      nic_link = nic_dict.get('link', None)
8205
      if nic_bridge and nic_link:
8206
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8207
                                   " at the same time", errors.ECODE_INVAL)
8208
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8209
        nic_dict['bridge'] = None
8210
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8211
        nic_dict['link'] = None
8212

    
8213
      if nic_op == constants.DDM_ADD:
8214
        nic_mac = nic_dict.get('mac', None)
8215
        if nic_mac is None:
8216
          nic_dict['mac'] = constants.VALUE_AUTO
8217

    
8218
      if 'mac' in nic_dict:
8219
        nic_mac = nic_dict['mac']
8220
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8221
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8222

    
8223
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8224
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8225
                                     " modifying an existing nic",
8226
                                     errors.ECODE_INVAL)
8227

    
8228
    if nic_addremove > 1:
8229
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8230
                                 " supported at a time", errors.ECODE_INVAL)
8231

    
8232
  def ExpandNames(self):
8233
    self._ExpandAndLockInstance()
8234
    self.needed_locks[locking.LEVEL_NODE] = []
8235
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8236

    
8237
  def DeclareLocks(self, level):
8238
    if level == locking.LEVEL_NODE:
8239
      self._LockInstancesNodes()
8240
      if self.op.disk_template and self.op.remote_node:
8241
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8242
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8243

    
8244
  def BuildHooksEnv(self):
8245
    """Build hooks env.
8246

8247
    This runs on the master, primary and secondaries.
8248

8249
    """
8250
    args = dict()
8251
    if constants.BE_MEMORY in self.be_new:
8252
      args['memory'] = self.be_new[constants.BE_MEMORY]
8253
    if constants.BE_VCPUS in self.be_new:
8254
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8255
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8256
    # information at all.
8257
    if self.op.nics:
8258
      args['nics'] = []
8259
      nic_override = dict(self.op.nics)
8260
      c_nicparams = self.cluster.nicparams[constants.PP_DEFAULT]
8261
      for idx, nic in enumerate(self.instance.nics):
8262
        if idx in nic_override:
8263
          this_nic_override = nic_override[idx]
8264
        else:
8265
          this_nic_override = {}
8266
        if 'ip' in this_nic_override:
8267
          ip = this_nic_override['ip']
8268
        else:
8269
          ip = nic.ip
8270
        if 'mac' in this_nic_override:
8271
          mac = this_nic_override['mac']
8272
        else:
8273
          mac = nic.mac
8274
        if idx in self.nic_pnew:
8275
          nicparams = self.nic_pnew[idx]
8276
        else:
8277
          nicparams = objects.FillDict(c_nicparams, nic.nicparams)
8278
        mode = nicparams[constants.NIC_MODE]
8279
        link = nicparams[constants.NIC_LINK]
8280
        args['nics'].append((ip, mac, mode, link))
8281
      if constants.DDM_ADD in nic_override:
8282
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8283
        mac = nic_override[constants.DDM_ADD]['mac']
8284
        nicparams = self.nic_pnew[constants.DDM_ADD]
8285
        mode = nicparams[constants.NIC_MODE]
8286
        link = nicparams[constants.NIC_LINK]
8287
        args['nics'].append((ip, mac, mode, link))
8288
      elif constants.DDM_REMOVE in nic_override:
8289
        del args['nics'][-1]
8290

    
8291
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8292
    if self.op.disk_template:
8293
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8294
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8295
    return env, nl, nl
8296

    
8297
  @staticmethod
8298
  def _GetUpdatedParams(old_params, update_dict,
8299
                        default_values, parameter_types):
8300
    """Return the new params dict for the given params.
8301

8302
    @type old_params: dict
8303
    @param old_params: old parameters
8304
    @type update_dict: dict
8305
    @param update_dict: dict containing new parameter values,
8306
                        or constants.VALUE_DEFAULT to reset the
8307
                        parameter to its default value
8308
    @type default_values: dict
8309
    @param default_values: default values for the filled parameters
8310
    @type parameter_types: dict
8311
    @param parameter_types: dict mapping target dict keys to types
8312
                            in constants.ENFORCEABLE_TYPES
8313
    @rtype: (dict, dict)
8314
    @return: (new_parameters, filled_parameters)
8315

8316
    """
8317
    params_copy = copy.deepcopy(old_params)
8318
    for key, val in update_dict.iteritems():
8319
      if val == constants.VALUE_DEFAULT:
8320
        try:
8321
          del params_copy[key]
8322
        except KeyError:
8323
          pass
8324
      else:
8325
        params_copy[key] = val
8326
    utils.ForceDictType(params_copy, parameter_types)
8327
    params_filled = objects.FillDict(default_values, params_copy)
8328
    return (params_copy, params_filled)
8329

    
8330
  def CheckPrereq(self):
8331
    """Check prerequisites.
8332

8333
    This only checks the instance list against the existing names.
8334

8335
    """
8336
    self.force = self.op.force
8337

    
8338
    # checking the new params on the primary/secondary nodes
8339

    
8340
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8341
    cluster = self.cluster = self.cfg.GetClusterInfo()
8342
    assert self.instance is not None, \
8343
      "Cannot retrieve locked instance %s" % self.op.instance_name
8344
    pnode = instance.primary_node
8345
    nodelist = list(instance.all_nodes)
8346

    
8347
    if self.op.disk_template:
8348
      if instance.disk_template == self.op.disk_template:
8349
        raise errors.OpPrereqError("Instance already has disk template %s" %
8350
                                   instance.disk_template, errors.ECODE_INVAL)
8351

    
8352
      if (instance.disk_template,
8353
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8354
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8355
                                   " %s to %s" % (instance.disk_template,
8356
                                                  self.op.disk_template),
8357
                                   errors.ECODE_INVAL)
8358
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8359
        _CheckNodeOnline(self, self.op.remote_node)
8360
        _CheckNodeNotDrained(self, self.op.remote_node)
8361
        disks = [{"size": d.size} for d in instance.disks]
8362
        required = _ComputeDiskSize(self.op.disk_template, disks)
8363
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8364
        _CheckInstanceDown(self, instance, "cannot change disk template")
8365

    
8366
    # hvparams processing
8367
    if self.op.hvparams:
8368
      i_hvdict, hv_new = self._GetUpdatedParams(
8369
                             instance.hvparams, self.op.hvparams,
8370
                             cluster.hvparams[instance.hypervisor],
8371
                             constants.HVS_PARAMETER_TYPES)
8372
      # local check
8373
      hypervisor.GetHypervisor(
8374
        instance.hypervisor).CheckParameterSyntax(hv_new)
8375
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8376
      self.hv_new = hv_new # the new actual values
8377
      self.hv_inst = i_hvdict # the new dict (without defaults)
8378
    else:
8379
      self.hv_new = self.hv_inst = {}
8380

    
8381
    # beparams processing
8382
    if self.op.beparams:
8383
      i_bedict, be_new = self._GetUpdatedParams(
8384
                             instance.beparams, self.op.beparams,
8385
                             cluster.beparams[constants.PP_DEFAULT],
8386
                             constants.BES_PARAMETER_TYPES)
8387
      self.be_new = be_new # the new actual values
8388
      self.be_inst = i_bedict # the new dict (without defaults)
8389
    else:
8390
      self.be_new = self.be_inst = {}
8391

    
8392
    self.warn = []
8393

    
8394
    if constants.BE_MEMORY in self.op.beparams and not self.force:
8395
      mem_check_list = [pnode]
8396
      if be_new[constants.BE_AUTO_BALANCE]:
8397
        # either we changed auto_balance to yes or it was from before
8398
        mem_check_list.extend(instance.secondary_nodes)
8399
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8400
                                                  instance.hypervisor)
8401
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8402
                                         instance.hypervisor)
8403
      pninfo = nodeinfo[pnode]
8404
      msg = pninfo.fail_msg
8405
      if msg:
8406
        # Assume the primary node is unreachable and go ahead
8407
        self.warn.append("Can't get info from primary node %s: %s" %
8408
                         (pnode,  msg))
8409
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8410
        self.warn.append("Node data from primary node %s doesn't contain"
8411
                         " free memory information" % pnode)
8412
      elif instance_info.fail_msg:
8413
        self.warn.append("Can't get instance runtime information: %s" %
8414
                        instance_info.fail_msg)
8415
      else:
8416
        if instance_info.payload:
8417
          current_mem = int(instance_info.payload['memory'])
8418
        else:
8419
          # Assume instance not running
8420
          # (there is a slight race condition here, but it's not very probable,
8421
          # and we have no other way to check)
8422
          current_mem = 0
8423
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8424
                    pninfo.payload['memory_free'])
8425
        if miss_mem > 0:
8426
          raise errors.OpPrereqError("This change will prevent the instance"
8427
                                     " from starting, due to %d MB of memory"
8428
                                     " missing on its primary node" % miss_mem,
8429
                                     errors.ECODE_NORES)
8430

    
8431
      if be_new[constants.BE_AUTO_BALANCE]:
8432
        for node, nres in nodeinfo.items():
8433
          if node not in instance.secondary_nodes:
8434
            continue
8435
          msg = nres.fail_msg
8436
          if msg:
8437
            self.warn.append("Can't get info from secondary node %s: %s" %
8438
                             (node, msg))
8439
          elif not isinstance(nres.payload.get('memory_free', None), int):
8440
            self.warn.append("Secondary node %s didn't return free"
8441
                             " memory information" % node)
8442
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8443
            self.warn.append("Not enough memory to failover instance to"
8444
                             " secondary node %s" % node)
8445

    
8446
    # NIC processing
8447
    self.nic_pnew = {}
8448
    self.nic_pinst = {}
8449
    for nic_op, nic_dict in self.op.nics:
8450
      if nic_op == constants.DDM_REMOVE:
8451
        if not instance.nics:
8452
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8453
                                     errors.ECODE_INVAL)
8454
        continue
8455
      if nic_op != constants.DDM_ADD:
8456
        # an existing nic
8457
        if not instance.nics:
8458
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8459
                                     " no NICs" % nic_op,
8460
                                     errors.ECODE_INVAL)
8461
        if nic_op < 0 or nic_op >= len(instance.nics):
8462
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8463
                                     " are 0 to %d" %
8464
                                     (nic_op, len(instance.nics) - 1),
8465
                                     errors.ECODE_INVAL)
8466
        old_nic_params = instance.nics[nic_op].nicparams
8467
        old_nic_ip = instance.nics[nic_op].ip
8468
      else:
8469
        old_nic_params = {}
8470
        old_nic_ip = None
8471

    
8472
      update_params_dict = dict([(key, nic_dict[key])
8473
                                 for key in constants.NICS_PARAMETERS
8474
                                 if key in nic_dict])
8475

    
8476
      if 'bridge' in nic_dict:
8477
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8478

    
8479
      new_nic_params, new_filled_nic_params = \
8480
          self._GetUpdatedParams(old_nic_params, update_params_dict,
8481
                                 cluster.nicparams[constants.PP_DEFAULT],
8482
                                 constants.NICS_PARAMETER_TYPES)
8483
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8484
      self.nic_pinst[nic_op] = new_nic_params
8485
      self.nic_pnew[nic_op] = new_filled_nic_params
8486
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8487

    
8488
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8489
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8490
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8491
        if msg:
8492
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8493
          if self.force:
8494
            self.warn.append(msg)
8495
          else:
8496
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8497
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8498
        if 'ip' in nic_dict:
8499
          nic_ip = nic_dict['ip']
8500
        else:
8501
          nic_ip = old_nic_ip
8502
        if nic_ip is None:
8503
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8504
                                     ' on a routed nic', errors.ECODE_INVAL)
8505
      if 'mac' in nic_dict:
8506
        nic_mac = nic_dict['mac']
8507
        if nic_mac is None:
8508
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8509
                                     errors.ECODE_INVAL)
8510
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8511
          # otherwise generate the mac
8512
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8513
        else:
8514
          # or validate/reserve the current one
8515
          try:
8516
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8517
          except errors.ReservationError:
8518
            raise errors.OpPrereqError("MAC address %s already in use"
8519
                                       " in cluster" % nic_mac,
8520
                                       errors.ECODE_NOTUNIQUE)
8521

    
8522
    # DISK processing
8523
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8524
      raise errors.OpPrereqError("Disk operations not supported for"
8525
                                 " diskless instances",
8526
                                 errors.ECODE_INVAL)
8527
    for disk_op, _ in self.op.disks:
8528
      if disk_op == constants.DDM_REMOVE:
8529
        if len(instance.disks) == 1:
8530
          raise errors.OpPrereqError("Cannot remove the last disk of"
8531
                                     " an instance", errors.ECODE_INVAL)
8532
        _CheckInstanceDown(self, instance, "cannot remove disks")
8533

    
8534
      if (disk_op == constants.DDM_ADD and
8535
          len(instance.nics) >= constants.MAX_DISKS):
8536
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8537
                                   " add more" % constants.MAX_DISKS,
8538
                                   errors.ECODE_STATE)
8539
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8540
        # an existing disk
8541
        if disk_op < 0 or disk_op >= len(instance.disks):
8542
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8543
                                     " are 0 to %d" %
8544
                                     (disk_op, len(instance.disks)),
8545
                                     errors.ECODE_INVAL)
8546

    
8547
    # OS change
8548
    if self.op.os_name and not self.op.force:
8549
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8550
                      self.op.force_variant)
8551

    
8552
    return
8553

    
8554
  def _ConvertPlainToDrbd(self, feedback_fn):
8555
    """Converts an instance from plain to drbd.
8556

8557
    """
8558
    feedback_fn("Converting template to drbd")
8559
    instance = self.instance
8560
    pnode = instance.primary_node
8561
    snode = self.op.remote_node
8562

    
8563
    # create a fake disk info for _GenerateDiskTemplate
8564
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8565
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8566
                                      instance.name, pnode, [snode],
8567
                                      disk_info, None, None, 0)
8568
    info = _GetInstanceInfoText(instance)
8569
    feedback_fn("Creating aditional volumes...")
8570
    # first, create the missing data and meta devices
8571
    for disk in new_disks:
8572
      # unfortunately this is... not too nice
8573
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8574
                            info, True)
8575
      for child in disk.children:
8576
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8577
    # at this stage, all new LVs have been created, we can rename the
8578
    # old ones
8579
    feedback_fn("Renaming original volumes...")
8580
    rename_list = [(o, n.children[0].logical_id)
8581
                   for (o, n) in zip(instance.disks, new_disks)]
8582
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8583
    result.Raise("Failed to rename original LVs")
8584

    
8585
    feedback_fn("Initializing DRBD devices...")
8586
    # all child devices are in place, we can now create the DRBD devices
8587
    for disk in new_disks:
8588
      for node in [pnode, snode]:
8589
        f_create = node == pnode
8590
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8591

    
8592
    # at this point, the instance has been modified
8593
    instance.disk_template = constants.DT_DRBD8
8594
    instance.disks = new_disks
8595
    self.cfg.Update(instance, feedback_fn)
8596

    
8597
    # disks are created, waiting for sync
8598
    disk_abort = not _WaitForSync(self, instance)
8599
    if disk_abort:
8600
      raise errors.OpExecError("There are some degraded disks for"
8601
                               " this instance, please cleanup manually")
8602

    
8603
  def _ConvertDrbdToPlain(self, feedback_fn):
8604
    """Converts an instance from drbd to plain.
8605

8606
    """
8607
    instance = self.instance
8608
    assert len(instance.secondary_nodes) == 1
8609
    pnode = instance.primary_node
8610
    snode = instance.secondary_nodes[0]
8611
    feedback_fn("Converting template to plain")
8612

    
8613
    old_disks = instance.disks
8614
    new_disks = [d.children[0] for d in old_disks]
8615

    
8616
    # copy over size and mode
8617
    for parent, child in zip(old_disks, new_disks):
8618
      child.size = parent.size
8619
      child.mode = parent.mode
8620

    
8621
    # update instance structure
8622
    instance.disks = new_disks
8623
    instance.disk_template = constants.DT_PLAIN
8624
    self.cfg.Update(instance, feedback_fn)
8625

    
8626
    feedback_fn("Removing volumes on the secondary node...")
8627
    for disk in old_disks:
8628
      self.cfg.SetDiskID(disk, snode)
8629
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
8630
      if msg:
8631
        self.LogWarning("Could not remove block device %s on node %s,"
8632
                        " continuing anyway: %s", disk.iv_name, snode, msg)
8633

    
8634
    feedback_fn("Removing unneeded volumes on the primary node...")
8635
    for idx, disk in enumerate(old_disks):
8636
      meta = disk.children[1]
8637
      self.cfg.SetDiskID(meta, pnode)
8638
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
8639
      if msg:
8640
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
8641
                        " continuing anyway: %s", idx, pnode, msg)
8642

    
8643

    
8644
  def Exec(self, feedback_fn):
8645
    """Modifies an instance.
8646

8647
    All parameters take effect only at the next restart of the instance.
8648

8649
    """
8650
    # Process here the warnings from CheckPrereq, as we don't have a
8651
    # feedback_fn there.
8652
    for warn in self.warn:
8653
      feedback_fn("WARNING: %s" % warn)
8654

    
8655
    result = []
8656
    instance = self.instance
8657
    # disk changes
8658
    for disk_op, disk_dict in self.op.disks:
8659
      if disk_op == constants.DDM_REMOVE:
8660
        # remove the last disk
8661
        device = instance.disks.pop()
8662
        device_idx = len(instance.disks)
8663
        for node, disk in device.ComputeNodeTree(instance.primary_node):
8664
          self.cfg.SetDiskID(disk, node)
8665
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
8666
          if msg:
8667
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
8668
                            " continuing anyway", device_idx, node, msg)
8669
        result.append(("disk/%d" % device_idx, "remove"))
8670
      elif disk_op == constants.DDM_ADD:
8671
        # add a new disk
8672
        if instance.disk_template == constants.DT_FILE:
8673
          file_driver, file_path = instance.disks[0].logical_id
8674
          file_path = os.path.dirname(file_path)
8675
        else:
8676
          file_driver = file_path = None
8677
        disk_idx_base = len(instance.disks)
8678
        new_disk = _GenerateDiskTemplate(self,
8679
                                         instance.disk_template,
8680
                                         instance.name, instance.primary_node,
8681
                                         instance.secondary_nodes,
8682
                                         [disk_dict],
8683
                                         file_path,
8684
                                         file_driver,
8685
                                         disk_idx_base)[0]
8686
        instance.disks.append(new_disk)
8687
        info = _GetInstanceInfoText(instance)
8688

    
8689
        logging.info("Creating volume %s for instance %s",
8690
                     new_disk.iv_name, instance.name)
8691
        # Note: this needs to be kept in sync with _CreateDisks
8692
        #HARDCODE
8693
        for node in instance.all_nodes:
8694
          f_create = node == instance.primary_node
8695
          try:
8696
            _CreateBlockDev(self, node, instance, new_disk,
8697
                            f_create, info, f_create)
8698
          except errors.OpExecError, err:
8699
            self.LogWarning("Failed to create volume %s (%s) on"
8700
                            " node %s: %s",
8701
                            new_disk.iv_name, new_disk, node, err)
8702
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
8703
                       (new_disk.size, new_disk.mode)))
8704
      else:
8705
        # change a given disk
8706
        instance.disks[disk_op].mode = disk_dict['mode']
8707
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
8708

    
8709
    if self.op.disk_template:
8710
      r_shut = _ShutdownInstanceDisks(self, instance)
8711
      if not r_shut:
8712
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
8713
                                 " proceed with disk template conversion")
8714
      mode = (instance.disk_template, self.op.disk_template)
8715
      try:
8716
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
8717
      except:
8718
        self.cfg.ReleaseDRBDMinors(instance.name)
8719
        raise
8720
      result.append(("disk_template", self.op.disk_template))
8721

    
8722
    # NIC changes
8723
    for nic_op, nic_dict in self.op.nics:
8724
      if nic_op == constants.DDM_REMOVE:
8725
        # remove the last nic
8726
        del instance.nics[-1]
8727
        result.append(("nic.%d" % len(instance.nics), "remove"))
8728
      elif nic_op == constants.DDM_ADD:
8729
        # mac and bridge should be set, by now
8730
        mac = nic_dict['mac']
8731
        ip = nic_dict.get('ip', None)
8732
        nicparams = self.nic_pinst[constants.DDM_ADD]
8733
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
8734
        instance.nics.append(new_nic)
8735
        result.append(("nic.%d" % (len(instance.nics) - 1),
8736
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
8737
                       (new_nic.mac, new_nic.ip,
8738
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
8739
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
8740
                       )))
8741
      else:
8742
        for key in 'mac', 'ip':
8743
          if key in nic_dict:
8744
            setattr(instance.nics[nic_op], key, nic_dict[key])
8745
        if nic_op in self.nic_pinst:
8746
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
8747
        for key, val in nic_dict.iteritems():
8748
          result.append(("nic.%s/%d" % (key, nic_op), val))
8749

    
8750
    # hvparams changes
8751
    if self.op.hvparams:
8752
      instance.hvparams = self.hv_inst
8753
      for key, val in self.op.hvparams.iteritems():
8754
        result.append(("hv/%s" % key, val))
8755

    
8756
    # beparams changes
8757
    if self.op.beparams:
8758
      instance.beparams = self.be_inst
8759
      for key, val in self.op.beparams.iteritems():
8760
        result.append(("be/%s" % key, val))
8761

    
8762
    # OS change
8763
    if self.op.os_name:
8764
      instance.os = self.op.os_name
8765

    
8766
    self.cfg.Update(instance, feedback_fn)
8767

    
8768
    return result
8769

    
8770
  _DISK_CONVERSIONS = {
8771
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
8772
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
8773
    }
8774

    
8775

    
8776
class LUQueryExports(NoHooksLU):
8777
  """Query the exports list
8778

8779
  """
8780
  _OP_REQP = ['nodes']
8781
  REQ_BGL = False
8782

    
8783
  def ExpandNames(self):
8784
    self.needed_locks = {}
8785
    self.share_locks[locking.LEVEL_NODE] = 1
8786
    if not self.op.nodes:
8787
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8788
    else:
8789
      self.needed_locks[locking.LEVEL_NODE] = \
8790
        _GetWantedNodes(self, self.op.nodes)
8791

    
8792
  def CheckPrereq(self):
8793
    """Check prerequisites.
8794

8795
    """
8796
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
8797

    
8798
  def Exec(self, feedback_fn):
8799
    """Compute the list of all the exported system images.
8800

8801
    @rtype: dict
8802
    @return: a dictionary with the structure node->(export-list)
8803
        where export-list is a list of the instances exported on
8804
        that node.
8805

8806
    """
8807
    rpcresult = self.rpc.call_export_list(self.nodes)
8808
    result = {}
8809
    for node in rpcresult:
8810
      if rpcresult[node].fail_msg:
8811
        result[node] = False
8812
      else:
8813
        result[node] = rpcresult[node].payload
8814

    
8815
    return result
8816

    
8817

    
8818
class LUExportInstance(LogicalUnit):
8819
  """Export an instance to an image in the cluster.
8820

8821
  """
8822
  HPATH = "instance-export"
8823
  HTYPE = constants.HTYPE_INSTANCE
8824
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
8825
  REQ_BGL = False
8826

    
8827
  def CheckArguments(self):
8828
    """Check the arguments.
8829

8830
    """
8831
    _CheckBooleanOpField(self.op, "remove_instance")
8832
    _CheckBooleanOpField(self.op, "ignore_remove_failures")
8833

    
8834
    self.shutdown_timeout = getattr(self.op, "shutdown_timeout",
8835
                                    constants.DEFAULT_SHUTDOWN_TIMEOUT)
8836
    self.remove_instance = getattr(self.op, "remove_instance", False)
8837
    self.ignore_remove_failures = getattr(self.op, "ignore_remove_failures",
8838
                                          False)
8839

    
8840
    if self.remove_instance and not self.op.shutdown:
8841
      raise errors.OpPrereqError("Can not remove instance without shutting it"
8842
                                 " down before")
8843

    
8844
  def ExpandNames(self):
8845
    self._ExpandAndLockInstance()
8846

    
8847
    # FIXME: lock only instance primary and destination node
8848
    #
8849
    # Sad but true, for now we have do lock all nodes, as we don't know where
8850
    # the previous export might be, and and in this LU we search for it and
8851
    # remove it from its current node. In the future we could fix this by:
8852
    #  - making a tasklet to search (share-lock all), then create the new one,
8853
    #    then one to remove, after
8854
    #  - removing the removal operation altogether
8855
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8856

    
8857
  def DeclareLocks(self, level):
8858
    """Last minute lock declaration."""
8859
    # All nodes are locked anyway, so nothing to do here.
8860

    
8861
  def BuildHooksEnv(self):
8862
    """Build hooks env.
8863

8864
    This will run on the master, primary node and target node.
8865

8866
    """
8867
    env = {
8868
      "EXPORT_NODE": self.op.target_node,
8869
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
8870
      "SHUTDOWN_TIMEOUT": self.shutdown_timeout,
8871
      # TODO: Generic function for boolean env variables
8872
      "REMOVE_INSTANCE": str(bool(self.remove_instance)),
8873
      }
8874
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8875
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node,
8876
          self.op.target_node]
8877
    return env, nl, nl
8878

    
8879
  def CheckPrereq(self):
8880
    """Check prerequisites.
8881

8882
    This checks that the instance and node names are valid.
8883

8884
    """
8885
    instance_name = self.op.instance_name
8886
    self.instance = self.cfg.GetInstanceInfo(instance_name)
8887
    assert self.instance is not None, \
8888
          "Cannot retrieve locked instance %s" % self.op.instance_name
8889
    _CheckNodeOnline(self, self.instance.primary_node)
8890

    
8891
    self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
8892
    self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
8893
    assert self.dst_node is not None
8894

    
8895
    _CheckNodeOnline(self, self.dst_node.name)
8896
    _CheckNodeNotDrained(self, self.dst_node.name)
8897

    
8898
    # instance disk type verification
8899
    # TODO: Implement export support for file-based disks
8900
    for disk in self.instance.disks:
8901
      if disk.dev_type == constants.LD_FILE:
8902
        raise errors.OpPrereqError("Export not supported for instances with"
8903
                                   " file-based disks", errors.ECODE_INVAL)
8904

    
8905
  def _CleanupExports(self, feedback_fn):
8906
    """Removes exports of current instance from all other nodes.
8907

8908
    If an instance in a cluster with nodes A..D was exported to node C, its
8909
    exports will be removed from the nodes A, B and D.
8910

8911
    """
8912
    nodelist = self.cfg.GetNodeList()
8913
    nodelist.remove(self.dst_node.name)
8914

    
8915
    # on one-node clusters nodelist will be empty after the removal
8916
    # if we proceed the backup would be removed because OpQueryExports
8917
    # substitutes an empty list with the full cluster node list.
8918
    iname = self.instance.name
8919
    if nodelist:
8920
      feedback_fn("Removing old exports for instance %s" % iname)
8921
      exportlist = self.rpc.call_export_list(nodelist)
8922
      for node in exportlist:
8923
        if exportlist[node].fail_msg:
8924
          continue
8925
        if iname in exportlist[node].payload:
8926
          msg = self.rpc.call_export_remove(node, iname).fail_msg
8927
          if msg:
8928
            self.LogWarning("Could not remove older export for instance %s"
8929
                            " on node %s: %s", iname, node, msg)
8930

    
8931
  def Exec(self, feedback_fn):
8932
    """Export an instance to an image in the cluster.
8933

8934
    """
8935
    instance = self.instance
8936
    src_node = instance.primary_node
8937

    
8938
    if self.op.shutdown:
8939
      # shutdown the instance, but not the disks
8940
      feedback_fn("Shutting down instance %s" % instance.name)
8941
      result = self.rpc.call_instance_shutdown(src_node, instance,
8942
                                               self.shutdown_timeout)
8943
      # TODO: Maybe ignore failures if ignore_remove_failures is set
8944
      result.Raise("Could not shutdown instance %s on"
8945
                   " node %s" % (instance.name, src_node))
8946

    
8947
    # set the disks ID correctly since call_instance_start needs the
8948
    # correct drbd minor to create the symlinks
8949
    for disk in instance.disks:
8950
      self.cfg.SetDiskID(disk, src_node)
8951

    
8952
    activate_disks = (not instance.admin_up)
8953

    
8954
    if activate_disks:
8955
      # Activate the instance disks if we'exporting a stopped instance
8956
      feedback_fn("Activating disks for %s" % instance.name)
8957
      _StartInstanceDisks(self, instance, None)
8958

    
8959
    try:
8960
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
8961
                                                     instance)
8962

    
8963
      helper.CreateSnapshots()
8964
      try:
8965
        (fin_resu, dresults) = helper.LocalExport(self.dst_node)
8966
      finally:
8967
        helper.Cleanup()
8968

    
8969
      # Check for backwards compatibility
8970
      assert len(dresults) == len(instance.disks)
8971
      assert compat.all(isinstance(i, bool) for i in dresults), \
8972
             "Not all results are boolean: %r" % dresults
8973

    
8974
    finally:
8975
      if activate_disks:
8976
        feedback_fn("Deactivating disks for %s" % instance.name)
8977
        _ShutdownInstanceDisks(self, instance)
8978

    
8979
    # Remove instance if requested
8980
    if self.remove_instance:
8981
      if not (compat.all(dresults) and fin_resu):
8982
        feedback_fn("Not removing instance %s as parts of the export failed" %
8983
                    instance.name)
8984
      else:
8985
        feedback_fn("Removing instance %s" % instance.name)
8986
        _RemoveInstance(self, feedback_fn, instance,
8987
                        self.ignore_remove_failures)
8988

    
8989
    self._CleanupExports(feedback_fn)
8990

    
8991
    return fin_resu, dresults
8992

    
8993

    
8994
class LURemoveExport(NoHooksLU):
8995
  """Remove exports related to the named instance.
8996

8997
  """
8998
  _OP_REQP = ["instance_name"]
8999
  REQ_BGL = False
9000

    
9001
  def ExpandNames(self):
9002
    self.needed_locks = {}
9003
    # We need all nodes to be locked in order for RemoveExport to work, but we
9004
    # don't need to lock the instance itself, as nothing will happen to it (and
9005
    # we can remove exports also for a removed instance)
9006
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9007

    
9008
  def CheckPrereq(self):
9009
    """Check prerequisites.
9010
    """
9011
    pass
9012

    
9013
  def Exec(self, feedback_fn):
9014
    """Remove any export.
9015

9016
    """
9017
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9018
    # If the instance was not found we'll try with the name that was passed in.
9019
    # This will only work if it was an FQDN, though.
9020
    fqdn_warn = False
9021
    if not instance_name:
9022
      fqdn_warn = True
9023
      instance_name = self.op.instance_name
9024

    
9025
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9026
    exportlist = self.rpc.call_export_list(locked_nodes)
9027
    found = False
9028
    for node in exportlist:
9029
      msg = exportlist[node].fail_msg
9030
      if msg:
9031
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9032
        continue
9033
      if instance_name in exportlist[node].payload:
9034
        found = True
9035
        result = self.rpc.call_export_remove(node, instance_name)
9036
        msg = result.fail_msg
9037
        if msg:
9038
          logging.error("Could not remove export for instance %s"
9039
                        " on node %s: %s", instance_name, node, msg)
9040

    
9041
    if fqdn_warn and not found:
9042
      feedback_fn("Export not found. If trying to remove an export belonging"
9043
                  " to a deleted instance please use its Fully Qualified"
9044
                  " Domain Name.")
9045

    
9046

    
9047
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9048
  """Generic tags LU.
9049

9050
  This is an abstract class which is the parent of all the other tags LUs.
9051

9052
  """
9053

    
9054
  def ExpandNames(self):
9055
    self.needed_locks = {}
9056
    if self.op.kind == constants.TAG_NODE:
9057
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9058
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9059
    elif self.op.kind == constants.TAG_INSTANCE:
9060
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9061
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9062

    
9063
  def CheckPrereq(self):
9064
    """Check prerequisites.
9065

9066
    """
9067
    if self.op.kind == constants.TAG_CLUSTER:
9068
      self.target = self.cfg.GetClusterInfo()
9069
    elif self.op.kind == constants.TAG_NODE:
9070
      self.target = self.cfg.GetNodeInfo(self.op.name)
9071
    elif self.op.kind == constants.TAG_INSTANCE:
9072
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9073
    else:
9074
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9075
                                 str(self.op.kind), errors.ECODE_INVAL)
9076

    
9077

    
9078
class LUGetTags(TagsLU):
9079
  """Returns the tags of a given object.
9080

9081
  """
9082
  _OP_REQP = ["kind", "name"]
9083
  REQ_BGL = False
9084

    
9085
  def Exec(self, feedback_fn):
9086
    """Returns the tag list.
9087

9088
    """
9089
    return list(self.target.GetTags())
9090

    
9091

    
9092
class LUSearchTags(NoHooksLU):
9093
  """Searches the tags for a given pattern.
9094

9095
  """
9096
  _OP_REQP = ["pattern"]
9097
  REQ_BGL = False
9098

    
9099
  def ExpandNames(self):
9100
    self.needed_locks = {}
9101

    
9102
  def CheckPrereq(self):
9103
    """Check prerequisites.
9104

9105
    This checks the pattern passed for validity by compiling it.
9106

9107
    """
9108
    try:
9109
      self.re = re.compile(self.op.pattern)
9110
    except re.error, err:
9111
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9112
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9113

    
9114
  def Exec(self, feedback_fn):
9115
    """Returns the tag list.
9116

9117
    """
9118
    cfg = self.cfg
9119
    tgts = [("/cluster", cfg.GetClusterInfo())]
9120
    ilist = cfg.GetAllInstancesInfo().values()
9121
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9122
    nlist = cfg.GetAllNodesInfo().values()
9123
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9124
    results = []
9125
    for path, target in tgts:
9126
      for tag in target.GetTags():
9127
        if self.re.search(tag):
9128
          results.append((path, tag))
9129
    return results
9130

    
9131

    
9132
class LUAddTags(TagsLU):
9133
  """Sets a tag on a given object.
9134

9135
  """
9136
  _OP_REQP = ["kind", "name", "tags"]
9137
  REQ_BGL = False
9138

    
9139
  def CheckPrereq(self):
9140
    """Check prerequisites.
9141

9142
    This checks the type and length of the tag name and value.
9143

9144
    """
9145
    TagsLU.CheckPrereq(self)
9146
    for tag in self.op.tags:
9147
      objects.TaggableObject.ValidateTag(tag)
9148

    
9149
  def Exec(self, feedback_fn):
9150
    """Sets the tag.
9151

9152
    """
9153
    try:
9154
      for tag in self.op.tags:
9155
        self.target.AddTag(tag)
9156
    except errors.TagError, err:
9157
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9158
    self.cfg.Update(self.target, feedback_fn)
9159

    
9160

    
9161
class LUDelTags(TagsLU):
9162
  """Delete a list of tags from a given object.
9163

9164
  """
9165
  _OP_REQP = ["kind", "name", "tags"]
9166
  REQ_BGL = False
9167

    
9168
  def CheckPrereq(self):
9169
    """Check prerequisites.
9170

9171
    This checks that we have the given tag.
9172

9173
    """
9174
    TagsLU.CheckPrereq(self)
9175
    for tag in self.op.tags:
9176
      objects.TaggableObject.ValidateTag(tag)
9177
    del_tags = frozenset(self.op.tags)
9178
    cur_tags = self.target.GetTags()
9179
    if not del_tags <= cur_tags:
9180
      diff_tags = del_tags - cur_tags
9181
      diff_names = ["'%s'" % tag for tag in diff_tags]
9182
      diff_names.sort()
9183
      raise errors.OpPrereqError("Tag(s) %s not found" %
9184
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9185

    
9186
  def Exec(self, feedback_fn):
9187
    """Remove the tag from the object.
9188

9189
    """
9190
    for tag in self.op.tags:
9191
      self.target.RemoveTag(tag)
9192
    self.cfg.Update(self.target, feedback_fn)
9193

    
9194

    
9195
class LUTestDelay(NoHooksLU):
9196
  """Sleep for a specified amount of time.
9197

9198
  This LU sleeps on the master and/or nodes for a specified amount of
9199
  time.
9200

9201
  """
9202
  _OP_REQP = ["duration", "on_master", "on_nodes"]
9203
  REQ_BGL = False
9204

    
9205
  def ExpandNames(self):
9206
    """Expand names and set required locks.
9207

9208
    This expands the node list, if any.
9209

9210
    """
9211
    self.needed_locks = {}
9212
    if self.op.on_nodes:
9213
      # _GetWantedNodes can be used here, but is not always appropriate to use
9214
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9215
      # more information.
9216
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9217
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9218

    
9219
  def CheckPrereq(self):
9220
    """Check prerequisites.
9221

9222
    """
9223

    
9224
  def Exec(self, feedback_fn):
9225
    """Do the actual sleep.
9226

9227
    """
9228
    if self.op.on_master:
9229
      if not utils.TestDelay(self.op.duration):
9230
        raise errors.OpExecError("Error during master delay test")
9231
    if self.op.on_nodes:
9232
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9233
      for node, node_result in result.items():
9234
        node_result.Raise("Failure during rpc call to node %s" % node)
9235

    
9236

    
9237
class IAllocator(object):
9238
  """IAllocator framework.
9239

9240
  An IAllocator instance has three sets of attributes:
9241
    - cfg that is needed to query the cluster
9242
    - input data (all members of the _KEYS class attribute are required)
9243
    - four buffer attributes (in|out_data|text), that represent the
9244
      input (to the external script) in text and data structure format,
9245
      and the output from it, again in two formats
9246
    - the result variables from the script (success, info, nodes) for
9247
      easy usage
9248

9249
  """
9250
  # pylint: disable-msg=R0902
9251
  # lots of instance attributes
9252
  _ALLO_KEYS = [
9253
    "name", "mem_size", "disks", "disk_template",
9254
    "os", "tags", "nics", "vcpus", "hypervisor",
9255
    ]
9256
  _RELO_KEYS = [
9257
    "name", "relocate_from",
9258
    ]
9259
  _EVAC_KEYS = [
9260
    "evac_nodes",
9261
    ]
9262

    
9263
  def __init__(self, cfg, rpc, mode, **kwargs):
9264
    self.cfg = cfg
9265
    self.rpc = rpc
9266
    # init buffer variables
9267
    self.in_text = self.out_text = self.in_data = self.out_data = None
9268
    # init all input fields so that pylint is happy
9269
    self.mode = mode
9270
    self.mem_size = self.disks = self.disk_template = None
9271
    self.os = self.tags = self.nics = self.vcpus = None
9272
    self.hypervisor = None
9273
    self.relocate_from = None
9274
    self.name = None
9275
    self.evac_nodes = None
9276
    # computed fields
9277
    self.required_nodes = None
9278
    # init result fields
9279
    self.success = self.info = self.result = None
9280
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9281
      keyset = self._ALLO_KEYS
9282
      fn = self._AddNewInstance
9283
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9284
      keyset = self._RELO_KEYS
9285
      fn = self._AddRelocateInstance
9286
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9287
      keyset = self._EVAC_KEYS
9288
      fn = self._AddEvacuateNodes
9289
    else:
9290
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9291
                                   " IAllocator" % self.mode)
9292
    for key in kwargs:
9293
      if key not in keyset:
9294
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9295
                                     " IAllocator" % key)
9296
      setattr(self, key, kwargs[key])
9297

    
9298
    for key in keyset:
9299
      if key not in kwargs:
9300
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9301
                                     " IAllocator" % key)
9302
    self._BuildInputData(fn)
9303

    
9304
  def _ComputeClusterData(self):
9305
    """Compute the generic allocator input data.
9306

9307
    This is the data that is independent of the actual operation.
9308

9309
    """
9310
    cfg = self.cfg
9311
    cluster_info = cfg.GetClusterInfo()
9312
    # cluster data
9313
    data = {
9314
      "version": constants.IALLOCATOR_VERSION,
9315
      "cluster_name": cfg.GetClusterName(),
9316
      "cluster_tags": list(cluster_info.GetTags()),
9317
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9318
      # we don't have job IDs
9319
      }
9320
    iinfo = cfg.GetAllInstancesInfo().values()
9321
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9322

    
9323
    # node data
9324
    node_results = {}
9325
    node_list = cfg.GetNodeList()
9326

    
9327
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9328
      hypervisor_name = self.hypervisor
9329
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9330
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9331
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9332
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9333

    
9334
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9335
                                        hypervisor_name)
9336
    node_iinfo = \
9337
      self.rpc.call_all_instances_info(node_list,
9338
                                       cluster_info.enabled_hypervisors)
9339
    for nname, nresult in node_data.items():
9340
      # first fill in static (config-based) values
9341
      ninfo = cfg.GetNodeInfo(nname)
9342
      pnr = {
9343
        "tags": list(ninfo.GetTags()),
9344
        "primary_ip": ninfo.primary_ip,
9345
        "secondary_ip": ninfo.secondary_ip,
9346
        "offline": ninfo.offline,
9347
        "drained": ninfo.drained,
9348
        "master_candidate": ninfo.master_candidate,
9349
        }
9350

    
9351
      if not (ninfo.offline or ninfo.drained):
9352
        nresult.Raise("Can't get data for node %s" % nname)
9353
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9354
                                nname)
9355
        remote_info = nresult.payload
9356

    
9357
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9358
                     'vg_size', 'vg_free', 'cpu_total']:
9359
          if attr not in remote_info:
9360
            raise errors.OpExecError("Node '%s' didn't return attribute"
9361
                                     " '%s'" % (nname, attr))
9362
          if not isinstance(remote_info[attr], int):
9363
            raise errors.OpExecError("Node '%s' returned invalid value"
9364
                                     " for '%s': %s" %
9365
                                     (nname, attr, remote_info[attr]))
9366
        # compute memory used by primary instances
9367
        i_p_mem = i_p_up_mem = 0
9368
        for iinfo, beinfo in i_list:
9369
          if iinfo.primary_node == nname:
9370
            i_p_mem += beinfo[constants.BE_MEMORY]
9371
            if iinfo.name not in node_iinfo[nname].payload:
9372
              i_used_mem = 0
9373
            else:
9374
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9375
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9376
            remote_info['memory_free'] -= max(0, i_mem_diff)
9377

    
9378
            if iinfo.admin_up:
9379
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9380

    
9381
        # compute memory used by instances
9382
        pnr_dyn = {
9383
          "total_memory": remote_info['memory_total'],
9384
          "reserved_memory": remote_info['memory_dom0'],
9385
          "free_memory": remote_info['memory_free'],
9386
          "total_disk": remote_info['vg_size'],
9387
          "free_disk": remote_info['vg_free'],
9388
          "total_cpus": remote_info['cpu_total'],
9389
          "i_pri_memory": i_p_mem,
9390
          "i_pri_up_memory": i_p_up_mem,
9391
          }
9392
        pnr.update(pnr_dyn)
9393

    
9394
      node_results[nname] = pnr
9395
    data["nodes"] = node_results
9396

    
9397
    # instance data
9398
    instance_data = {}
9399
    for iinfo, beinfo in i_list:
9400
      nic_data = []
9401
      for nic in iinfo.nics:
9402
        filled_params = objects.FillDict(
9403
            cluster_info.nicparams[constants.PP_DEFAULT],
9404
            nic.nicparams)
9405
        nic_dict = {"mac": nic.mac,
9406
                    "ip": nic.ip,
9407
                    "mode": filled_params[constants.NIC_MODE],
9408
                    "link": filled_params[constants.NIC_LINK],
9409
                   }
9410
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
9411
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
9412
        nic_data.append(nic_dict)
9413
      pir = {
9414
        "tags": list(iinfo.GetTags()),
9415
        "admin_up": iinfo.admin_up,
9416
        "vcpus": beinfo[constants.BE_VCPUS],
9417
        "memory": beinfo[constants.BE_MEMORY],
9418
        "os": iinfo.os,
9419
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
9420
        "nics": nic_data,
9421
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
9422
        "disk_template": iinfo.disk_template,
9423
        "hypervisor": iinfo.hypervisor,
9424
        }
9425
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
9426
                                                 pir["disks"])
9427
      instance_data[iinfo.name] = pir
9428

    
9429
    data["instances"] = instance_data
9430

    
9431
    self.in_data = data
9432

    
9433
  def _AddNewInstance(self):
9434
    """Add new instance data to allocator structure.
9435

9436
    This in combination with _AllocatorGetClusterData will create the
9437
    correct structure needed as input for the allocator.
9438

9439
    The checks for the completeness of the opcode must have already been
9440
    done.
9441

9442
    """
9443
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
9444

    
9445
    if self.disk_template in constants.DTS_NET_MIRROR:
9446
      self.required_nodes = 2
9447
    else:
9448
      self.required_nodes = 1
9449
    request = {
9450
      "name": self.name,
9451
      "disk_template": self.disk_template,
9452
      "tags": self.tags,
9453
      "os": self.os,
9454
      "vcpus": self.vcpus,
9455
      "memory": self.mem_size,
9456
      "disks": self.disks,
9457
      "disk_space_total": disk_space,
9458
      "nics": self.nics,
9459
      "required_nodes": self.required_nodes,
9460
      }
9461
    return request
9462

    
9463
  def _AddRelocateInstance(self):
9464
    """Add relocate instance data to allocator structure.
9465

9466
    This in combination with _IAllocatorGetClusterData will create the
9467
    correct structure needed as input for the allocator.
9468

9469
    The checks for the completeness of the opcode must have already been
9470
    done.
9471

9472
    """
9473
    instance = self.cfg.GetInstanceInfo(self.name)
9474
    if instance is None:
9475
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
9476
                                   " IAllocator" % self.name)
9477

    
9478
    if instance.disk_template not in constants.DTS_NET_MIRROR:
9479
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
9480
                                 errors.ECODE_INVAL)
9481

    
9482
    if len(instance.secondary_nodes) != 1:
9483
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
9484
                                 errors.ECODE_STATE)
9485

    
9486
    self.required_nodes = 1
9487
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
9488
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
9489

    
9490
    request = {
9491
      "name": self.name,
9492
      "disk_space_total": disk_space,
9493
      "required_nodes": self.required_nodes,
9494
      "relocate_from": self.relocate_from,
9495
      }
9496
    return request
9497

    
9498
  def _AddEvacuateNodes(self):
9499
    """Add evacuate nodes data to allocator structure.
9500

9501
    """
9502
    request = {
9503
      "evac_nodes": self.evac_nodes
9504
      }
9505
    return request
9506

    
9507
  def _BuildInputData(self, fn):
9508
    """Build input data structures.
9509

9510
    """
9511
    self._ComputeClusterData()
9512

    
9513
    request = fn()
9514
    request["type"] = self.mode
9515
    self.in_data["request"] = request
9516

    
9517
    self.in_text = serializer.Dump(self.in_data)
9518

    
9519
  def Run(self, name, validate=True, call_fn=None):
9520
    """Run an instance allocator and return the results.
9521

9522
    """
9523
    if call_fn is None:
9524
      call_fn = self.rpc.call_iallocator_runner
9525

    
9526
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
9527
    result.Raise("Failure while running the iallocator script")
9528

    
9529
    self.out_text = result.payload
9530
    if validate:
9531
      self._ValidateResult()
9532

    
9533
  def _ValidateResult(self):
9534
    """Process the allocator results.
9535

9536
    This will process and if successful save the result in
9537
    self.out_data and the other parameters.
9538

9539
    """
9540
    try:
9541
      rdict = serializer.Load(self.out_text)
9542
    except Exception, err:
9543
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
9544

    
9545
    if not isinstance(rdict, dict):
9546
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
9547

    
9548
    # TODO: remove backwards compatiblity in later versions
9549
    if "nodes" in rdict and "result" not in rdict:
9550
      rdict["result"] = rdict["nodes"]
9551
      del rdict["nodes"]
9552

    
9553
    for key in "success", "info", "result":
9554
      if key not in rdict:
9555
        raise errors.OpExecError("Can't parse iallocator results:"
9556
                                 " missing key '%s'" % key)
9557
      setattr(self, key, rdict[key])
9558

    
9559
    if not isinstance(rdict["result"], list):
9560
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
9561
                               " is not a list")
9562
    self.out_data = rdict
9563

    
9564

    
9565
class LUTestAllocator(NoHooksLU):
9566
  """Run allocator tests.
9567

9568
  This LU runs the allocator tests
9569

9570
  """
9571
  _OP_REQP = ["direction", "mode", "name"]
9572

    
9573
  def CheckPrereq(self):
9574
    """Check prerequisites.
9575

9576
    This checks the opcode parameters depending on the director and mode test.
9577

9578
    """
9579
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9580
      for attr in ["name", "mem_size", "disks", "disk_template",
9581
                   "os", "tags", "nics", "vcpus"]:
9582
        if not hasattr(self.op, attr):
9583
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
9584
                                     attr, errors.ECODE_INVAL)
9585
      iname = self.cfg.ExpandInstanceName(self.op.name)
9586
      if iname is not None:
9587
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
9588
                                   iname, errors.ECODE_EXISTS)
9589
      if not isinstance(self.op.nics, list):
9590
        raise errors.OpPrereqError("Invalid parameter 'nics'",
9591
                                   errors.ECODE_INVAL)
9592
      for row in self.op.nics:
9593
        if (not isinstance(row, dict) or
9594
            "mac" not in row or
9595
            "ip" not in row or
9596
            "bridge" not in row):
9597
          raise errors.OpPrereqError("Invalid contents of the 'nics'"
9598
                                     " parameter", errors.ECODE_INVAL)
9599
      if not isinstance(self.op.disks, list):
9600
        raise errors.OpPrereqError("Invalid parameter 'disks'",
9601
                                   errors.ECODE_INVAL)
9602
      for row in self.op.disks:
9603
        if (not isinstance(row, dict) or
9604
            "size" not in row or
9605
            not isinstance(row["size"], int) or
9606
            "mode" not in row or
9607
            row["mode"] not in ['r', 'w']):
9608
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
9609
                                     " parameter", errors.ECODE_INVAL)
9610
      if not hasattr(self.op, "hypervisor") or self.op.hypervisor is None:
9611
        self.op.hypervisor = self.cfg.GetHypervisorType()
9612
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9613
      if not hasattr(self.op, "name"):
9614
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input",
9615
                                   errors.ECODE_INVAL)
9616
      fname = _ExpandInstanceName(self.cfg, self.op.name)
9617
      self.op.name = fname
9618
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
9619
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9620
      if not hasattr(self.op, "evac_nodes"):
9621
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
9622
                                   " opcode input", errors.ECODE_INVAL)
9623
    else:
9624
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
9625
                                 self.op.mode, errors.ECODE_INVAL)
9626

    
9627
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
9628
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
9629
        raise errors.OpPrereqError("Missing allocator name",
9630
                                   errors.ECODE_INVAL)
9631
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
9632
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
9633
                                 self.op.direction, errors.ECODE_INVAL)
9634

    
9635
  def Exec(self, feedback_fn):
9636
    """Run the allocator test.
9637

9638
    """
9639
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
9640
      ial = IAllocator(self.cfg, self.rpc,
9641
                       mode=self.op.mode,
9642
                       name=self.op.name,
9643
                       mem_size=self.op.mem_size,
9644
                       disks=self.op.disks,
9645
                       disk_template=self.op.disk_template,
9646
                       os=self.op.os,
9647
                       tags=self.op.tags,
9648
                       nics=self.op.nics,
9649
                       vcpus=self.op.vcpus,
9650
                       hypervisor=self.op.hypervisor,
9651
                       )
9652
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
9653
      ial = IAllocator(self.cfg, self.rpc,
9654
                       mode=self.op.mode,
9655
                       name=self.op.name,
9656
                       relocate_from=list(self.relocate_from),
9657
                       )
9658
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
9659
      ial = IAllocator(self.cfg, self.rpc,
9660
                       mode=self.op.mode,
9661
                       evac_nodes=self.op.evac_nodes)
9662
    else:
9663
      raise errors.ProgrammerError("Uncatched mode %s in"
9664
                                   " LUTestAllocator.Exec", self.op.mode)
9665

    
9666
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
9667
      result = ial.in_text
9668
    else:
9669
      ial.Run(self.op.allocator, validate=False)
9670
      result = ial.out_text
9671
    return result